var MX=Object.defineProperty;var D8=n=>{throw TypeError(n)};var zX=(n,e,t)=>e in n?MX(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ve=(n,e,t)=>zX(n,typeof e!="symbol"?e+"":e,t),EE=(n,e,t)=>e.has(n)||D8("Cannot "+t);var h=(n,e,t)=>(EE(n,e,"read from private field"),t?t.call(n):e.get(n)),N=(n,e,t)=>e.has(n)?D8("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),R=(n,e,t,r)=>(EE(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),q=(n,e,t)=>(EE(n,e,"access private method"),t);var Gi=(n,e,t,r)=>({set _(i){R(n,e,i,t)},get _(){return h(n,e,r)}});function OX(n,e){for(var t=0;tr[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function t(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=t(i);fetch(i.href,o)}})();function a7(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var l7={exports:{}},tF={},d7={exports:{}},nr={};/** * @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 W_=Symbol.for("react.element"),LX=Symbol.for("react.portal"),NX=Symbol.for("react.fragment"),WX=Symbol.for("react.strict_mode"),UX=Symbol.for("react.profiler"),HX=Symbol.for("react.provider"),qX=Symbol.for("react.context"),VX=Symbol.for("react.forward_ref"),GX=Symbol.for("react.suspense"),KX=Symbol.for("react.memo"),XX=Symbol.for("react.lazy"),E8=Symbol.iterator;function YX(n){return n===null||typeof n!="object"?null:(n=E8&&n[E8]||n["@@iterator"],typeof n=="function"?n:null)}var c7={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},u7=Object.assign,h7={};function c1(n,e,t){this.props=n,this.context=e,this.refs=h7,this.updater=t||c7}c1.prototype.isReactComponent={};c1.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=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,n,e,"setState")};c1.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function f7(){}f7.prototype=c1.prototype;function jM(n,e,t){this.props=n,this.context=e,this.refs=h7,this.updater=t||c7}var kM=jM.prototype=new f7;kM.constructor=jM;u7(kM,c1.prototype);kM.isPureReactComponent=!0;var P8=Array.isArray,p7=Object.prototype.hasOwnProperty,_M={current:null},g7={key:!0,ref:!0,__self:!0,__source:!0};function m7(n,e,t){var r,i={},o=null,a=null;if(e!=null)for(r in e.ref!==void 0&&(a=e.ref),e.key!==void 0&&(o=""+e.key),e)p7.call(e,r)&&!g7.hasOwnProperty(r)&&(i[r]=e[r]);var l=arguments.length-2;if(l===1)i.children=t;else if(1>>1,re=H[te];if(0>>1;tei(ne,G))yei(ke,ne)?(H[te]=ke,H[ye]=G,te=ye):(H[te]=ne,H[J]=G,te=J);else if(yei(ke,G))H[te]=ke,H[ye]=G,te=ye;else break e}}return z}function i(H,z){var G=H.sortIndex-z.sortIndex;return G!==0?G:H.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;n.unstable_now=function(){return o.now()}}else{var a=Date,l=a.now();n.unstable_now=function(){return a.now()-l}}var d=[],c=[],u=1,f=null,p=3,g=!1,m=!1,y=!1,v=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function S(H){for(var z=t(c);z!==null;){if(z.callback===null)r(c);else if(z.startTime<=H)r(c),z.sortIndex=z.expirationTime,e(d,z);else break;z=t(c)}}function _(H){if(y=!1,S(H),!m)if(t(d)!==null)m=!0,M(b);else{var z=t(c);z!==null&&I(_,z.startTime-H)}}function b(H,z){m=!1,y&&(y=!1,x(F),F=-1),g=!0;var G=p;try{for(S(z),f=t(d);f!==null&&(!(f.expirationTime>z)||H&&!P());){var te=f.callback;if(typeof te=="function"){f.callback=null,p=f.priorityLevel;var re=te(f.expirationTime<=z);z=n.unstable_now(),typeof re=="function"?f.callback=re:f===t(d)&&r(d),S(z)}else r(d);f=t(d)}if(f!==null)var me=!0;else{var J=t(c);J!==null&&I(_,J.startTime-z),me=!1}return me}finally{f=null,p=G,g=!1}}var C=!1,T=null,F=-1,A=5,D=-1;function P(){return!(n.unstable_now()-DH||125te?(H.sortIndex=G,e(c,H),t(d)===null&&H===t(c)&&(y?(x(F),F=-1):y=!0,I(_,G-te))):(H.sortIndex=re,e(d,H),m||g||(m=!0,M(b))),H},n.unstable_shouldYield=P,n.unstable_wrapCallback=function(H){var z=p;return function(){var G=p;p=z;try{return H.apply(this,arguments)}finally{p=G}}}})(w7);v7.exports=w7;var aY=v7.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 lY=k,Xl=aY;function ft(n){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+n,t=1;t"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),eR=Object.prototype.hasOwnProperty,dY=/^[: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]*$/,B8={},I8={};function cY(n){return eR.call(I8,n)?!0:eR.call(B8,n)?!1:dY.test(n)?I8[n]=!0:(B8[n]=!0,!1)}function uY(n,e,t,r){if(t!==null&&t.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:t!==null?!t.acceptsBooleans:(n=n.toLowerCase().slice(0,5),n!=="data-"&&n!=="aria-");default:return!1}}function hY(n,e,t,r){if(e===null||typeof e>"u"||uY(n,e,t,r))return!0;if(r)return!1;if(t!==null)switch(t.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Da(n,e,t,r,i,o,a){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=n,this.type=e,this.sanitizeURL=o,this.removeEmptyString=a}var zo={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(n){zo[n]=new Da(n,0,!1,n,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(n){var e=n[0];zo[e]=new Da(e,1,!1,n[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(n){zo[n]=new Da(n,2,!1,n.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(n){zo[n]=new Da(n,2,!1,n,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(n){zo[n]=new Da(n,3,!1,n.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(n){zo[n]=new Da(n,3,!0,n,null,!1,!1)});["capture","download"].forEach(function(n){zo[n]=new Da(n,4,!1,n,null,!1,!1)});["cols","rows","size","span"].forEach(function(n){zo[n]=new Da(n,6,!1,n,null,!1,!1)});["rowSpan","start"].forEach(function(n){zo[n]=new Da(n,5,!1,n.toLowerCase(),null,!1,!1)});var AM=/[\-:]([a-z])/g;function TM(n){return n[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(n){var e=n.replace(AM,TM);zo[e]=new Da(e,1,!1,n,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(n){var e=n.replace(AM,TM);zo[e]=new Da(e,1,!1,n,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(n){var e=n.replace(AM,TM);zo[e]=new Da(e,1,!1,n,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(n){zo[n]=new Da(n,1,!1,n.toLowerCase(),null,!1,!1)});zo.xlinkHref=new Da("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(n){zo[n]=new Da(n,1,!1,n.toLowerCase(),null,!0,!0)});function FM(n,e,t,r){var i=zo.hasOwnProperty(e)?zo[e]:null;(i!==null?i.type!==0:r||!(2l||i[a]!==o[l]){var d=` `+i[a].replace(" at new "," at ");return n.displayName&&d.includes("")&&(d=d.replace("",n.displayName)),d}while(1<=a&&0<=l);break}}}finally{BE=!1,Error.prepareStackTrace=t}return(n=n?n.displayName||n.name:"")?Xw(n):""}function fY(n){switch(n.tag){case 5:return Xw(n.type);case 16:return Xw("Lazy");case 13:return Xw("Suspense");case 19:return Xw("SuspenseList");case 0:case 2:case 15:return n=IE(n.type,!1),n;case 11:return n=IE(n.type.render,!1),n;case 1:return n=IE(n.type,!0),n;default:return""}}function iR(n){if(n==null)return null;if(typeof n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n;switch(n){case Rx:return"Fragment";case Px:return"Portal";case tR:return"Profiler";case DM:return"StrictMode";case nR:return"Suspense";case rR:return"SuspenseList"}if(typeof n=="object")switch(n.$$typeof){case k7:return(n.displayName||"Context")+".Consumer";case j7:return(n._context.displayName||"Context")+".Provider";case EM:var e=n.render;return n=n.displayName,n||(n=e.displayName||e.name||"",n=n!==""?"ForwardRef("+n+")":"ForwardRef"),n;case PM:return e=n.displayName||null,e!==null?e:iR(n.type)||"Memo";case ep:e=n._payload,n=n._init;try{return iR(n(e))}catch{}}return null}function pY(n){var e=n.type;switch(n.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return n=e.render,n=n.displayName||n.name||"",e.displayName||(n!==""?"ForwardRef("+n+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return iR(e);case 8:return e===DM?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function Bg(n){switch(typeof n){case"boolean":case"number":case"string":case"undefined":return n;case"object":return n;default:return""}}function C7(n){var e=n.type;return(n=n.nodeName)&&n.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function gY(n){var e=C7(n)?"checked":"value",t=Object.getOwnPropertyDescriptor(n.constructor.prototype,e),r=""+n[e];if(!n.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var i=t.get,o=t.set;return Object.defineProperty(n,e,{configurable:!0,get:function(){return i.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(n,e,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){n._valueTracker=null,delete n[e]}}}}function ZC(n){n._valueTracker||(n._valueTracker=gY(n))}function A7(n){if(!n)return!1;var e=n._valueTracker;if(!e)return!0;var t=e.getValue(),r="";return n&&(r=C7(n)?n.checked?"true":"false":n.value),n=r,n!==t?(e.setValue(n),!0):!1}function gA(n){if(n=n||(typeof document<"u"?document:void 0),typeof n>"u")return null;try{return n.activeElement||n.body}catch{return n.body}}function sR(n,e){var t=e.checked;return ns({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??n._wrapperState.initialChecked})}function z8(n,e){var t=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;t=Bg(e.value!=null?e.value:t),n._wrapperState={initialChecked:r,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function T7(n,e){e=e.checked,e!=null&&FM(n,"checked",e,!1)}function oR(n,e){T7(n,e);var t=Bg(e.value),r=e.type;if(t!=null)r==="number"?(t===0&&n.value===""||n.value!=t)&&(n.value=""+t):n.value!==""+t&&(n.value=""+t);else if(r==="submit"||r==="reset"){n.removeAttribute("value");return}e.hasOwnProperty("value")?aR(n,e.type,t):e.hasOwnProperty("defaultValue")&&aR(n,e.type,Bg(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(n.defaultChecked=!!e.defaultChecked)}function O8(n,e,t){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+n._wrapperState.initialValue,t||e===n.value||(n.value=e),n.defaultValue=e}t=n.name,t!==""&&(n.name=""),n.defaultChecked=!!n._wrapperState.initialChecked,t!==""&&(n.name=t)}function aR(n,e,t){(e!=="number"||gA(n.ownerDocument)!==n)&&(t==null?n.defaultValue=""+n._wrapperState.initialValue:n.defaultValue!==""+t&&(n.defaultValue=""+t))}var Yw=Array.isArray;function Zx(n,e,t,r){if(n=n.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=JC.firstChild;n.firstChild;)n.removeChild(n.firstChild);for(;e.firstChild;)n.appendChild(e.firstChild)}});function lj(n,e){if(e){var t=n.firstChild;if(t&&t===n.lastChild&&t.nodeType===3){t.nodeValue=e;return}}n.textContent=e}var RS={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},mY=["Webkit","ms","Moz","O"];Object.keys(RS).forEach(function(n){mY.forEach(function(e){e=e+n.charAt(0).toUpperCase()+n.substring(1),RS[e]=RS[n]})});function P7(n,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||RS.hasOwnProperty(n)&&RS[n]?(""+e).trim():e+"px"}function R7(n,e){n=n.style;for(var t in e)if(e.hasOwnProperty(t)){var r=t.indexOf("--")===0,i=P7(t,e[t],r);t==="float"&&(t="cssFloat"),r?n.setProperty(t,i):n[t]=i}}var yY=ns({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 cR(n,e){if(e){if(yY[n]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(ft(137,n));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(ft(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(ft(61))}if(e.style!=null&&typeof e.style!="object")throw Error(ft(62))}}function uR(n,e){if(n.indexOf("-")===-1)return typeof e.is=="string";switch(n){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 hR=null;function RM(n){return n=n.target||n.srcElement||window,n.correspondingUseElement&&(n=n.correspondingUseElement),n.nodeType===3?n.parentNode:n}var fR=null,Jx=null,eb=null;function W8(n){if(n=q_(n)){if(typeof fR!="function")throw Error(ft(280));var e=n.stateNode;e&&(e=aF(e),fR(n.stateNode,n.type,e))}}function B7(n){Jx?eb?eb.push(n):eb=[n]:Jx=n}function I7(){if(Jx){var n=Jx,e=eb;if(eb=Jx=null,W8(n),e)for(n=0;n>>=0,n===0?32:31-(TY(n)/FY|0)|0}var e2=64,t2=4194304;function Qw(n){switch(n&-n){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 n&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return n&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return n}}function bA(n,e){var t=n.pendingLanes;if(t===0)return 0;var r=0,i=n.suspendedLanes,o=n.pingedLanes,a=t&268435455;if(a!==0){var l=a&~i;l!==0?r=Qw(l):(o&=a,o!==0&&(r=Qw(o)))}else a=t&~i,a!==0?r=Qw(a):o!==0&&(r=Qw(o));if(r===0)return 0;if(e!==0&&e!==r&&!(e&i)&&(i=r&-r,o=e&-e,i>=o||i===16&&(o&4194240)!==0))return e;if(r&4&&(r|=t&16),e=n.entangledLanes,e!==0)for(n=n.entanglements,e&=r;0t;t++)e.push(n);return e}function U_(n,e,t){n.pendingLanes|=e,e!==536870912&&(n.suspendedLanes=0,n.pingedLanes=0),n=n.eventTimes,e=31-Tc(e),n[e]=t}function RY(n,e){var t=n.pendingLanes&~e;n.pendingLanes=e,n.suspendedLanes=0,n.pingedLanes=0,n.expiredLanes&=e,n.mutableReadLanes&=e,n.entangledLanes&=e,e=n.entanglements;var r=n.eventTimes;for(n=n.expirationTimes;0=IS),Q8=" ",$8=!1;function tW(n,e){switch(n){case"keyup":return aQ.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function nW(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Bx=!1;function dQ(n,e){switch(n){case"compositionend":return nW(e);case"keypress":return e.which!==32?null:($8=!0,Q8);case"textInput":return n=e.data,n===Q8&&$8?null:n;default:return null}}function cQ(n,e){if(Bx)return n==="compositionend"||!WM&&tW(n,e)?(n=J7(),r5=OM=dg=null,Bx=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:t,offset:e-n};n=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=tz(t)}}function oW(n,e){return n&&e?n===e?!0:n&&n.nodeType===3?!1:e&&e.nodeType===3?oW(n,e.parentNode):"contains"in n?n.contains(e):n.compareDocumentPosition?!!(n.compareDocumentPosition(e)&16):!1:!1}function aW(){for(var n=window,e=gA();e instanceof n.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)n=e.contentWindow;else break;e=gA(n.document)}return e}function UM(n){var e=n&&n.nodeName&&n.nodeName.toLowerCase();return e&&(e==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||e==="textarea"||n.contentEditable==="true")}function bQ(n){var e=aW(),t=n.focusedElem,r=n.selectionRange;if(e!==t&&t&&t.ownerDocument&&oW(t.ownerDocument.documentElement,t)){if(r!==null&&UM(t)){if(e=r.start,n=r.end,n===void 0&&(n=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(n,t.value.length);else if(n=(e=t.ownerDocument||document)&&e.defaultView||window,n.getSelection){n=n.getSelection();var i=t.textContent.length,o=Math.min(r.start,i);r=r.end===void 0?o:Math.min(r.end,i),!n.extend&&o>r&&(i=r,r=o,o=i),i=nz(t,o);var a=nz(t,r);i&&a&&(n.rangeCount!==1||n.anchorNode!==i.node||n.anchorOffset!==i.offset||n.focusNode!==a.node||n.focusOffset!==a.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),n.removeAllRanges(),o>r?(n.addRange(e),n.extend(a.node,a.offset)):(e.setEnd(a.node,a.offset),n.addRange(e)))}}for(e=[],n=t;n=n.parentNode;)n.nodeType===1&&e.push({element:n,left:n.scrollLeft,top:n.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,Ix=null,bR=null,zS=null,vR=!1;function rz(n,e,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;vR||Ix==null||Ix!==gA(r)||(r=Ix,"selectionStart"in r&&UM(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),zS&&pj(zS,r)||(zS=r,r=SA(bR,"onSelect"),0Ox||(n.current=CR[Ox],CR[Ox]=null,Ox--)}function yi(n,e){Ox++,CR[Ox]=n.current,n.current=e}var Ig={},ia=qg(Ig),tl=qg(!1),d0=Ig;function Qv(n,e){var t=n.type.contextTypes;if(!t)return Ig;var r=n.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in t)i[o]=e[o];return r&&(n=n.stateNode,n.__reactInternalMemoizedUnmaskedChildContext=e,n.__reactInternalMemoizedMaskedChildContext=i),i}function nl(n){return n=n.childContextTypes,n!=null}function kA(){_i(tl),_i(ia)}function cz(n,e,t){if(ia.current!==Ig)throw Error(ft(168));yi(ia,e),yi(tl,t)}function mW(n,e,t){var r=n.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var i in r)if(!(i in e))throw Error(ft(108,pY(n)||"Unknown",i));return ns({},t,r)}function _A(n){return n=(n=n.stateNode)&&n.__reactInternalMemoizedMergedChildContext||Ig,d0=ia.current,yi(ia,n),yi(tl,tl.current),!0}function uz(n,e,t){var r=n.stateNode;if(!r)throw Error(ft(169));t?(n=mW(n,e,d0),r.__reactInternalMemoizedMergedChildContext=n,_i(tl),_i(ia),yi(ia,n)):_i(tl),yi(tl,t)}var bh=null,lF=!1,YE=!1;function yW(n){bh===null?bh=[n]:bh.push(n)}function EQ(n){lF=!0,yW(n)}function Vg(){if(!YE&&bh!==null){YE=!0;var n=0,e=$r;try{var t=bh;for($r=1;n>=a,i-=a,cf=1<<32-Tc(e)+i|t<F?(A=T,T=null):A=T.sibling;var D=p(x,T,S[F],_);if(D===null){T===null&&(T=A);break}n&&T&&D.alternate===null&&e(x,T),w=o(D,w,F),C===null?b=D:C.sibling=D,C=D,T=A}if(F===S.length)return t(x,T),Ii&&im(x,F),b;if(T===null){for(;FF?(A=T,T=null):A=T.sibling;var P=p(x,T,D.value,_);if(P===null){T===null&&(T=A);break}n&&T&&P.alternate===null&&e(x,T),w=o(P,w,F),C===null?b=P:C.sibling=P,C=P,T=A}if(D.done)return t(x,T),Ii&&im(x,F),b;if(T===null){for(;!D.done;F++,D=S.next())D=f(x,D.value,_),D!==null&&(w=o(D,w,F),C===null?b=D:C.sibling=D,C=D);return Ii&&im(x,F),b}for(T=r(x,T);!D.done;F++,D=S.next())D=g(T,x,F,D.value,_),D!==null&&(n&&D.alternate!==null&&T.delete(D.key===null?F:D.key),w=o(D,w,F),C===null?b=D:C.sibling=D,C=D);return n&&T.forEach(function(L){return e(x,L)}),Ii&&im(x,F),b}function v(x,w,S,_){if(typeof S=="object"&&S!==null&&S.type===Rx&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case $C:e:{for(var b=S.key,C=w;C!==null;){if(C.key===b){if(b=S.type,b===Rx){if(C.tag===7){t(x,C.sibling),w=i(C,S.props.children),w.return=x,x=w;break e}}else if(C.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===ep&&pz(b)===C.type){t(x,C.sibling),w=i(C,S.props),w.ref=_w(x,C,S),w.return=x,x=w;break e}t(x,C);break}else e(x,C);C=C.sibling}S.type===Rx?(w=s0(S.props.children,x.mode,_,S.key),w.return=x,x=w):(_=u5(S.type,S.key,S.props,null,x.mode,_),_.ref=_w(x,w,S),_.return=x,x=_)}return a(x);case Px:e:{for(C=S.key;w!==null;){if(w.key===C)if(w.tag===4&&w.stateNode.containerInfo===S.containerInfo&&w.stateNode.implementation===S.implementation){t(x,w.sibling),w=i(w,S.children||[]),w.return=x,x=w;break e}else{t(x,w);break}else e(x,w);w=w.sibling}w=rP(S,x.mode,_),w.return=x,x=w}return a(x);case ep:return C=S._init,v(x,w,C(S._payload),_)}if(Yw(S))return m(x,w,S,_);if(vw(S))return y(x,w,S,_);l2(x,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,w!==null&&w.tag===6?(t(x,w.sibling),w=i(w,S),w.return=x,x=w):(t(x,w),w=nP(S,x.mode,_),w.return=x,x=w),a(x)):t(x,w)}return v}var Zv=wW(!0),SW=wW(!1),TA=qg(null),FA=null,Wx=null,GM=null;function KM(){GM=Wx=FA=null}function XM(n){var e=TA.current;_i(TA),n._currentValue=e}function FR(n,e,t){for(;n!==null;){var r=n.alternate;if((n.childLanes&e)!==e?(n.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),n===t)break;n=n.return}}function nb(n,e){FA=n,GM=Wx=null,n=n.dependencies,n!==null&&n.firstContext!==null&&(n.lanes&e&&(Ja=!0),n.firstContext=null)}function Od(n){var e=n._currentValue;if(GM!==n)if(n={context:n,memoizedValue:e,next:null},Wx===null){if(FA===null)throw Error(ft(308));Wx=n,FA.dependencies={lanes:0,firstContext:n}}else Wx=Wx.next=n;return e}var mm=null;function YM(n){mm===null?mm=[n]:mm.push(n)}function jW(n,e,t,r){var i=e.interleaved;return i===null?(t.next=t,YM(e)):(t.next=i.next,i.next=t),e.interleaved=t,kf(n,r)}function kf(n,e){n.lanes|=e;var t=n.alternate;for(t!==null&&(t.lanes|=e),t=n,n=n.return;n!==null;)n.childLanes|=e,t=n.alternate,t!==null&&(t.childLanes|=e),t=n,n=n.return;return t.tag===3?t.stateNode:null}var tp=!1;function QM(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function kW(n,e){n=n.updateQueue,e.updateQueue===n&&(e.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,effects:n.effects})}function ff(n,e){return{eventTime:n,lane:e,tag:0,payload:null,callback:null,next:null}}function Sg(n,e,t){var r=n.updateQueue;if(r===null)return null;if(r=r.shared,jr&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,kf(n,t)}return i=r.interleaved,i===null?(e.next=e,YM(r)):(e.next=i.next,i.next=e),r.interleaved=e,kf(n,t)}function s5(n,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var r=e.lanes;r&=n.pendingLanes,t|=r,e.lanes=t,IM(n,t)}}function gz(n,e){var t=n.updateQueue,r=n.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var i=null,o=null;if(t=t.firstBaseUpdate,t!==null){do{var a={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};o===null?i=o=a:o=o.next=a,t=t.next}while(t!==null);o===null?i=o=e:o=o.next=e}else i=o=e;t={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:r.shared,effects:r.effects},n.updateQueue=t;return}n=t.lastBaseUpdate,n===null?t.firstBaseUpdate=e:n.next=e,t.lastBaseUpdate=e}function DA(n,e,t,r){var i=n.updateQueue;tp=!1;var o=i.firstBaseUpdate,a=i.lastBaseUpdate,l=i.shared.pending;if(l!==null){i.shared.pending=null;var d=l,c=d.next;d.next=null,a===null?o=c:a.next=c,a=d;var u=n.alternate;u!==null&&(u=u.updateQueue,l=u.lastBaseUpdate,l!==a&&(l===null?u.firstBaseUpdate=c:l.next=c,u.lastBaseUpdate=d))}if(o!==null){var f=i.baseState;a=0,u=c=d=null,l=o;do{var p=l.lane,g=l.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:g,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var m=n,y=l;switch(p=e,g=t,y.tag){case 1:if(m=y.payload,typeof m=="function"){f=m.call(g,f,p);break e}f=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=y.payload,p=typeof m=="function"?m.call(g,f,p):m,p==null)break e;f=ns({},f,p);break e;case 2:tp=!0}}l.callback!==null&&l.lane!==0&&(n.flags|=64,p=i.effects,p===null?i.effects=[l]:p.push(l))}else g={eventTime:g,lane:p,tag:l.tag,payload:l.payload,callback:l.callback,next:null},u===null?(c=u=g,d=f):u=u.next=g,a|=p;if(l=l.next,l===null){if(l=i.shared.pending,l===null)break;p=l,l=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(!0);if(u===null&&(d=f),i.baseState=d,i.firstBaseUpdate=c,i.lastBaseUpdate=u,e=i.shared.interleaved,e!==null){i=e;do a|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);h0|=a,n.lanes=a,n.memoizedState=f}}function mz(n,e,t){if(n=e.effects,e.effects=null,n!==null)for(e=0;et?t:4,n(!0);var r=$E.transition;$E.transition={};try{n(!1),e()}finally{$r=t,$E.transition=r}}function WW(){return Ld().memoizedState}function IQ(n,e,t){var r=kg(n);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},UW(n))HW(e,t);else if(t=jW(n,e,t,r),t!==null){var i=_a();Fc(t,n,r,i),qW(t,e,r)}}function MQ(n,e,t){var r=kg(n),i={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(UW(n))HW(e,i);else{var o=n.alternate;if(n.lanes===0&&(o===null||o.lanes===0)&&(o=e.lastRenderedReducer,o!==null))try{var a=e.lastRenderedState,l=o(a,t);if(i.hasEagerState=!0,i.eagerState=l,Ec(l,a)){var d=e.interleaved;d===null?(i.next=i,YM(e)):(i.next=d.next,d.next=i),e.interleaved=i;return}}catch{}finally{}t=jW(n,e,i,r),t!==null&&(i=_a(),Fc(t,n,r,i),qW(t,e,r))}}function UW(n){var e=n.alternate;return n===Ji||e!==null&&e===Ji}function HW(n,e){OS=PA=!0;var t=n.pending;t===null?e.next=e:(e.next=t.next,t.next=e),n.pending=e}function qW(n,e,t){if(t&4194240){var r=e.lanes;r&=n.pendingLanes,t|=r,e.lanes=t,IM(n,t)}}var RA={readContext:Od,useCallback:Vo,useContext:Vo,useEffect:Vo,useImperativeHandle:Vo,useInsertionEffect:Vo,useLayoutEffect:Vo,useMemo:Vo,useReducer:Vo,useRef:Vo,useState:Vo,useDebugValue:Vo,useDeferredValue:Vo,useTransition:Vo,useMutableSource:Vo,useSyncExternalStore:Vo,useId:Vo,unstable_isNewReconciler:!1},zQ={readContext:Od,useCallback:function(n,e){return Zc().memoizedState=[n,e===void 0?null:e],n},useContext:Od,useEffect:xz,useImperativeHandle:function(n,e,t){return t=t!=null?t.concat([n]):null,a5(4194308,4,MW.bind(null,e,n),t)},useLayoutEffect:function(n,e){return a5(4194308,4,n,e)},useInsertionEffect:function(n,e){return a5(4,2,n,e)},useMemo:function(n,e){var t=Zc();return e=e===void 0?null:e,n=n(),t.memoizedState=[n,e],n},useReducer:function(n,e,t){var r=Zc();return e=t!==void 0?t(e):e,r.memoizedState=r.baseState=e,n={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:e},r.queue=n,n=n.dispatch=IQ.bind(null,Ji,n),[r.memoizedState,n]},useRef:function(n){var e=Zc();return n={current:n},e.memoizedState=n},useState:yz,useDebugValue:i6,useDeferredValue:function(n){return Zc().memoizedState=n},useTransition:function(){var n=yz(!1),e=n[0];return n=BQ.bind(null,n[1]),Zc().memoizedState=n,[e,n]},useMutableSource:function(){},useSyncExternalStore:function(n,e,t){var r=Ji,i=Zc();if(Ii){if(t===void 0)throw Error(ft(407));t=t()}else{if(t=e(),po===null)throw Error(ft(349));u0&30||TW(r,e,t)}i.memoizedState=t;var o={value:t,getSnapshot:e};return i.queue=o,xz(DW.bind(null,r,o,n),[n]),r.flags|=2048,Sj(9,FW.bind(null,r,o,t,e),void 0,null),t},useId:function(){var n=Zc(),e=po.identifierPrefix;if(Ii){var t=uf,r=cf;t=(r&~(1<<32-Tc(r)-1)).toString(32)+t,e=":"+e+"R"+t,t=vj++,0<\/script>",n=n.removeChild(n.firstChild)):typeof r.is=="string"?n=a.createElement(t,{is:r.is}):(n=a.createElement(t),t==="select"&&(a=n,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):n=a.createElementNS(n,t),n[Du]=e,n[yj]=r,e9(n,e,!1,!1),e.stateNode=n;e:{switch(a=uR(t,r),t){case"dialog":vi("cancel",n),vi("close",n),i=r;break;case"iframe":case"object":case"embed":vi("load",n),i=r;break;case"video":case"audio":for(i=0;i<$w.length;i++)vi($w[i],n);i=r;break;case"source":vi("error",n),i=r;break;case"img":case"image":case"link":vi("error",n),vi("load",n),i=r;break;case"details":vi("toggle",n),i=r;break;case"input":z8(n,r),i=sR(n,r),vi("invalid",n);break;case"option":i=r;break;case"select":n._wrapperState={wasMultiple:!!r.multiple},i=ns({},r,{value:void 0}),vi("invalid",n);break;case"textarea":L8(n,r),i=lR(n,r),vi("invalid",n);break;default:i=r}cR(t,i),l=i;for(o in l)if(l.hasOwnProperty(o)){var d=l[o];o==="style"?R7(n,d):o==="dangerouslySetInnerHTML"?(d=d?d.__html:void 0,d!=null&&E7(n,d)):o==="children"?typeof d=="string"?(t!=="textarea"||d!=="")&&lj(n,d):typeof d=="number"&&lj(n,""+d):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(aj.hasOwnProperty(o)?d!=null&&o==="onScroll"&&vi("scroll",n):d!=null&&FM(n,o,d,a))}switch(t){case"input":ZC(n),O8(n,r,!1);break;case"textarea":ZC(n),N8(n);break;case"option":r.value!=null&&n.setAttribute("value",""+Bg(r.value));break;case"select":n.multiple=!!r.multiple,o=r.value,o!=null?Zx(n,!!r.multiple,o,!1):r.defaultValue!=null&&Zx(n,!!r.multiple,r.defaultValue,!0);break;default:typeof i.onClick=="function"&&(n.onclick=jA)}switch(t){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return Go(e),null;case 6:if(n&&e.stateNode!=null)n9(n,e,n.memoizedProps,r);else{if(typeof r!="string"&&e.stateNode===null)throw Error(ft(166));if(t=ym(bj.current),ym(Mu.current),a2(e)){if(r=e.stateNode,t=e.memoizedProps,r[Du]=e,(o=r.nodeValue!==t)&&(n=Vl,n!==null))switch(n.tag){case 3:o2(r.nodeValue,t,(n.mode&1)!==0);break;case 5:n.memoizedProps.suppressHydrationWarning!==!0&&o2(r.nodeValue,t,(n.mode&1)!==0)}o&&(e.flags|=4)}else r=(t.nodeType===9?t:t.ownerDocument).createTextNode(r),r[Du]=e,e.stateNode=r}return Go(e),null;case 13:if(_i(Qi),r=e.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(Ii&&Nl!==null&&e.mode&1&&!(e.flags&128))vW(),$v(),e.flags|=98560,o=!1;else if(o=a2(e),r!==null&&r.dehydrated!==null){if(n===null){if(!o)throw Error(ft(318));if(o=e.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(ft(317));o[Du]=e}else $v(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Go(e),o=!1}else kc!==null&&(VR(kc),kc=null),o=!0;if(!o)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(r=r!==null,r!==(n!==null&&n.memoizedState!==null)&&r&&(e.child.flags|=8192,e.mode&1&&(n===null||Qi.current&1?Ws===0&&(Ws=3):u6())),e.updateQueue!==null&&(e.flags|=4),Go(e),null);case 4:return Jv(),zR(n,e),n===null&&gj(e.stateNode.containerInfo),Go(e),null;case 10:return XM(e.type._context),Go(e),null;case 17:return nl(e.type)&&kA(),Go(e),null;case 19:if(_i(Qi),o=e.memoizedState,o===null)return Go(e),null;if(r=(e.flags&128)!==0,a=o.rendering,a===null)if(r)Cw(o,!1);else{if(Ws!==0||n!==null&&n.flags&128)for(n=e.child;n!==null;){if(a=EA(n),a!==null){for(e.flags|=128,Cw(o,!1),r=a.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),e.subtreeFlags=0,r=t,t=e.child;t!==null;)o=t,n=r,o.flags&=14680066,a=o.alternate,a===null?(o.childLanes=0,o.lanes=n,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=a.childLanes,o.lanes=a.lanes,o.child=a.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=a.memoizedProps,o.memoizedState=a.memoizedState,o.updateQueue=a.updateQueue,o.type=a.type,n=a.dependencies,o.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext}),t=t.sibling;return yi(Qi,Qi.current&1|2),e.child}n=n.sibling}o.tail!==null&&ws()>t1&&(e.flags|=128,r=!0,Cw(o,!1),e.lanes=4194304)}else{if(!r)if(n=EA(a),n!==null){if(e.flags|=128,r=!0,t=n.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),Cw(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Ii)return Go(e),null}else 2*ws()-o.renderingStartTime>t1&&t!==1073741824&&(e.flags|=128,r=!0,Cw(o,!1),e.lanes=4194304);o.isBackwards?(a.sibling=e.child,e.child=a):(t=o.last,t!==null?t.sibling=a:e.child=a,o.last=a)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=ws(),e.sibling=null,t=Qi.current,yi(Qi,r?t&1|2:t&1),e):(Go(e),null);case 22:case 23:return c6(),r=e.memoizedState!==null,n!==null&&n.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?Bl&1073741824&&(Go(e),e.subtreeFlags&6&&(e.flags|=8192)):Go(e),null;case 24:return null;case 25:return null}throw Error(ft(156,e.tag))}function VQ(n,e){switch(qM(e),e.tag){case 1:return nl(e.type)&&kA(),n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 3:return Jv(),_i(tl),_i(ia),JM(),n=e.flags,n&65536&&!(n&128)?(e.flags=n&-65537|128,e):null;case 5:return ZM(e),null;case 13:if(_i(Qi),n=e.memoizedState,n!==null&&n.dehydrated!==null){if(e.alternate===null)throw Error(ft(340));$v()}return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 19:return _i(Qi),null;case 4:return Jv(),null;case 10:return XM(e.type._context),null;case 22:case 23:return c6(),null;case 24:return null;default:return null}}var c2=!1,na=!1,GQ=typeof WeakSet=="function"?WeakSet:Set,Ut=null;function Ux(n,e){var t=n.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){us(n,e,r)}else t.current=null}function OR(n,e,t){try{t()}catch(r){us(n,e,r)}}var Fz=!1;function KQ(n,e){if(wR=vA,n=aW(),UM(n)){if("selectionStart"in n)var t={start:n.selectionStart,end:n.selectionEnd};else e:{t=(t=n.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{t.nodeType,o.nodeType}catch{t=null;break e}var a=0,l=-1,d=-1,c=0,u=0,f=n,p=null;t:for(;;){for(var g;f!==t||i!==0&&f.nodeType!==3||(l=a+i),f!==o||r!==0&&f.nodeType!==3||(d=a+r),f.nodeType===3&&(a+=f.nodeValue.length),(g=f.firstChild)!==null;)p=f,f=g;for(;;){if(f===n)break t;if(p===t&&++c===i&&(l=a),p===o&&++u===r&&(d=a),(g=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=g}t=l===-1||d===-1?null:{start:l,end:d}}else t=null}t=t||{start:0,end:0}}else t=null;for(SR={focusedElem:n,selectionRange:t},vA=!1,Ut=e;Ut!==null;)if(e=Ut,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,Ut=n;else for(;Ut!==null;){e=Ut;try{var m=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var y=m.memoizedProps,v=m.memoizedState,x=e.stateNode,w=x.getSnapshotBeforeUpdate(e.elementType===e.type?y:ac(e.type,y),v);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var S=e.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ft(163))}}catch(_){us(e,e.return,_)}if(n=e.sibling,n!==null){n.return=e.return,Ut=n;break}Ut=e.return}return m=Fz,Fz=!1,m}function LS(n,e,t){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&n)===n){var o=i.destroy;i.destroy=void 0,o!==void 0&&OR(e,t,o)}i=i.next}while(i!==r)}}function uF(n,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&n)===n){var r=t.create;t.destroy=r()}t=t.next}while(t!==e)}}function LR(n){var e=n.ref;if(e!==null){var t=n.stateNode;switch(n.tag){case 5:n=t;break;default:n=t}typeof e=="function"?e(n):e.current=n}}function r9(n){var e=n.alternate;e!==null&&(n.alternate=null,r9(e)),n.child=null,n.deletions=null,n.sibling=null,n.tag===5&&(e=n.stateNode,e!==null&&(delete e[Du],delete e[yj],delete e[_R],delete e[FQ],delete e[DQ])),n.stateNode=null,n.return=null,n.dependencies=null,n.memoizedProps=null,n.memoizedState=null,n.pendingProps=null,n.stateNode=null,n.updateQueue=null}function i9(n){return n.tag===5||n.tag===3||n.tag===4}function Dz(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||i9(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function NR(n,e,t){var r=n.tag;if(r===5||r===6)n=n.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(n,e):t.insertBefore(n,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(n,t)):(e=t,e.appendChild(n)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=jA));else if(r!==4&&(n=n.child,n!==null))for(NR(n,e,t),n=n.sibling;n!==null;)NR(n,e,t),n=n.sibling}function WR(n,e,t){var r=n.tag;if(r===5||r===6)n=n.stateNode,e?t.insertBefore(n,e):t.appendChild(n);else if(r!==4&&(n=n.child,n!==null))for(WR(n,e,t),n=n.sibling;n!==null;)WR(n,e,t),n=n.sibling}var Ao=null,jc=!1;function Hf(n,e,t){for(t=t.child;t!==null;)s9(n,e,t),t=t.sibling}function s9(n,e,t){if(Iu&&typeof Iu.onCommitFiberUnmount=="function")try{Iu.onCommitFiberUnmount(rF,t)}catch{}switch(t.tag){case 5:na||Ux(t,e);case 6:var r=Ao,i=jc;Ao=null,Hf(n,e,t),Ao=r,jc=i,Ao!==null&&(jc?(n=Ao,t=t.stateNode,n.nodeType===8?n.parentNode.removeChild(t):n.removeChild(t)):Ao.removeChild(t.stateNode));break;case 18:Ao!==null&&(jc?(n=Ao,t=t.stateNode,n.nodeType===8?XE(n.parentNode,t):n.nodeType===1&&XE(n,t),hj(n)):XE(Ao,t.stateNode));break;case 4:r=Ao,i=jc,Ao=t.stateNode.containerInfo,jc=!0,Hf(n,e,t),Ao=r,jc=i;break;case 0:case 11:case 14:case 15:if(!na&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var o=i,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&OR(t,e,a),i=i.next}while(i!==r)}Hf(n,e,t);break;case 1:if(!na&&(Ux(t,e),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(l){us(t,e,l)}Hf(n,e,t);break;case 21:Hf(n,e,t);break;case 22:t.mode&1?(na=(r=na)||t.memoizedState!==null,Hf(n,e,t),na=r):Hf(n,e,t);break;default:Hf(n,e,t)}}function Ez(n){var e=n.updateQueue;if(e!==null){n.updateQueue=null;var t=n.stateNode;t===null&&(t=n.stateNode=new GQ),e.forEach(function(r){var i=n$.bind(null,n,r);t.has(r)||(t.add(r),r.then(i,i))})}}function tc(n,e){var t=e.deletions;if(t!==null)for(var r=0;ri&&(i=a),r&=~o}if(r=i,r=ws()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*YQ(r/1960))-r,10n?16:n,cg===null)var r=!1;else{if(n=cg,cg=null,MA=0,jr&6)throw Error(ft(331));var i=jr;for(jr|=4,Ut=n.current;Ut!==null;){var o=Ut,a=o.child;if(Ut.flags&16){var l=o.deletions;if(l!==null){for(var d=0;dws()-l6?i0(n,0):a6|=t),rl(n,e)}function f9(n,e){e===0&&(n.mode&1?(e=t2,t2<<=1,!(t2&130023424)&&(t2=4194304)):e=1);var t=_a();n=kf(n,e),n!==null&&(U_(n,e,t),rl(n,t))}function t$(n){var e=n.memoizedState,t=0;e!==null&&(t=e.retryLane),f9(n,t)}function n$(n,e){var t=0;switch(n.tag){case 13:var r=n.stateNode,i=n.memoizedState;i!==null&&(t=i.retryLane);break;case 19:r=n.stateNode;break;default:throw Error(ft(314))}r!==null&&r.delete(e),f9(n,t)}var p9;p9=function(n,e,t){if(n!==null)if(n.memoizedProps!==e.pendingProps||tl.current)Ja=!0;else{if(!(n.lanes&t)&&!(e.flags&128))return Ja=!1,HQ(n,e,t);Ja=!!(n.flags&131072)}else Ja=!1,Ii&&e.flags&1048576&&xW(e,AA,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;l5(n,e),n=e.pendingProps;var i=Qv(e,ia.current);nb(e,t),i=t6(null,e,r,n,i,t);var o=n6();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,nl(r)?(o=!0,_A(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,QM(e),i.updater=cF,e.stateNode=i,i._reactInternals=e,ER(e,r,n,t),e=BR(null,e,r,!0,o,t)):(e.tag=0,Ii&&o&&HM(e),va(null,e,i,t),e=e.child),e;case 16:r=e.elementType;e:{switch(l5(n,e),n=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=i$(r),n=ac(r,n),i){case 0:e=RR(null,e,r,n,t);break e;case 1:e=Cz(null,e,r,n,t);break e;case 11:e=kz(null,e,r,n,t);break e;case 14:e=_z(null,e,r,ac(r.type,n),t);break e}throw Error(ft(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),RR(n,e,r,i,t);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),Cz(n,e,r,i,t);case 3:e:{if($W(e),n===null)throw Error(ft(387));r=e.pendingProps,o=e.memoizedState,i=o.element,kW(n,e),DA(e,r,null,t);var a=e.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},e.updateQueue.baseState=o,e.memoizedState=o,e.flags&256){i=e1(Error(ft(423)),e),e=Az(n,e,r,t,i);break e}else if(r!==i){i=e1(Error(ft(424)),e),e=Az(n,e,r,t,i);break e}else for(Nl=wg(e.stateNode.containerInfo.firstChild),Vl=e,Ii=!0,kc=null,t=SW(e,null,r,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if($v(),r===i){e=_f(n,e,t);break e}va(n,e,r,t)}e=e.child}return e;case 5:return _W(e),n===null&&TR(e),r=e.type,i=e.pendingProps,o=n!==null?n.memoizedProps:null,a=i.children,jR(r,i)?a=null:o!==null&&jR(r,o)&&(e.flags|=32),QW(n,e),va(n,e,a,t),e.child;case 6:return n===null&&TR(e),null;case 13:return ZW(n,e,t);case 4:return $M(e,e.stateNode.containerInfo),r=e.pendingProps,n===null?e.child=Zv(e,null,r,t):va(n,e,r,t),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),kz(n,e,r,i,t);case 7:return va(n,e,e.pendingProps,t),e.child;case 8:return va(n,e,e.pendingProps.children,t),e.child;case 12:return va(n,e,e.pendingProps.children,t),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,o=e.memoizedProps,a=i.value,yi(TA,r._currentValue),r._currentValue=a,o!==null)if(Ec(o.value,a)){if(o.children===i.children&&!tl.current){e=_f(n,e,t);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var l=o.dependencies;if(l!==null){a=o.child;for(var d=l.firstContext;d!==null;){if(d.context===r){if(o.tag===1){d=ff(-1,t&-t),d.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?d.next=d:(d.next=u.next,u.next=d),c.pending=d}}o.lanes|=t,d=o.alternate,d!==null&&(d.lanes|=t),FR(o.return,t,e),l.lanes|=t;break}d=d.next}}else if(o.tag===10)a=o.type===e.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(ft(341));a.lanes|=t,l=a.alternate,l!==null&&(l.lanes|=t),FR(a,t,e),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===e){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}va(n,e,i.children,t),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,nb(e,t),i=Od(i),r=r(i),e.flags|=1,va(n,e,r,t),e.child;case 14:return r=e.type,i=ac(r,e.pendingProps),i=ac(r.type,i),_z(n,e,r,i,t);case 15:return XW(n,e,e.type,e.pendingProps,t);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),l5(n,e),e.tag=1,nl(r)?(n=!0,_A(e)):n=!1,nb(e,t),VW(e,r,i),ER(e,r,i,t),BR(null,e,r,!0,n,t);case 19:return JW(n,e,t);case 22:return YW(n,e,t)}throw Error(ft(156,e.tag))};function g9(n,e){return U7(n,e)}function r$(n,e,t,r){this.tag=n,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dd(n,e,t,r){return new r$(n,e,t,r)}function h6(n){return n=n.prototype,!(!n||!n.isReactComponent)}function i$(n){if(typeof n=="function")return h6(n)?1:0;if(n!=null){if(n=n.$$typeof,n===EM)return 11;if(n===PM)return 14}return 2}function _g(n,e){var t=n.alternate;return t===null?(t=Dd(n.tag,e,n.key,n.mode),t.elementType=n.elementType,t.type=n.type,t.stateNode=n.stateNode,t.alternate=n,n.alternate=t):(t.pendingProps=e,t.type=n.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=n.flags&14680064,t.childLanes=n.childLanes,t.lanes=n.lanes,t.child=n.child,t.memoizedProps=n.memoizedProps,t.memoizedState=n.memoizedState,t.updateQueue=n.updateQueue,e=n.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=n.sibling,t.index=n.index,t.ref=n.ref,t}function u5(n,e,t,r,i,o){var a=2;if(r=n,typeof n=="function")h6(n)&&(a=1);else if(typeof n=="string")a=5;else e:switch(n){case Rx:return s0(t.children,i,o,e);case DM:a=8,i|=8;break;case tR:return n=Dd(12,t,e,i|2),n.elementType=tR,n.lanes=o,n;case nR:return n=Dd(13,t,e,i),n.elementType=nR,n.lanes=o,n;case rR:return n=Dd(19,t,e,i),n.elementType=rR,n.lanes=o,n;case _7:return fF(t,i,o,e);default:if(typeof n=="object"&&n!==null)switch(n.$$typeof){case j7:a=10;break e;case k7:a=9;break e;case EM:a=11;break e;case PM:a=14;break e;case ep:a=16,r=null;break e}throw Error(ft(130,n==null?n:typeof n,""))}return e=Dd(a,t,e,i),e.elementType=n,e.type=r,e.lanes=o,e}function s0(n,e,t,r){return n=Dd(7,n,r,e),n.lanes=t,n}function fF(n,e,t,r){return n=Dd(22,n,r,e),n.elementType=_7,n.lanes=t,n.stateNode={isHidden:!1},n}function nP(n,e,t){return n=Dd(6,n,null,e),n.lanes=t,n}function rP(n,e,t){return e=Dd(4,n.children!==null?n.children:[],n.key,e),e.lanes=t,e.stateNode={containerInfo:n.containerInfo,pendingChildren:null,implementation:n.implementation},e}function s$(n,e,t,r,i){this.tag=e,this.containerInfo=n,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zE(0),this.expirationTimes=zE(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zE(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function f6(n,e,t,r,i,o,a,l,d){return n=new s$(n,e,t,l,d),e===1?(e=1,o===!0&&(e|=8)):e=0,o=Dd(3,null,null,e),n.current=o,o.stateNode=n,o.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},QM(o),n}function o$(n,e,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(b9)}catch(n){console.error(n)}}b9(),b7.exports=Ql;var u$=b7.exports,Lz=u$;JP.createRoot=Lz.createRoot,JP.hydrateRoot=Lz.hydrateRoot;/** * @remix-run/router v1.23.3 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function kj(){return kj=Object.assign?Object.assign.bind():function(n){for(var e=1;e"u")throw new Error(e)}function y6(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function f$(){return Math.random().toString(36).substr(2,8)}function Wz(n,e){return{usr:n.state,key:n.key,idx:e}}function GR(n,e,t,r){return t===void 0&&(t=null),kj({pathname:typeof n=="string"?n:n.pathname,search:"",hash:""},typeof e=="string"?f1(e):e,{state:t,key:e&&e.key||r||f$()})}function LA(n){let{pathname:e="/",search:t="",hash:r=""}=n;return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),r&&r!=="#"&&(e+=r.charAt(0)==="#"?r:"#"+r),e}function f1(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substr(t),n=n.substr(0,t));let r=n.indexOf("?");r>=0&&(e.search=n.substr(r),n=n.substr(0,r)),n&&(e.pathname=n)}return e}function p$(n,e,t,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:o=!1}=r,a=i.history,l=ug.Pop,d=null,c=u();c==null&&(c=0,a.replaceState(kj({},a.state,{idx:c}),""));function u(){return(a.state||{idx:null}).idx}function f(){l=ug.Pop;let v=u(),x=v==null?null:v-c;c=v,d&&d({action:l,location:y.location,delta:x})}function p(v,x){l=ug.Push;let w=GR(y.location,v,x);c=u()+1;let S=Wz(w,c),_=y.createHref(w);try{a.pushState(S,"",_)}catch(b){if(b instanceof DOMException&&b.name==="DataCloneError")throw b;i.location.assign(_)}o&&d&&d({action:l,location:y.location,delta:1})}function g(v,x){l=ug.Replace;let w=GR(y.location,v,x);c=u();let S=Wz(w,c),_=y.createHref(w);a.replaceState(S,"",_),o&&d&&d({action:l,location:y.location,delta:0})}function m(v){let x=i.location.origin!=="null"?i.location.origin:i.location.href,w=typeof v=="string"?v:LA(v);return w=w.replace(/ $/,"%20"),es(x,"No window.location.(origin|href) available to create URL for href: "+w),new URL(w,x)}let y={get action(){return l},get location(){return n(i,a)},listen(v){if(d)throw new Error("A history only accepts one active listener");return i.addEventListener(Nz,f),d=v,()=>{i.removeEventListener(Nz,f),d=null}},createHref(v){return e(i,v)},createURL:m,encodeLocation(v){let x=m(v);return{pathname:x.pathname,search:x.search,hash:x.hash}},push:p,replace:g,go(v){return a.go(v)}};return y}var Uz;(function(n){n.data="data",n.deferred="deferred",n.redirect="redirect",n.error="error"})(Uz||(Uz={}));function g$(n,e,t){return t===void 0&&(t="/"),m$(n,e,t)}function m$(n,e,t,r){let i=typeof e=="string"?f1(e):e,o=n1(i.pathname||"/",t);if(o==null)return null;let a=v9(n);y$(a);let l=null,d=T$(o);for(let c=0;l==null&&c{let d={relativePath:l===void 0?o.path||"":l,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};d.relativePath.startsWith("/")&&(es(d.relativePath.startsWith(r),'Absolute route path "'+d.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),d.relativePath=d.relativePath.slice(r.length));let c=Cg([r,d.relativePath]),u=t.concat(d);o.children&&o.children.length>0&&(es(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),v9(o.children,e,u,c)),!(o.path==null&&!o.index)&&e.push({path:c,score:k$(c,o.index),routesMeta:u})};return n.forEach((o,a)=>{var l;if(o.path===""||!((l=o.path)!=null&&l.includes("?")))i(o,a);else for(let d of w9(o.path))i(o,a,d)}),e}function w9(n){let e=n.split("/");if(e.length===0)return[];let[t,...r]=e,i=t.endsWith("?"),o=t.replace(/\?$/,"");if(r.length===0)return i?[o,""]:[o];let a=w9(r.join("/")),l=[];return l.push(...a.map(d=>d===""?o:[o,d].join("/"))),i&&l.push(...a),l.map(d=>n.startsWith("/")&&d===""?"/":d)}function y$(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:_$(e.routesMeta.map(r=>r.childrenIndex),t.routesMeta.map(r=>r.childrenIndex)))}const x$=/^:[\w-]+$/,b$=3,v$=2,w$=1,S$=10,j$=-2,Hz=n=>n==="*";function k$(n,e){let t=n.split("/"),r=t.length;return t.some(Hz)&&(r+=j$),e&&(r+=v$),t.filter(i=>!Hz(i)).reduce((i,o)=>i+(x$.test(o)?b$:o===""?w$:S$),r)}function _$(n,e){return n.length===e.length&&n.slice(0,-1).every((r,i)=>r===e[i])?n[n.length-1]-e[e.length-1]:0}function C$(n,e,t){let{routesMeta:r}=n,i={},o="/",a=[];for(let l=0;l{let{paramName:p,isOptional:g}=u;if(p==="*"){let y=l[f]||"";a=o.slice(0,o.length-y.length).replace(/(.)\/+$/,"$1")}const m=l[f];return g&&!m?c[p]=void 0:c[p]=(m||"").replace(/%2F/g,"/"),c},{}),pathname:o,pathnameBase:a,pattern:n}}function A$(n,e,t){e===void 0&&(e=!1),t===void 0&&(t=!0),y6(n==="*"||!n.endsWith("*")||n.endsWith("/*"),'Route path "'+n+'" will be treated as if it were '+('"'+n.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+n.replace(/\*$/,"/*")+'".'));let r=[],i="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,d)=>(r.push({paramName:l,isOptional:d!=null}),d?"/?([^\\/]+)?":"/([^\\/]+)"));return n.endsWith("*")?(r.push({paramName:"*"}),i+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?i+="\\/*$":n!==""&&n!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function T$(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return y6(!1,'The URL path "'+n+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),n}}function n1(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,r=n.charAt(t);return r&&r!=="/"?null:n.slice(t)||"/"}const F$=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,D$=n=>F$.test(n);function E$(n,e){e===void 0&&(e="/");let{pathname:t,search:r="",hash:i=""}=typeof n=="string"?f1(n):n,o;if(t)if(D$(t))o=t;else{if(t.includes("//")){let a=t;t=S9(t),y6(!1,"Pathnames cannot have embedded double slashes - normalizing "+(a+" -> "+t))}t.startsWith("/")?o=qz(t.substring(1),"/"):o=qz(t,e)}else o=e;return{pathname:o,search:B$(r),hash:I$(i)}}function qz(n,e){let t=e.replace(/\/+$/,"").split("/");return n.split("/").forEach(i=>{i===".."?t.length>1&&t.pop():i!=="."&&t.push(i)}),t.length>1?t.join("/"):"/"}function iP(n,e,t,r){return"Cannot include a '"+n+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+t+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function P$(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function x6(n,e){let t=P$(n);return e?t.map((r,i)=>i===t.length-1?r.pathname:r.pathnameBase):t.map(r=>r.pathnameBase)}function b6(n,e,t,r){r===void 0&&(r=!1);let i;typeof n=="string"?i=f1(n):(i=kj({},n),es(!i.pathname||!i.pathname.includes("?"),iP("?","pathname","search",i)),es(!i.pathname||!i.pathname.includes("#"),iP("#","pathname","hash",i)),es(!i.search||!i.search.includes("#"),iP("#","search","hash",i)));let o=n===""||i.pathname==="",a=o?"/":i.pathname,l;if(a==null)l=t;else{let f=e.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;i.pathname=p.join("/")}l=f>=0?e[f]:"/"}let d=E$(i,l),c=a&&a!=="/"&&a.endsWith("/"),u=(o||a===".")&&t.endsWith("/");return!d.pathname.endsWith("/")&&(c||u)&&(d.pathname+="/"),d}const S9=n=>n.replace(/\/\/+/g,"/"),Cg=n=>S9(n.join("/")),R$=n=>n.replace(/\/+$/,"").replace(/^\/*/,"/"),B$=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,I$=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n;function M$(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}const j9=["post","put","patch","delete"];new Set(j9);const z$=["get",...j9];new Set(z$);/** * React Router v6.30.4 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function _j(){return _j=Object.assign?Object.assign.bind():function(n){for(var e=1;e{l.current=!0}),k.useCallback(function(c,u){if(u===void 0&&(u={}),!l.current)return;if(typeof c=="number"){r.go(c);return}let f=b6(c,JSON.parse(a),o,u.relative==="path");n==null&&e!=="/"&&(f.pathname=f.pathname==="/"?e:Cg([e,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[e,r,a,o,n])}const N$=k.createContext(null);function W$(n){let e=k.useContext(Uu).outlet;return e&&k.createElement(N$.Provider,{value:n},e)}function G_(){let{matches:n}=k.useContext(Uu),e=n[n.length-1];return e?e.params:{}}function vF(n,e){let{relative:t}=e===void 0?{}:e,{future:r}=k.useContext(Pf),{matches:i}=k.useContext(Uu),{pathname:o}=E0(),a=JSON.stringify(x6(i,r.v7_relativeSplatPath));return k.useMemo(()=>b6(n,JSON.parse(a),o,t==="path"),[n,a,o,t])}function U$(n,e){return H$(n,e)}function H$(n,e,t,r){p1()||es(!1);let{navigator:i}=k.useContext(Pf),{matches:o}=k.useContext(Uu),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let d=a?a.pathnameBase:"/";a&&a.route;let c=E0(),u;if(e){var f;let v=typeof e=="string"?f1(e):e;d==="/"||(f=v.pathname)!=null&&f.startsWith(d)||es(!1),u=v}else u=c;let p=u.pathname||"/",g=p;if(d!=="/"){let v=d.replace(/^\//,"").split("/");g="/"+p.replace(/^\//,"").split("/").slice(v.length).join("/")}let m=g$(n,{pathname:g}),y=X$(m&&m.map(v=>Object.assign({},v,{params:Object.assign({},l,v.params),pathname:Cg([d,i.encodeLocation?i.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?d:Cg([d,i.encodeLocation?i.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),o,t,r);return e&&y?k.createElement(bF.Provider,{value:{location:_j({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:ug.Pop}},y):y}function q$(){let n=Z$(),e=M$(n)?n.status+" "+n.statusText:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},e),t?k.createElement("pre",{style:i},t):null,null)}const V$=k.createElement(q$,null);class G$ extends k.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return this.state.error!==void 0?k.createElement(Uu.Provider,{value:this.props.routeContext},k.createElement(_9.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function K$(n){let{routeContext:e,match:t,children:r}=n,i=k.useContext(xF);return i&&i.static&&i.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=t.route.id),k.createElement(Uu.Provider,{value:e},r)}function X$(n,e,t,r){var i;if(e===void 0&&(e=[]),t===void 0&&(t=null),r===void 0&&(r=null),n==null){var o;if(!t)return null;if(t.errors)n=t.matches;else if((o=r)!=null&&o.v7_partialHydration&&e.length===0&&!t.initialized&&t.matches.length>0)n=t.matches;else return null}let a=n,l=(i=t)==null?void 0:i.errors;if(l!=null){let u=a.findIndex(f=>f.route.id&&(l==null?void 0:l[f.route.id])!==void 0);u>=0||es(!1),a=a.slice(0,Math.min(a.length,u+1))}let d=!1,c=-1;if(t&&r&&r.v7_partialHydration)for(let u=0;u=0?a=a.slice(0,c+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let g,m=!1,y=null,v=null;t&&(g=l&&f.route.id?l[f.route.id]:void 0,y=f.route.errorElement||V$,d&&(c<0&&p===0?(eZ("route-fallback"),m=!0,v=null):c===p&&(m=!0,v=f.route.hydrateFallbackElement||null)));let x=e.concat(a.slice(0,p+1)),w=()=>{let S;return g?S=y:m?S=v:f.route.Component?S=k.createElement(f.route.Component,null):f.route.element?S=f.route.element:S=u,k.createElement(K$,{match:f,routeContext:{outlet:u,matches:x,isDataRoute:t!=null},children:S})};return t&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?k.createElement(G$,{location:t.location,revalidation:t.revalidation,component:y,error:g,children:w(),routeContext:{outlet:null,matches:x,isDataRoute:!0}}):w()},null)}var A9=function(n){return n.UseBlocker="useBlocker",n.UseRevalidator="useRevalidator",n.UseNavigateStable="useNavigate",n}(A9||{}),T9=function(n){return n.UseBlocker="useBlocker",n.UseLoaderData="useLoaderData",n.UseActionData="useActionData",n.UseRouteError="useRouteError",n.UseNavigation="useNavigation",n.UseRouteLoaderData="useRouteLoaderData",n.UseMatches="useMatches",n.UseRevalidator="useRevalidator",n.UseNavigateStable="useNavigate",n.UseRouteId="useRouteId",n}(T9||{});function Y$(n){let e=k.useContext(xF);return e||es(!1),e}function Q$(n){let e=k.useContext(k9);return e||es(!1),e}function $$(n){let e=k.useContext(Uu);return e||es(!1),e}function F9(n){let e=$$(),t=e.matches[e.matches.length-1];return t.route.id||es(!1),t.route.id}function Z$(){var n;let e=k.useContext(_9),t=Q$(),r=F9();return e!==void 0?e:(n=t.errors)==null?void 0:n[r]}function J$(){let{router:n}=Y$(A9.UseNavigateStable),e=F9(T9.UseNavigateStable),t=k.useRef(!1);return C9(()=>{t.current=!0}),k.useCallback(function(i,o){o===void 0&&(o={}),t.current&&(typeof i=="number"?n.navigate(i):n.navigate(i,_j({fromRouteId:e},o)))},[n,e])}const Vz={};function eZ(n,e,t){Vz[n]||(Vz[n]=!0)}function tZ(n,e){n==null||n.v7_startTransition,n==null||n.v7_relativeSplatPath}function Gz(n){let{to:e,replace:t,state:r,relative:i}=n;p1()||es(!1);let{future:o,static:a}=k.useContext(Pf),{matches:l}=k.useContext(Uu),{pathname:d}=E0(),c=go(),u=b6(e,x6(l,o.v7_relativeSplatPath),d,i==="path"),f=JSON.stringify(u);return k.useEffect(()=>c(JSON.parse(f),{replace:t,state:r,relative:i}),[c,f,i,t,r]),null}function nZ(n){return W$(n.context)}function Zn(n){es(!1)}function rZ(n){let{basename:e="/",children:t=null,location:r,navigationType:i=ug.Pop,navigator:o,static:a=!1,future:l}=n;p1()&&es(!1);let d=e.replace(/^\/*/,"/"),c=k.useMemo(()=>({basename:d,navigator:o,static:a,future:_j({v7_relativeSplatPath:!1},l)}),[d,l,o,a]);typeof r=="string"&&(r=f1(r));let{pathname:u="/",search:f="",hash:p="",state:g=null,key:m="default"}=r,y=k.useMemo(()=>{let v=n1(u,d);return v==null?null:{location:{pathname:v,search:f,hash:p,state:g,key:m},navigationType:i}},[d,u,f,p,g,m,i]);return y==null?null:k.createElement(Pf.Provider,{value:c},k.createElement(bF.Provider,{children:t,value:y}))}function iZ(n){let{children:e,location:t}=n;return U$(XR(e),t)}new Promise(()=>{});function XR(n,e){e===void 0&&(e=[]);let t=[];return k.Children.forEach(n,(r,i)=>{if(!k.isValidElement(r))return;let o=[...e,i];if(r.type===k.Fragment){t.push.apply(t,XR(r.props.children,o));return}r.type!==Zn&&es(!1),!r.props.index||!r.props.children||es(!1);let a={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=XR(r.props.children,o)),t.push(a)}),t}/** * React Router DOM v6.30.4 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function NA(){return NA=Object.assign?Object.assign.bind():function(n){for(var e=1;e{let r=n[t];return e.concat(Array.isArray(r)?r.map(i=>[t,i]):[[t,r]])},[]))}function aZ(n,e){let t=YR(n);return e&&e.forEach((r,i)=>{t.has(i)||e.getAll(i).forEach(o=>{t.append(i,o)})}),t}const lZ=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],dZ=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],cZ="6";try{window.__reactRouterVersion=cZ}catch{}const uZ=k.createContext({isTransitioning:!1}),hZ="startTransition",Kz=eY[hZ];function fZ(n){let{basename:e,children:t,future:r,window:i}=n,o=k.useRef();o.current==null&&(o.current=h$({window:i,v5Compat:!0}));let a=o.current,[l,d]=k.useState({action:a.action,location:a.location}),{v7_startTransition:c}=r||{},u=k.useCallback(f=>{c&&Kz?Kz(()=>d(f)):d(f)},[d,c]);return k.useLayoutEffect(()=>a.listen(u),[a,u]),k.useEffect(()=>tZ(r),[r]),k.createElement(rZ,{basename:e,children:t,location:l.location,navigationType:l.action,navigator:a,future:r})}const pZ=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",gZ=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,mZ=k.forwardRef(function(e,t){let{onClick:r,relative:i,reloadDocument:o,replace:a,state:l,target:d,to:c,preventScrollReset:u,viewTransition:f}=e,p=D9(e,lZ),{basename:g}=k.useContext(Pf),m,y=!1;if(typeof c=="string"&&gZ.test(c)&&(m=c,pZ))try{let S=new URL(window.location.href),_=c.startsWith("//")?new URL(S.protocol+c):new URL(c),b=n1(_.pathname,g);_.origin===S.origin&&b!=null?c=b+_.search+_.hash:y=!0}catch{}let v=O$(c,{relative:i}),x=xZ(c,{replace:a,state:l,target:d,preventScrollReset:u,relative:i,viewTransition:f});function w(S){r&&r(S),S.defaultPrevented||x(S)}return k.createElement("a",NA({},p,{href:m||v,onClick:y||o?r:w,ref:t,target:d}))}),wx=k.forwardRef(function(e,t){let{"aria-current":r="page",caseSensitive:i=!1,className:o="",end:a=!1,style:l,to:d,viewTransition:c,children:u}=e,f=D9(e,dZ),p=vF(d,{relative:f.relative}),g=E0(),m=k.useContext(k9),{navigator:y,basename:v}=k.useContext(Pf),x=m!=null&&bZ(p)&&c===!0,w=y.encodeLocation?y.encodeLocation(p).pathname:p.pathname,S=g.pathname,_=m&&m.navigation&&m.navigation.location?m.navigation.location.pathname:null;i||(S=S.toLowerCase(),_=_?_.toLowerCase():null,w=w.toLowerCase()),_&&v&&(_=n1(_,v)||_);const b=w!=="/"&&w.endsWith("/")?w.length-1:w.length;let C=S===w||!a&&S.startsWith(w)&&S.charAt(b)==="/",T=_!=null&&(_===w||!a&&_.startsWith(w)&&_.charAt(w.length)==="/"),F={isActive:C,isPending:T,isTransitioning:x},A=C?r:void 0,D;typeof o=="function"?D=o(F):D=[o,C?"active":null,T?"pending":null,x?"transitioning":null].filter(Boolean).join(" ");let P=typeof l=="function"?l(F):l;return k.createElement(mZ,NA({},f,{"aria-current":A,className:D,ref:t,style:P,to:d,viewTransition:c}),typeof u=="function"?u(F):u)});var QR;(function(n){n.UseScrollRestoration="useScrollRestoration",n.UseSubmit="useSubmit",n.UseSubmitFetcher="useSubmitFetcher",n.UseFetcher="useFetcher",n.useViewTransitionState="useViewTransitionState"})(QR||(QR={}));var Xz;(function(n){n.UseFetcher="useFetcher",n.UseFetchers="useFetchers",n.UseScrollRestoration="useScrollRestoration"})(Xz||(Xz={}));function yZ(n){let e=k.useContext(xF);return e||es(!1),e}function xZ(n,e){let{target:t,replace:r,state:i,preventScrollReset:o,relative:a,viewTransition:l}=e===void 0?{}:e,d=go(),c=E0(),u=vF(n,{relative:a});return k.useCallback(f=>{if(oZ(f,t)){f.preventDefault();let p=r!==void 0?r:LA(c)===LA(u);d(n,{replace:p,state:i,preventScrollReset:o,relative:a,viewTransition:l})}},[c,d,u,r,i,t,n,o,a,l])}function K_(n){let e=k.useRef(YR(n)),t=k.useRef(!1),r=E0(),i=k.useMemo(()=>aZ(r.search,t.current?null:e.current),[r.search]),o=go(),a=k.useCallback((l,d)=>{const c=YR(typeof l=="function"?l(i):l);t.current=!0,o("?"+c,d)},[o,i]);return[i,a]}function bZ(n,e){e===void 0&&(e={});let t=k.useContext(uZ);t==null&&es(!1);let{basename:r}=yZ(QR.useViewTransitionState),i=vF(n,{relative:e.relative});if(!t.isTransitioning)return!1;let o=n1(t.currentLocation.pathname,r)||t.currentLocation.pathname,a=n1(t.nextLocation.pathname,r)||t.nextLocation.pathname;return KR(i.pathname,a)!=null||KR(i.pathname,o)!=null}var g1=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(n){return this.listeners.add(n),this.onSubscribe(),()=>{this.listeners.delete(n),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Am,op,cb,YN,vZ=(YN=class extends g1{constructor(){super();N(this,Am);N(this,op);N(this,cb);R(this,cb,e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){h(this,op)||this.setEventListener(h(this,cb))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,op))==null||e.call(this),R(this,op,void 0))}setEventListener(e){var t;R(this,cb,e),(t=h(this,op))==null||t.call(this),R(this,op,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){h(this,Am)!==e&&(R(this,Am,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){var e;return typeof h(this,Am)=="boolean"?h(this,Am):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Am=new WeakMap,op=new WeakMap,cb=new WeakMap,YN),v6=new vZ,wZ={setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n),setInterval:(n,e)=>setInterval(n,e),clearInterval:n=>clearInterval(n)},ap,SM,QN,SZ=(QN=class{constructor(){N(this,ap,wZ);N(this,SM,!1)}setTimeoutProvider(n){R(this,ap,n)}setTimeout(n,e){return h(this,ap).setTimeout(n,e)}clearTimeout(n){h(this,ap).clearTimeout(n)}setInterval(n,e){return h(this,ap).setInterval(n,e)}clearInterval(n){h(this,ap).clearInterval(n)}},ap=new WeakMap,SM=new WeakMap,QN),xm=new SZ;function jZ(n){setTimeout(n,0)}var kZ=typeof window>"u"||"Deno"in globalThis;function wa(){}function _Z(n,e){return typeof n=="function"?n(e):n}function $R(n){return typeof n=="number"&&n>=0&&n!==1/0}function E9(n,e){return Math.max(n+(e||0)-Date.now(),0)}function Ag(n,e){return typeof n=="function"?n(e):n}function Ml(n,e){return typeof n=="function"?n(e):n}function Yz(n,e){const{type:t="all",exact:r,fetchStatus:i,predicate:o,queryKey:a,stale:l}=n;if(a){if(r){if(e.queryHash!==w6(a,e.options))return!1}else if(!Cj(e.queryKey,a))return!1}if(t!=="all"){const d=e.isActive();if(t==="active"&&!d||t==="inactive"&&d)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||i&&i!==e.state.fetchStatus||o&&!o(e))}function Qz(n,e){const{exact:t,status:r,predicate:i,mutationKey:o}=n;if(o){if(!e.options.mutationKey)return!1;if(t){if(p0(e.options.mutationKey)!==p0(o))return!1}else if(!Cj(e.options.mutationKey,o))return!1}return!(r&&e.state.status!==r||i&&!i(e))}function w6(n,e){return((e==null?void 0:e.queryKeyHashFn)||p0)(n)}function p0(n){return JSON.stringify(n,(e,t)=>ZR(t)?Object.keys(t).sort().reduce((r,i)=>(r[i]=t[i],r),{}):t)}function Cj(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"&&typeof e=="object"?Object.keys(e).every(t=>Cj(n[t],e[t])):!1}var CZ=Object.prototype.hasOwnProperty;function P9(n,e,t=0){if(n===e)return n;if(t>500)return e;const r=$z(n)&&$z(e);if(!r&&!(ZR(n)&&ZR(e)))return e;const o=(r?n:Object.keys(n)).length,a=r?e:Object.keys(e),l=a.length,d=r?new Array(l):{};let c=0;for(let u=0;u{xm.setTimeout(e,n)})}function JR(n,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(n,e):t.structuralSharing!==!1?P9(n,e):e}function TZ(n,e,t=0){const r=[...n,e];return t&&r.length>t?r.slice(1):r}function FZ(n,e,t=0){const r=[e,...n];return t&&r.length>t?r.slice(0,-1):r}var S6=Symbol();function R9(n,e){return!n.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!n.queryFn||n.queryFn===S6?()=>Promise.reject(new Error(`Missing queryFn: '${n.queryHash}'`)):n.queryFn}function j6(n,e){return typeof n=="function"?n(...e):!!n}function DZ(n,e,t){let r=!1,i;return Object.defineProperty(n,"signal",{enumerable:!0,get:()=>(i??(i=e()),r||(r=!0,i.aborted?t():i.addEventListener("abort",t,{once:!0})),i)}),n}var Aj=(()=>{let n=()=>kZ;return{isServer(){return n()},setIsServer(e){n=e}}})();function eB(){let n,e;const t=new Promise((i,o)=>{n=i,e=o});t.status="pending",t.catch(()=>{});function r(i){Object.assign(t,i),delete t.resolve,delete t.reject}return t.resolve=i=>{r({status:"fulfilled",value:i}),n(i)},t.reject=i=>{r({status:"rejected",reason:i}),e(i)},t}var EZ=jZ;function PZ(){let n=[],e=0,t=l=>{l()},r=l=>{l()},i=EZ;const o=l=>{e?n.push(l):i(()=>{t(l)})},a=()=>{const l=n;n=[],l.length&&i(()=>{r(()=>{l.forEach(d=>{t(d)})})})};return{batch:l=>{let d;e++;try{d=l()}finally{e--,e||a()}return d},batchCalls:l=>(...d)=>{o(()=>{l(...d)})},schedule:o,setNotifyFunction:l=>{t=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var Ls=PZ(),ub,lp,hb,$N,RZ=($N=class extends g1{constructor(){super();N(this,ub,!0);N(this,lp);N(this,hb);R(this,hb,e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}})}onSubscribe(){h(this,lp)||this.setEventListener(h(this,hb))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,lp))==null||e.call(this),R(this,lp,void 0))}setEventListener(e){var t;R(this,hb,e),(t=h(this,lp))==null||t.call(this),R(this,lp,e(this.setOnline.bind(this)))}setOnline(e){h(this,ub)!==e&&(R(this,ub,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return h(this,ub)}},ub=new WeakMap,lp=new WeakMap,hb=new WeakMap,$N),UA=new RZ;function BZ(n){return Math.min(1e3*2**n,3e4)}function B9(n){return(n??"online")==="online"?UA.isOnline():!0}var tB=class extends Error{constructor(n){super("CancelledError"),this.revert=n==null?void 0:n.revert,this.silent=n==null?void 0:n.silent}};function I9(n){let e=!1,t=0,r;const i=eB(),o=()=>i.status!=="pending",a=y=>{var v;if(!o()){const x=new tB(y);p(x),(v=n.onCancel)==null||v.call(n,x)}},l=()=>{e=!0},d=()=>{e=!1},c=()=>v6.isFocused()&&(n.networkMode==="always"||UA.isOnline())&&n.canRun(),u=()=>B9(n.networkMode)&&n.canRun(),f=y=>{o()||(r==null||r(),i.resolve(y))},p=y=>{o()||(r==null||r(),i.reject(y))},g=()=>new Promise(y=>{var v;r=x=>{(o()||c())&&y(x)},(v=n.onPause)==null||v.call(n)}).then(()=>{var y;r=void 0,o()||(y=n.onContinue)==null||y.call(n)}),m=()=>{if(o())return;let y;const v=t===0?n.initialPromise:void 0;try{y=v??n.fn()}catch(x){y=Promise.reject(x)}Promise.resolve(y).then(f).catch(x=>{var C;if(o())return;const w=n.retry??(Aj.isServer()?0:3),S=n.retryDelay??BZ,_=typeof S=="function"?S(t,x):S,b=w===!0||typeof w=="number"&&tc()?void 0:g()).then(()=>{e?p(x):m()})})};return{promise:i,status:()=>i.status,cancel:a,continue:()=>(r==null||r(),i),cancelRetry:l,continueRetry:d,canStart:u,start:()=>(u()?m():g().then(m),i)}}var Tm,ZN,M9=(ZN=class{constructor(){N(this,Tm)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),$R(this.gcTime)&&R(this,Tm,xm.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(n){this.gcTime=Math.max(this.gcTime||0,n??(Aj.isServer()?1/0:5*60*1e3))}clearGcTimeout(){h(this,Tm)!==void 0&&(xm.clearTimeout(h(this,Tm)),R(this,Tm,void 0))}},Tm=new WeakMap,ZN);function IZ(n){return{onFetch:(e,t)=>{var u,f,p,g,m;const r=e.options,i=(p=(f=(u=e.fetchOptions)==null?void 0:u.meta)==null?void 0:f.fetchMore)==null?void 0:p.direction,o=((g=e.state.data)==null?void 0:g.pages)||[],a=((m=e.state.data)==null?void 0:m.pageParams)||[];let l={pages:[],pageParams:[]},d=0;const c=async()=>{let y=!1;const v=S=>{DZ(S,()=>e.signal,()=>y=!0)},x=R9(e.options,e.fetchOptions),w=async(S,_,b)=>{if(y)return Promise.reject(e.signal.reason);if(_==null&&S.pages.length)return Promise.resolve(S);const T=(()=>{const P={client:e.client,queryKey:e.queryKey,pageParam:_,direction:b?"backward":"forward",meta:e.options.meta};return v(P),P})(),F=await x(T),{maxPages:A}=e.options,D=b?FZ:TZ;return{pages:D(S.pages,F,A),pageParams:D(S.pageParams,_,A)}};if(i&&o.length){const S=i==="backward",_=S?MZ:Jz,b={pages:o,pageParams:a},C=_(r,b);l=await w(b,C,S)}else{const S=n??o.length;do{const _=d===0?a[0]??r.initialPageParam:Jz(r,l);if(d>0&&_==null)break;l=await w(l,_),d++}while(d{var y,v;return(v=(y=e.options).persister)==null?void 0:v.call(y,c,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},t)}:e.fetchFn=c}}}function Jz(n,{pages:e,pageParams:t}){const r=e.length-1;return e.length>0?n.getNextPageParam(e[r],e,t[r],t):void 0}function MZ(n,{pages:e,pageParams:t}){var r;return e.length>0?(r=n.getPreviousPageParam)==null?void 0:r.call(n,e[0],e,t[0],t):void 0}var fb,Fm,pb,dd,Dm,eo,Zj,Em,Il,z9,dh,JN,zZ=(JN=class extends M9{constructor(e){super();N(this,Il);N(this,fb);N(this,Fm);N(this,pb);N(this,dd);N(this,Dm);N(this,eo);N(this,Zj);N(this,Em);R(this,Em,!1),R(this,Zj,e.defaultOptions),this.setOptions(e.options),this.observers=[],R(this,Dm,e.client),R(this,dd,h(this,Dm).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,R(this,Fm,tO(this.options)),this.state=e.state??h(this,Fm),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return h(this,fb)}get promise(){var e;return(e=h(this,eo))==null?void 0:e.promise}setOptions(e){if(this.options={...h(this,Zj),...e},e!=null&&e._type&&R(this,fb,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=tO(this.options);t.data!==void 0&&(this.setState(eO(t.data,t.dataUpdatedAt)),R(this,Fm,t))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&h(this,dd).remove(this)}setData(e,t){const r=JR(this.state.data,e,this.options);return q(this,Il,dh).call(this,{data:r,type:"success",dataUpdatedAt:t==null?void 0:t.updatedAt,manual:t==null?void 0:t.manual}),r}setState(e){q(this,Il,dh).call(this,{type:"setState",state:e})}cancel(e){var r,i;const t=(r=h(this,eo))==null?void 0:r.promise;return(i=h(this,eo))==null||i.cancel(e),t?t.then(wa).catch(wa):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return h(this,Fm)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Ml(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===S6||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ag(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!E9(this.state.dataUpdatedAt,e)}onFocus(){var t;const e=this.observers.find(r=>r.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,eo))==null||t.continue()}onOnline(){var t;const e=this.observers.find(r=>r.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,eo))==null||t.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),h(this,dd).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(h(this,eo)&&(h(this,Em)||q(this,Il,z9).call(this)?h(this,eo).cancel({revert:!0}):h(this,eo).cancelRetry()),this.scheduleGc()),h(this,dd).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,Il,dh).call(this,{type:"invalidate"})}async fetch(e,t){var c,u,f,p,g,m,y,v,x,w,S;if(this.state.fetchStatus!=="idle"&&((c=h(this,eo))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(t!=null&&t.cancelRefetch))this.cancel({silent:!0});else if(h(this,eo))return h(this,eo).continueRetry(),h(this,eo).promise}if(e&&this.setOptions(e),!this.options.queryFn){const _=this.observers.find(b=>b.options.queryFn);_&&this.setOptions(_.options)}const r=new AbortController,i=_=>{Object.defineProperty(_,"signal",{enumerable:!0,get:()=>(R(this,Em,!0),r.signal)})},o=()=>{const _=R9(this.options,t),C=(()=>{const T={client:h(this,Dm),queryKey:this.queryKey,meta:this.meta};return i(T),T})();return R(this,Em,!1),this.options.persister?this.options.persister(_,C,this):_(C)},l=(()=>{const _={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:h(this,Dm),state:this.state,fetchFn:o};return i(_),_})(),d=h(this,fb)==="infinite"?IZ(this.options.pages):this.options.behavior;d==null||d.onFetch(l,this),R(this,pb,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=l.fetchOptions)==null?void 0:u.meta))&&q(this,Il,dh).call(this,{type:"fetch",meta:(f=l.fetchOptions)==null?void 0:f.meta}),R(this,eo,I9({initialPromise:t==null?void 0:t.initialPromise,fn:l.fetchFn,onCancel:_=>{_ instanceof tB&&_.revert&&this.setState({...h(this,pb),fetchStatus:"idle"}),r.abort()},onFail:(_,b)=>{q(this,Il,dh).call(this,{type:"failed",failureCount:_,error:b})},onPause:()=>{q(this,Il,dh).call(this,{type:"pause"})},onContinue:()=>{q(this,Il,dh).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const _=await h(this,eo).start();if(_===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(_),(g=(p=h(this,dd).config).onSuccess)==null||g.call(p,_,this),(y=(m=h(this,dd).config).onSettled)==null||y.call(m,_,this.state.error,this),_}catch(_){if(_ instanceof tB){if(_.silent)return h(this,eo).promise;if(_.revert){if(this.state.data===void 0)throw _;return this.state.data}}throw q(this,Il,dh).call(this,{type:"error",error:_}),(x=(v=h(this,dd).config).onError)==null||x.call(v,_,this),(S=(w=h(this,dd).config).onSettled)==null||S.call(w,this.state.data,_,this),_}finally{this.scheduleGc()}}},fb=new WeakMap,Fm=new WeakMap,pb=new WeakMap,dd=new WeakMap,Dm=new WeakMap,eo=new WeakMap,Zj=new WeakMap,Em=new WeakMap,Il=new WeakSet,z9=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},dh=function(e){const t=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...O9(r.data,this.options),fetchMeta:e.meta??null};case"success":const i={...r,...eO(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return R(this,pb,e.manual?i:void 0),i;case"error":const o=e.error;return{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=t(this.state),Ls.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),h(this,dd).notify({query:this,type:"updated",action:e})})},JN);function O9(n,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:B9(e.networkMode)?"fetching":"paused",...n===void 0&&{error:null,status:"pending"}}}function eO(n,e){return{data:n,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tO(n){const e=typeof n.initialData=="function"?n.initialData():n.initialData,t=e!==void 0,r=t?typeof n.initialDataUpdatedAt=="function"?n.initialDataUpdatedAt():n.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:t?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}var Wa,ur,Jj,fa,Pm,gb,jh,dp,ek,mb,yb,Rm,Bm,cp,xb,qr,Zw,nB,rB,iB,sB,oB,aB,lB,L9,e7,OZ=(e7=class extends g1{constructor(e,t){super();N(this,qr);N(this,Wa);N(this,ur);N(this,Jj);N(this,fa);N(this,Pm);N(this,gb);N(this,jh);N(this,dp);N(this,ek);N(this,mb);N(this,yb);N(this,Rm);N(this,Bm);N(this,cp);N(this,xb,new Set);this.options=t,R(this,Wa,e),R(this,dp,null),R(this,jh,eB()),this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(h(this,ur).addObserver(this),nO(h(this,ur),this.options)?q(this,qr,Zw).call(this):this.updateResult(),q(this,qr,sB).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dB(h(this,ur),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dB(h(this,ur),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,qr,oB).call(this),q(this,qr,aB).call(this),h(this,ur).removeObserver(this)}setOptions(e){const t=this.options,r=h(this,ur);if(this.options=h(this,Wa).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ml(this.options.enabled,h(this,ur))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,qr,lB).call(this),h(this,ur).setOptions(this.options),t._defaulted&&!WA(this.options,t)&&h(this,Wa).getQueryCache().notify({type:"observerOptionsUpdated",query:h(this,ur),observer:this});const i=this.hasListeners();i&&rO(h(this,ur),r,this.options,t)&&q(this,qr,Zw).call(this),this.updateResult(),i&&(h(this,ur)!==r||Ml(this.options.enabled,h(this,ur))!==Ml(t.enabled,h(this,ur))||Ag(this.options.staleTime,h(this,ur))!==Ag(t.staleTime,h(this,ur)))&&q(this,qr,nB).call(this);const o=q(this,qr,rB).call(this);i&&(h(this,ur)!==r||Ml(this.options.enabled,h(this,ur))!==Ml(t.enabled,h(this,ur))||o!==h(this,cp))&&q(this,qr,iB).call(this,o)}getOptimisticResult(e){const t=h(this,Wa).getQueryCache().build(h(this,Wa),e),r=this.createResult(t,e);return NZ(this,r)&&(R(this,fa,r),R(this,gb,this.options),R(this,Pm,h(this,ur).state)),r}getCurrentResult(){return h(this,fa)}trackResult(e,t){return new Proxy(e,{get:(r,i)=>(this.trackProp(i),t==null||t(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&h(this,jh).status==="pending"&&h(this,jh).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,i))})}trackProp(e){h(this,xb).add(e)}getCurrentQuery(){return h(this,ur)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=h(this,Wa).defaultQueryOptions(e),r=h(this,Wa).getQueryCache().build(h(this,Wa),t);return r.fetch().then(()=>this.createResult(r,t))}fetch(e){return q(this,qr,Zw).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),h(this,fa)))}createResult(e,t){var A;const r=h(this,ur),i=this.options,o=h(this,fa),a=h(this,Pm),l=h(this,gb),c=e!==r?e.state:h(this,Jj),{state:u}=e;let f={...u},p=!1,g;if(t._optimisticResults){const D=this.hasListeners(),P=!D&&nO(e,t),L=D&&rO(e,r,t,i);(P||L)&&(f={...f,...O9(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:v}=f;g=f.data;let x=!1;if(t.placeholderData!==void 0&&g===void 0&&v==="pending"){let D;o!=null&&o.isPlaceholderData&&t.placeholderData===(l==null?void 0:l.placeholderData)?(D=o.data,x=!0):D=typeof t.placeholderData=="function"?t.placeholderData((A=h(this,yb))==null?void 0:A.state.data,h(this,yb)):t.placeholderData,D!==void 0&&(v="success",g=JR(o==null?void 0:o.data,D,t),p=!0)}if(t.select&&g!==void 0&&!x)if(o&&g===(a==null?void 0:a.data)&&t.select===h(this,ek))g=h(this,mb);else try{R(this,ek,t.select),g=t.select(g),g=JR(o==null?void 0:o.data,g,t),R(this,mb,g),R(this,dp,null)}catch(D){R(this,dp,D)}h(this,dp)&&(m=h(this,dp),g=h(this,mb),y=Date.now(),v="error");const w=f.fetchStatus==="fetching",S=v==="pending",_=v==="error",b=S&&w,C=g!==void 0,F={status:v,fetchStatus:f.fetchStatus,isPending:S,isSuccess:v==="success",isError:_,isInitialLoading:b,isLoading:b,data:g,dataUpdatedAt:f.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:f.dataUpdateCount>c.dataUpdateCount||f.errorUpdateCount>c.errorUpdateCount,isFetching:w,isRefetching:w&&!S,isLoadingError:_&&!C,isPaused:f.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:_&&C,isStale:k6(e,t),refetch:this.refetch,promise:h(this,jh),isEnabled:Ml(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const D=F.data!==void 0,P=F.status==="error"&&!D,L=U=>{P?U.reject(F.error):D&&U.resolve(F.data)},W=()=>{const U=R(this,jh,F.promise=eB());L(U)},O=h(this,jh);switch(O.status){case"pending":e.queryHash===r.queryHash&&L(O);break;case"fulfilled":(P||F.data!==O.value)&&W();break;case"rejected":(!P||F.error!==O.reason)&&W();break}}return F}updateResult(){const e=h(this,fa),t=this.createResult(h(this,ur),this.options);if(R(this,Pm,h(this,ur).state),R(this,gb,this.options),h(this,Pm).data!==void 0&&R(this,yb,h(this,ur)),WA(t,e))return;R(this,fa,t);const r=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!h(this,xb).size)return!0;const a=new Set(o??h(this,xb));return this.options.throwOnError&&a.add("error"),Object.keys(h(this,fa)).some(l=>{const d=l;return h(this,fa)[d]!==e[d]&&a.has(d)})};q(this,qr,L9).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,qr,sB).call(this)}},Wa=new WeakMap,ur=new WeakMap,Jj=new WeakMap,fa=new WeakMap,Pm=new WeakMap,gb=new WeakMap,jh=new WeakMap,dp=new WeakMap,ek=new WeakMap,mb=new WeakMap,yb=new WeakMap,Rm=new WeakMap,Bm=new WeakMap,cp=new WeakMap,xb=new WeakMap,qr=new WeakSet,Zw=function(e){q(this,qr,lB).call(this);let t=h(this,ur).fetch(this.options,e);return e!=null&&e.throwOnError||(t=t.catch(wa)),t},nB=function(){q(this,qr,oB).call(this);const e=Ag(this.options.staleTime,h(this,ur));if(Aj.isServer()||h(this,fa).isStale||!$R(e))return;const r=E9(h(this,fa).dataUpdatedAt,e)+1;R(this,Rm,xm.setTimeout(()=>{h(this,fa).isStale||this.updateResult()},r))},rB=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(h(this,ur)):this.options.refetchInterval)??!1},iB=function(e){q(this,qr,aB).call(this),R(this,cp,e),!(Aj.isServer()||Ml(this.options.enabled,h(this,ur))===!1||!$R(h(this,cp))||h(this,cp)===0)&&R(this,Bm,xm.setInterval(()=>{(this.options.refetchIntervalInBackground||v6.isFocused())&&q(this,qr,Zw).call(this)},h(this,cp)))},sB=function(){q(this,qr,nB).call(this),q(this,qr,iB).call(this,q(this,qr,rB).call(this))},oB=function(){h(this,Rm)!==void 0&&(xm.clearTimeout(h(this,Rm)),R(this,Rm,void 0))},aB=function(){h(this,Bm)!==void 0&&(xm.clearInterval(h(this,Bm)),R(this,Bm,void 0))},lB=function(){const e=h(this,Wa).getQueryCache().build(h(this,Wa),this.options);if(e===h(this,ur))return;const t=h(this,ur);R(this,ur,e),R(this,Jj,e.state),this.hasListeners()&&(t==null||t.removeObserver(this),e.addObserver(this))},L9=function(e){Ls.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(h(this,fa))}),h(this,Wa).getQueryCache().notify({query:h(this,ur),type:"observerResultsUpdated"})})},e7);function LZ(n,e){return Ml(e.enabled,n)!==!1&&n.state.data===void 0&&!(n.state.status==="error"&&Ml(e.retryOnMount,n)===!1)}function nO(n,e){return LZ(n,e)||n.state.data!==void 0&&dB(n,e,e.refetchOnMount)}function dB(n,e,t){if(Ml(e.enabled,n)!==!1&&Ag(e.staleTime,n)!=="static"){const r=typeof t=="function"?t(n):t;return r==="always"||r!==!1&&k6(n,e)}return!1}function rO(n,e,t,r){return(n!==e||Ml(r.enabled,n)===!1)&&(!t.suspense||n.state.status!=="error")&&k6(n,t)}function k6(n,e){return Ml(e.enabled,n)!==!1&&n.isStaleByTime(Ag(e.staleTime,n))}function NZ(n,e){return!WA(n.getCurrentResult(),e)}var tk,eu,Qo,Im,tu,Xf,t7,WZ=(t7=class extends M9{constructor(e){super();N(this,tu);N(this,tk);N(this,eu);N(this,Qo);N(this,Im);R(this,tk,e.client),this.mutationId=e.mutationId,R(this,Qo,e.mutationCache),R(this,eu,[]),this.state=e.state||N9(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){h(this,eu).includes(e)||(h(this,eu).push(e),this.clearGcTimeout(),h(this,Qo).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){R(this,eu,h(this,eu).filter(t=>t!==e)),this.scheduleGc(),h(this,Qo).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){h(this,eu).length||(this.state.status==="pending"?this.scheduleGc():h(this,Qo).remove(this))}continue(){var e;return((e=h(this,Im))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,d,c,u,f,p,g,m,y,v,x,w,S,_,b,C,T;const t=()=>{q(this,tu,Xf).call(this,{type:"continue"})},r={client:h(this,tk),meta:this.options.meta,mutationKey:this.options.mutationKey};R(this,Im,I9({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(F,A)=>{q(this,tu,Xf).call(this,{type:"failed",failureCount:F,error:A})},onPause:()=>{q(this,tu,Xf).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>h(this,Qo).canRun(this)}));const i=this.state.status==="pending",o=!h(this,Im).canStart();try{if(i)t();else{q(this,tu,Xf).call(this,{type:"pending",variables:e,isPaused:o}),h(this,Qo).config.onMutate&&await h(this,Qo).config.onMutate(e,this,r);const A=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,r));A!==this.state.context&&q(this,tu,Xf).call(this,{type:"pending",context:A,variables:e,isPaused:o})}const F=await h(this,Im).start();return await((c=(d=h(this,Qo).config).onSuccess)==null?void 0:c.call(d,F,e,this.state.context,this,r)),await((f=(u=this.options).onSuccess)==null?void 0:f.call(u,F,e,this.state.context,r)),await((g=(p=h(this,Qo).config).onSettled)==null?void 0:g.call(p,F,null,this.state.variables,this.state.context,this,r)),await((y=(m=this.options).onSettled)==null?void 0:y.call(m,F,null,e,this.state.context,r)),q(this,tu,Xf).call(this,{type:"success",data:F}),F}catch(F){try{await((x=(v=h(this,Qo).config).onError)==null?void 0:x.call(v,F,e,this.state.context,this,r))}catch(A){Promise.reject(A)}try{await((S=(w=this.options).onError)==null?void 0:S.call(w,F,e,this.state.context,r))}catch(A){Promise.reject(A)}try{await((b=(_=h(this,Qo).config).onSettled)==null?void 0:b.call(_,void 0,F,this.state.variables,this.state.context,this,r))}catch(A){Promise.reject(A)}try{await((T=(C=this.options).onSettled)==null?void 0:T.call(C,void 0,F,e,this.state.context,r))}catch(A){Promise.reject(A)}throw q(this,tu,Xf).call(this,{type:"error",error:F}),F}finally{h(this,Qo).runNext(this)}}},tk=new WeakMap,eu=new WeakMap,Qo=new WeakMap,Im=new WeakMap,tu=new WeakSet,Xf=function(e){const t=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Ls.batch(()=>{h(this,eu).forEach(r=>{r.onMutationUpdate(e)}),h(this,Qo).notify({mutation:this,type:"updated",action:e})})},t7);function N9(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var kh,lc,nk,n7,UZ=(n7=class extends g1{constructor(e={}){super();N(this,kh);N(this,lc);N(this,nk);this.config=e,R(this,kh,new Set),R(this,lc,new Map),R(this,nk,0)}build(e,t,r){const i=new WZ({client:e,mutationCache:this,mutationId:++Gi(this,nk)._,options:e.defaultMutationOptions(t),state:r});return this.add(i),i}add(e){h(this,kh).add(e);const t=f2(e);if(typeof t=="string"){const r=h(this,lc).get(t);r?r.push(e):h(this,lc).set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(h(this,kh).delete(e)){const t=f2(e);if(typeof t=="string"){const r=h(this,lc).get(t);if(r)if(r.length>1){const i=r.indexOf(e);i!==-1&&r.splice(i,1)}else r[0]===e&&h(this,lc).delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=f2(e);if(typeof t=="string"){const r=h(this,lc).get(t),i=r==null?void 0:r.find(o=>o.state.status==="pending");return!i||i===e}else return!0}runNext(e){var r;const t=f2(e);if(typeof t=="string"){const i=(r=h(this,lc).get(t))==null?void 0:r.find(o=>o!==e&&o.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ls.batch(()=>{h(this,kh).forEach(e=>{this.notify({type:"removed",mutation:e})}),h(this,kh).clear(),h(this,lc).clear()})}getAll(){return Array.from(h(this,kh))}find(e){const t={exact:!0,...e};return this.getAll().find(r=>Qz(t,r))}findAll(e={}){return this.getAll().filter(t=>Qz(e,t))}notify(e){Ls.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Ls.batch(()=>Promise.all(e.map(t=>t.continue().catch(wa))))}},kh=new WeakMap,lc=new WeakMap,nk=new WeakMap,n7);function f2(n){var e;return(e=n.options.scope)==null?void 0:e.id}var _h,up,Ua,Ch,xf,h5,cB,r7,HZ=(r7=class extends g1{constructor(t,r){super();N(this,xf);N(this,_h);N(this,up);N(this,Ua);N(this,Ch);R(this,_h,t),this.setOptions(r),this.bindMethods(),q(this,xf,h5).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){var i;const r=this.options;this.options=h(this,_h).defaultMutationOptions(t),WA(this.options,r)||h(this,_h).getMutationCache().notify({type:"observerOptionsUpdated",mutation:h(this,Ua),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&p0(r.mutationKey)!==p0(this.options.mutationKey)?this.reset():((i=h(this,Ua))==null?void 0:i.state.status)==="pending"&&h(this,Ua).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=h(this,Ua))==null||t.removeObserver(this)}onMutationUpdate(t){q(this,xf,h5).call(this),q(this,xf,cB).call(this,t)}getCurrentResult(){return h(this,up)}reset(){var t;(t=h(this,Ua))==null||t.removeObserver(this),R(this,Ua,void 0),q(this,xf,h5).call(this),q(this,xf,cB).call(this)}mutate(t,r){var i;return R(this,Ch,r),(i=h(this,Ua))==null||i.removeObserver(this),R(this,Ua,h(this,_h).getMutationCache().build(h(this,_h),this.options)),h(this,Ua).addObserver(this),h(this,Ua).execute(t)}},_h=new WeakMap,up=new WeakMap,Ua=new WeakMap,Ch=new WeakMap,xf=new WeakSet,h5=function(){var r;const t=((r=h(this,Ua))==null?void 0:r.state)??N9();R(this,up,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},cB=function(t){Ls.batch(()=>{var r,i,o,a,l,d,c,u;if(h(this,Ch)&&this.hasListeners()){const f=h(this,up).variables,p=h(this,up).context,g={client:h(this,_h),meta:this.options.meta,mutationKey:this.options.mutationKey};if((t==null?void 0:t.type)==="success"){try{(i=(r=h(this,Ch)).onSuccess)==null||i.call(r,t.data,f,p,g)}catch(m){Promise.reject(m)}try{(a=(o=h(this,Ch)).onSettled)==null||a.call(o,t.data,null,f,p,g)}catch(m){Promise.reject(m)}}else if((t==null?void 0:t.type)==="error"){try{(d=(l=h(this,Ch)).onError)==null||d.call(l,t.error,f,p,g)}catch(m){Promise.reject(m)}try{(u=(c=h(this,Ch)).onSettled)==null||u.call(c,void 0,t.error,f,p,g)}catch(m){Promise.reject(m)}}}this.listeners.forEach(f=>{f(h(this,up))})})},r7),nu,i7,qZ=(i7=class extends g1{constructor(e={}){super();N(this,nu);this.config=e,R(this,nu,new Map)}build(e,t,r){const i=t.queryKey,o=t.queryHash??w6(i,t);let a=this.get(o);return a||(a=new zZ({client:e,queryKey:i,queryHash:o,options:e.defaultQueryOptions(t),state:r,defaultOptions:e.getQueryDefaults(i)}),this.add(a)),a}add(e){h(this,nu).has(e.queryHash)||(h(this,nu).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=h(this,nu).get(e.queryHash);t&&(e.destroy(),t===e&&h(this,nu).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ls.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return h(this,nu).get(e)}getAll(){return[...h(this,nu).values()]}find(e){const t={exact:!0,...e};return this.getAll().find(r=>Yz(t,r))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(r=>Yz(e,r)):t}notify(e){Ls.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Ls.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ls.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},nu=new WeakMap,i7),os,hp,fp,bb,vb,pp,wb,Sb,s7,VZ=(s7=class{constructor(n={}){N(this,os);N(this,hp);N(this,fp);N(this,bb);N(this,vb);N(this,pp);N(this,wb);N(this,Sb);R(this,os,n.queryCache||new qZ),R(this,hp,n.mutationCache||new UZ),R(this,fp,n.defaultOptions||{}),R(this,bb,new Map),R(this,vb,new Map),R(this,pp,0)}mount(){Gi(this,pp)._++,h(this,pp)===1&&(R(this,wb,v6.subscribe(async n=>{n&&(await this.resumePausedMutations(),h(this,os).onFocus())})),R(this,Sb,UA.subscribe(async n=>{n&&(await this.resumePausedMutations(),h(this,os).onOnline())})))}unmount(){var n,e;Gi(this,pp)._--,h(this,pp)===0&&((n=h(this,wb))==null||n.call(this),R(this,wb,void 0),(e=h(this,Sb))==null||e.call(this),R(this,Sb,void 0))}isFetching(n){return h(this,os).findAll({...n,fetchStatus:"fetching"}).length}isMutating(n){return h(this,hp).findAll({...n,status:"pending"}).length}getQueryData(n){var t;const e=this.defaultQueryOptions({queryKey:n});return(t=h(this,os).get(e.queryHash))==null?void 0:t.state.data}ensureQueryData(n){const e=this.defaultQueryOptions(n),t=h(this,os).build(this,e),r=t.state.data;return r===void 0?this.fetchQuery(n):(n.revalidateIfStale&&t.isStaleByTime(Ag(e.staleTime,t))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(n){return h(this,os).findAll(n).map(({queryKey:e,state:t})=>{const r=t.data;return[e,r]})}setQueryData(n,e,t){const r=this.defaultQueryOptions({queryKey:n}),i=h(this,os).get(r.queryHash),o=i==null?void 0:i.state.data,a=_Z(e,o);if(a!==void 0)return h(this,os).build(this,r).setData(a,{...t,manual:!0})}setQueriesData(n,e,t){return Ls.batch(()=>h(this,os).findAll(n).map(({queryKey:r})=>[r,this.setQueryData(r,e,t)]))}getQueryState(n){var t;const e=this.defaultQueryOptions({queryKey:n});return(t=h(this,os).get(e.queryHash))==null?void 0:t.state}removeQueries(n){const e=h(this,os);Ls.batch(()=>{e.findAll(n).forEach(t=>{e.remove(t)})})}resetQueries(n,e){const t=h(this,os);return Ls.batch(()=>(t.findAll(n).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...n},e)))}cancelQueries(n,e={}){const t={revert:!0,...e},r=Ls.batch(()=>h(this,os).findAll(n).map(i=>i.cancel(t)));return Promise.all(r).then(wa).catch(wa)}invalidateQueries(n,e={}){return Ls.batch(()=>(h(this,os).findAll(n).forEach(t=>{t.invalidate()}),(n==null?void 0:n.refetchType)==="none"?Promise.resolve():this.refetchQueries({...n,type:(n==null?void 0:n.refetchType)??(n==null?void 0:n.type)??"active"},e)))}refetchQueries(n,e={}){const t={...e,cancelRefetch:e.cancelRefetch??!0},r=Ls.batch(()=>h(this,os).findAll(n).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,t);return t.throwOnError||(o=o.catch(wa)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(wa)}fetchQuery(n){const e=this.defaultQueryOptions(n);e.retry===void 0&&(e.retry=!1);const t=h(this,os).build(this,e);return t.isStaleByTime(Ag(e.staleTime,t))?t.fetch(e):Promise.resolve(t.state.data)}prefetchQuery(n){return this.fetchQuery(n).then(wa).catch(wa)}fetchInfiniteQuery(n){return n._type="infinite",this.fetchQuery(n)}prefetchInfiniteQuery(n){return this.fetchInfiniteQuery(n).then(wa).catch(wa)}ensureInfiniteQueryData(n){return n._type="infinite",this.ensureQueryData(n)}resumePausedMutations(){return UA.isOnline()?h(this,hp).resumePausedMutations():Promise.resolve()}getQueryCache(){return h(this,os)}getMutationCache(){return h(this,hp)}getDefaultOptions(){return h(this,fp)}setDefaultOptions(n){R(this,fp,n)}setQueryDefaults(n,e){h(this,bb).set(p0(n),{queryKey:n,defaultOptions:e})}getQueryDefaults(n){const e=[...h(this,bb).values()],t={};return e.forEach(r=>{Cj(n,r.queryKey)&&Object.assign(t,r.defaultOptions)}),t}setMutationDefaults(n,e){h(this,vb).set(p0(n),{mutationKey:n,defaultOptions:e})}getMutationDefaults(n){const e=[...h(this,vb).values()],t={};return e.forEach(r=>{Cj(n,r.mutationKey)&&Object.assign(t,r.defaultOptions)}),t}defaultQueryOptions(n){if(n._defaulted)return n;const e={...h(this,fp).queries,...this.getQueryDefaults(n.queryKey),...n,_defaulted:!0};return e.queryHash||(e.queryHash=w6(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===S6&&(e.enabled=!1),e}defaultMutationOptions(n){return n!=null&&n._defaulted?n:{...h(this,fp).mutations,...(n==null?void 0:n.mutationKey)&&this.getMutationDefaults(n.mutationKey),...n,_defaulted:!0}}clear(){h(this,os).clear(),h(this,hp).clear()}},os=new WeakMap,hp=new WeakMap,fp=new WeakMap,bb=new WeakMap,vb=new WeakMap,pp=new WeakMap,wb=new WeakMap,Sb=new WeakMap,s7),W9=k.createContext(void 0),pi=n=>{const e=k.useContext(W9);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},GZ=({client:n,children:e})=>(k.useEffect(()=>(n.mount(),()=>{n.unmount()}),[n]),s.jsx(W9.Provider,{value:n,children:e})),U9=k.createContext(!1),KZ=()=>k.useContext(U9);U9.Provider;function XZ(){let n=!1;return{clearReset:()=>{n=!1},reset:()=>{n=!0},isReset:()=>n}}var YZ=k.createContext(XZ()),QZ=()=>k.useContext(YZ),$Z=(n,e,t)=>{const r=t!=null&&t.state.error&&typeof n.throwOnError=="function"?j6(n.throwOnError,[t.state.error,t]):n.throwOnError;(n.suspense||n.experimental_prefetchInRender||r)&&(e.isReset()||(n.retryOnMount=!1))},ZZ=n=>{k.useEffect(()=>{n.clearReset()},[n])},JZ=({result:n,errorResetBoundary:e,throwOnError:t,query:r,suspense:i})=>n.isError&&!e.isReset()&&!n.isFetching&&r&&(i&&n.data===void 0||j6(t,[n.error,r])),eJ=n=>{if(n.suspense){const t=i=>i==="static"?i:Math.max(i??1e3,1e3),r=n.staleTime;n.staleTime=typeof r=="function"?(...i)=>t(r(...i)):t(r),typeof n.gcTime=="number"&&(n.gcTime=Math.max(n.gcTime,1e3))}},tJ=(n,e)=>n.isLoading&&n.isFetching&&!e,nJ=(n,e)=>(n==null?void 0:n.suspense)&&e.isPending,iO=(n,e,t)=>e.fetchOptimistic(n).catch(()=>{t.clearReset()});function rJ(n,e,t){var g,m,y,v;const r=KZ(),i=QZ(),o=pi(),a=o.defaultQueryOptions(n);(m=(g=o.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||m.call(g,a);const l=o.getQueryCache().get(a.queryHash),d=n.subscribed!==!1;a._optimisticResults=r?"isRestoring":d?"optimistic":void 0,eJ(a),$Z(a,i,l),ZZ(i);const c=!o.getQueryCache().get(a.queryHash),[u]=k.useState(()=>new e(o,a)),f=u.getOptimisticResult(a),p=!r&&d;if(k.useSyncExternalStore(k.useCallback(x=>{const w=p?u.subscribe(Ls.batchCalls(x)):wa;return u.updateResult(),w},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),k.useEffect(()=>{u.setOptions(a)},[a,u]),nJ(a,f))throw iO(a,u,i);if(JZ({result:f,errorResetBoundary:i,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw f.error;if((v=(y=o.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||v.call(y,a,f),a.experimental_prefetchInRender&&!Aj.isServer()&&tJ(f,r)){const x=c?iO(a,u,i):l==null?void 0:l.promise;x==null||x.catch(wa).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?f:u.trackResult(f)}function Oe(n,e){return rJ(n,OZ)}function Ue(n,e){const t=pi(),[r]=k.useState(()=>new HZ(t,n));k.useEffect(()=>{r.setOptions(n)},[r,n]);const i=k.useSyncExternalStore(k.useCallback(a=>r.subscribe(Ls.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=k.useCallback((a,l)=>{r.mutate(a,l).catch(wa)},[r]);if(i.error&&j6(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}const H9=k.createContext(null);function gn(){const n=k.useContext(H9);if(!n)throw new Error("useAuth outside AuthGate");return n}function iJ({children:n}){const[e,t]=k.useState(null),[r,i]=k.useState(!0);if(k.useEffect(()=>{fetch("/kitchen/api/auth/verify?app=kitchen",{credentials:"include"}).then(a=>{if(!a.ok)throw new Error("unauth");return a.json()}).then(a=>t({email:a.email||a.sub||"",name:a.name||a.display_name||"",is_admin:a.is_admin??!1,caps:a.caps??[]})).catch(()=>{(window.top??window).location.href="/login"}).finally(()=>i(!1))},[]),r)return s.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--navy-dark)"},children:s.jsx("div",{className:"spinner",style:{width:32,height:32}})});if(!e)return null;const o={user:e,token:"__session__",restrictedPages:[],login:()=>{},logout:()=>{(window.top??window).location.href="/login"}};return s.jsx(H9.Provider,{value:o,children:n})}/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sJ=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),q9=(...n)=>n.filter((e,t,r)=>!!e&&r.indexOf(e)===t).join(" ");/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var oJ={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aJ=k.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:r,className:i="",children:o,iconNode:a,...l},d)=>k.createElement("svg",{ref:d,...oJ,width:e,height:e,stroke:n,strokeWidth:r?Number(t)*24/Number(e):t,className:q9("lucide",i),...l},[...a.map(([c,u])=>k.createElement(c,u)),...Array.isArray(o)?o:[o]]));/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mi=(n,e)=>{const t=k.forwardRef(({className:r,...i},o)=>k.createElement(aJ,{ref:o,iconNode:e,className:q9(`lucide-${sJ(n)}`,r),...i}));return t.displayName=`${n}`,t};/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lJ=Mi("Activity",[["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"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sO=Mi("BarChart2",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dJ=Mi("BookOpen",[["path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z",key:"vv98re"}],["path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",key:"1cyq3y"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cJ=Mi("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sP=Mi("ChefHat",[["path",{d:"M17 21a1 1 0 0 0 1-1v-5.35c0-.457.316-.844.727-1.041a4 4 0 0 0-2.134-7.589 5 5 0 0 0-9.186 0 4 4 0 0 0-2.134 7.588c.411.198.727.585.727 1.041V20a1 1 0 0 0 1 1Z",key:"1qvrer"}],["path",{d:"M6 17h12",key:"1jwigz"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uJ=Mi("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hJ=Mi("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fJ=Mi("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pJ=Mi("Hotel",[["path",{d:"M10 22v-6.57",key:"1wmca3"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M12 7h.01",key:"1ivr5q"}],["path",{d:"M14 15.43V22",key:"1q2vjd"}],["path",{d:"M15 16a5 5 0 0 0-6 0",key:"o9wqvi"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 7h.01",key:"1vti4s"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gJ=Mi("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mJ=Mi("List",[["line",{x1:"8",x2:"21",y1:"6",y2:"6",key:"7ey8pc"}],["line",{x1:"8",x2:"21",y1:"12",y2:"12",key:"rjfblc"}],["line",{x1:"8",x2:"21",y1:"18",y2:"18",key:"c3b1m8"}],["line",{x1:"3",x2:"3.01",y1:"6",y2:"6",key:"1g7gq3"}],["line",{x1:"3",x2:"3.01",y1:"12",y2:"12",key:"1pjlvk"}],["line",{x1:"3",x2:"3.01",y1:"18",y2:"18",key:"28t2mc"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yJ=Mi("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xJ=Mi("Package",[["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oO=Mi("PieChart",[["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}],["path",{d:"M22 12A10 10 0 0 0 12 2v10z",key:"1rfc4y"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bJ=Mi("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vJ=Mi("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wJ=Mi("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SJ=Mi("ShieldCheck",[["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"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jJ=Mi("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aO=Mi("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kJ=Mi("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _J=Mi("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CJ=Mi("UtensilsCrossed",[["path",{d:"m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8",key:"n7qcjb"}],["path",{d:"M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7",key:"d0u48b"}],["path",{d:"m2.1 21.8 6.4-6.3",key:"yn04lh"}],["path",{d:"m19 5-7 7",key:"194lzd"}]]);/** * @license lucide-react v0.395.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AJ=Mi("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);function Ma(n,e){return n?n.is_admin||n.caps.includes(e):!1}const TJ={size:15,strokeWidth:1.75};function dx({label:n,children:e}){return s.jsxs("div",{className:"sidebar-section",children:[s.jsx("div",{className:"sidebar-section-label",children:n}),e]})}function hi({to:n,label:e,icon:t}){return s.jsxs(wx,{to:n,className:({isActive:r})=>r?"active":"",children:[s.jsx(t,{...TJ}),e]})}function FJ(){const{user:n}=gn();return s.jsxs("div",{className:"app-shell",children:[s.jsxs("aside",{className:"sidebar",children:[s.jsxs("div",{className:"sidebar-logo",children:[s.jsx(sP,{size:18,strokeWidth:1.75,color:"var(--app-primary)"}),"Kitchen"]}),s.jsxs("nav",{className:"sidebar-nav",children:[s.jsx(hi,{to:"/dashboard",label:"Dashboard",icon:gJ}),Ma(n,"invoices")&&s.jsxs(dx,{label:"Invoices",children:[s.jsx(hi,{to:"/upload",label:"Upload",icon:kJ}),s.jsx(hi,{to:"/invoices",label:"Invoices",icon:fJ}),s.jsx(hi,{to:"/search/invoices",label:"Search",icon:vJ}),s.jsx(hi,{to:"/search/line-items",label:"Line Items",icon:mJ}),Ma(n,"disputes")&&s.jsx(hi,{to:"/disputes",label:"Disputes",icon:hJ}),Ma(n,"orders")&&s.jsx(hi,{to:"/purchase-orders",label:"Purchase Orders",icon:jJ})]}),Ma(n,"view")&&s.jsxs(dx,{label:"Reports",children:[s.jsx(hi,{to:"/gp",label:"Kitchen Flash",icon:aO}),s.jsx(hi,{to:"/purchases-report",label:"Purchases",icon:sO}),s.jsx(hi,{to:"/allowances-report",label:"Allowances",icon:oO}),s.jsx(hi,{to:"/sales-gp",label:"Sales GP%",icon:lJ}),s.jsx(hi,{to:"/usage-variance",label:"Usage Variance",icon:uJ}),s.jsx(hi,{to:"/purchases/reconcile",label:"Reconcile",icon:bJ})]}),Ma(n,"logbook")&&s.jsxs(dx,{label:"Kitchen",children:[s.jsx(hi,{to:"/logbook",label:"Allowance Logbook",icon:dJ}),s.jsx(hi,{to:"/budget",label:"Budget",icon:oO}),Ma(n,"orders")&&s.jsx(hi,{to:"/event-orders",label:"Event Orders",icon:xJ})]}),Ma(n,"view")&&s.jsxs(dx,{label:"Bookings",children:[s.jsx(hi,{to:"/resos",label:"ResOS Calendar",icon:cJ}),s.jsx(hi,{to:"/resos-stats",label:"Booking Stats",icon:sO}),s.jsx(hi,{to:"/residents-table-chart",label:"Residents Chart",icon:_J}),s.jsx(hi,{to:"/newbook",label:"NewBook Data",icon:pJ})]}),Ma(n,"recipes")&&s.jsxs(dx,{label:"Recipes",children:[s.jsx(hi,{to:"/ingredients",label:"Ingredients",icon:AJ}),s.jsx(hi,{to:"/recipes",label:"Recipes",icon:sP}),s.jsx(hi,{to:"/dishes",label:"Dishes",icon:CJ}),Ma(n,"menus")&&s.jsx(hi,{to:"/menus",label:"Menus",icon:yJ}),s.jsx(hi,{to:"/allergens",label:"Allergens",icon:SJ}),s.jsx(hi,{to:"/price-impact",label:"Price Impact",icon:aO})]}),Ma(n,"settings")&&s.jsx(dx,{label:"",children:s.jsx(hi,{to:"/settings",label:"Settings",icon:wJ})})]}),s.jsx("div",{className:"sidebar-user",children:n.name||n.email})]}),s.jsxs("header",{className:"top-bar",children:[s.jsx(sP,{size:16,strokeWidth:1.75,color:"var(--app-primary)"}),s.jsx("span",{className:"top-bar-title",children:"Kitchen"}),s.jsxs("nav",{className:"top-bar-nav",children:[s.jsx(wx,{to:"/dashboard",className:({isActive:e})=>e?"active":"",children:"Dashboard"}),Ma(n,"invoices")&&s.jsx(wx,{to:"/invoices",className:({isActive:e})=>e?"active":"",children:"Invoices"}),Ma(n,"view")&&s.jsx(wx,{to:"/gp",className:({isActive:e})=>e?"active":"",children:"Reports"}),Ma(n,"recipes")&&s.jsx(wx,{to:"/recipes",className:({isActive:e})=>e?"active":"",children:"Recipes"}),Ma(n,"settings")&&s.jsx(wx,{to:"/settings",className:({isActive:e})=>e?"active":"",children:"Settings"})]})]}),s.jsx("main",{className:"page-content",children:s.jsx(nZ,{})})]})}function DJ(){const{token:n}=gn(),e=pi(),[t,r]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(""),[d,c]=k.useState([]),[u,f]=k.useState(""),[p,g]=k.useState(!1),[m,y]=k.useState(""),[v,x]=k.useState(""),[w,S]=k.useState(null),{data:_,isLoading:b}=Oe({queryKey:["suppliers"],queryFn:async()=>{const I=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!I.ok)throw new Error("Failed to fetch suppliers");return I.json()}}),C=Ue({mutationFn:async({name:I,aliases:H,skip_dext:z,order_email:G,account_number:te})=>{const re=await fetch("/api/suppliers/",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:I,aliases:H,skip_dext:z,order_email:G||null,account_number:te||null})});if(!re.ok)throw new Error("Failed to create supplier");return re.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["suppliers"]}),r(!1),l(""),c([]),f(""),g(!1),y(""),x("")}}),T=Ue({mutationFn:async({id:I,name:H,aliases:z,skip_dext:G,order_email:te,account_number:re})=>{const me=await fetch(`/api/suppliers/${I}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:H,aliases:z,skip_dext:G,order_email:te||null,account_number:re||null})});if(!me.ok)throw new Error("Failed to update supplier");return me.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["suppliers"]}),o(null),l(""),c([]),f(""),g(!1),y(""),x("")}}),F=Ue({mutationFn:async I=>{const H=await fetch(`/api/suppliers/${I}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!H.ok)throw new Error("Failed to delete supplier");return H.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["suppliers"]}),S(null)}}),A=()=>{a.trim()&&C.mutate({name:a.trim(),aliases:d,skip_dext:p,order_email:m,account_number:v})},D=()=>{i&&a.trim()&&T.mutate({id:i.id,name:a.trim(),aliases:d,skip_dext:p,order_email:m,account_number:v})},P=I=>{o(I),l(I.name),c(I.aliases||[]),f(""),g(I.skip_dext||!1),y(I.order_email||""),x(I.account_number||"")},L=()=>{const I=u.trim();I&&!d.includes(I)&&(c([...d,I]),f(""))},W=I=>{c(d.filter(H=>H!==I))},O=I=>{I.key==="Enter"&&(I.preventDefault(),L())},U=()=>{r(!1),l(""),c([]),f(""),g(!1),y(""),x("")},M=()=>{o(null),l(""),c([]),f(""),g(!1),y(""),x("")};return b?s.jsx("div",{style:Pt.loading,children:"Loading suppliers..."}):s.jsxs("div",{children:[s.jsxs("div",{style:Pt.header,children:[s.jsx("h2",{style:Pt.title,children:"Suppliers"}),s.jsx("button",{onClick:()=>r(!0),style:Pt.addBtn,children:"+ Add Supplier"})]}),s.jsx("p",{style:Pt.hint,children:'Define your suppliers here. Add aliases for suppliers that appear with different names on invoices (e.g., "US Foods", "USF", "U.S. Foods Inc").'}),_&&_.length===0?s.jsxs("div",{style:Pt.empty,children:[s.jsx("p",{children:"No suppliers defined yet."}),s.jsx("p",{style:Pt.emptyHint,children:"Add your first supplier to start organizing invoices by vendor."})]}):s.jsx("div",{style:Pt.list,children:_==null?void 0:_.map(I=>s.jsxs("div",{style:Pt.card,children:[s.jsxs("div",{style:Pt.cardMain,children:[s.jsxs("span",{style:Pt.supplierName,children:[I.name,I.skip_dext&&s.jsx("span",{style:Pt.skipDextBadge,children:"Skip Dext"})]}),I.aliases&&I.aliases.length>0&&s.jsxs("div",{style:Pt.aliasesList,children:[s.jsx("span",{style:Pt.aliasesLabel,children:"Also known as: "}),I.aliases.map((H,z)=>s.jsxs("span",{style:Pt.aliasTag,children:[H,zP(I),style:Pt.editBtn,children:"Edit"}),s.jsx("button",{onClick:()=>S(I.id),style:Pt.deleteBtn,children:"Delete"})]})]},I.id))}),t&&s.jsx("div",{style:Pt.modalOverlay,onClick:U,children:s.jsxs("div",{style:Pt.modal,onClick:I=>I.stopPropagation(),children:[s.jsx("h3",{children:"Add Supplier"}),s.jsxs("label",{style:Pt.label,children:["Primary Name",s.jsx("input",{type:"text",value:a,onChange:I=>l(I.target.value),style:Pt.input,placeholder:"e.g., Sysco",autoFocus:!0})]}),s.jsxs("label",{style:Pt.label,children:["Aliases (alternative names on invoices)",s.jsxs("div",{style:Pt.aliasInputRow,children:[s.jsx("input",{type:"text",value:u,onChange:I=>f(I.target.value),onKeyDown:O,style:{...Pt.input,flex:1},placeholder:"e.g., SYSCO FOODS"}),s.jsx("button",{type:"button",onClick:L,style:Pt.addAliasBtn,children:"Add"})]}),d.length>0&&s.jsx("div",{style:Pt.aliasTagsContainer,children:d.map(I=>s.jsxs("span",{style:Pt.aliasTagEditable,children:[I,s.jsx("button",{type:"button",onClick:()=>W(I),style:Pt.removeAliasBtn,children:"x"})]},I))})]}),s.jsxs("label",{style:Pt.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:I=>g(I.target.checked),style:Pt.checkbox}),s.jsx("span",{children:"Don't Forward to Dext"}),s.jsx("span",{style:Pt.checkboxHint,children:"Invoices from this supplier won't be sent to Dext"})]}),s.jsxs("div",{style:Pt.poFieldsSection,children:[s.jsx("h4",{style:Pt.poFieldsTitle,children:"Purchase Order Details"}),s.jsxs("label",{style:Pt.label,children:["Order Email",s.jsx("input",{type:"email",value:m,onChange:I=>y(I.target.value),style:Pt.input,placeholder:"orders@supplier.com"})]}),s.jsxs("label",{style:Pt.label,children:["Account Number",s.jsx("input",{type:"text",value:v,onChange:I=>x(I.target.value),style:Pt.input,placeholder:"e.g., ACC-12345"})]})]}),s.jsxs("div",{style:Pt.modalActions,children:[s.jsx("button",{onClick:U,style:Pt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:A,style:Pt.saveBtn,disabled:!a.trim()||C.isPending,children:C.isPending?"Adding...":"Add Supplier"})]})]})}),i&&s.jsx("div",{style:Pt.modalOverlay,onClick:M,children:s.jsxs("div",{style:Pt.modal,onClick:I=>I.stopPropagation(),children:[s.jsx("h3",{children:"Edit Supplier"}),s.jsxs("label",{style:Pt.label,children:["Primary Name",s.jsx("input",{type:"text",value:a,onChange:I=>l(I.target.value),style:Pt.input,autoFocus:!0})]}),s.jsxs("label",{style:Pt.label,children:["Aliases (alternative names on invoices)",s.jsxs("div",{style:Pt.aliasInputRow,children:[s.jsx("input",{type:"text",value:u,onChange:I=>f(I.target.value),onKeyDown:O,style:{...Pt.input,flex:1},placeholder:"Add an alias..."}),s.jsx("button",{type:"button",onClick:L,style:Pt.addAliasBtn,children:"Add"})]}),d.length>0&&s.jsx("div",{style:Pt.aliasTagsContainer,children:d.map(I=>s.jsxs("span",{style:Pt.aliasTagEditable,children:[I,s.jsx("button",{type:"button",onClick:()=>W(I),style:Pt.removeAliasBtn,children:"x"})]},I))})]}),s.jsxs("label",{style:Pt.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:I=>g(I.target.checked),style:Pt.checkbox}),s.jsx("span",{children:"Don't Forward to Dext"}),s.jsx("span",{style:Pt.checkboxHint,children:"Invoices from this supplier won't be sent to Dext"})]}),s.jsxs("div",{style:Pt.poFieldsSection,children:[s.jsx("h4",{style:Pt.poFieldsTitle,children:"Purchase Order Details"}),s.jsxs("label",{style:Pt.label,children:["Order Email",s.jsx("input",{type:"email",value:m,onChange:I=>y(I.target.value),style:Pt.input,placeholder:"orders@supplier.com"})]}),s.jsxs("label",{style:Pt.label,children:["Account Number",s.jsx("input",{type:"text",value:v,onChange:I=>x(I.target.value),style:Pt.input,placeholder:"e.g., ACC-12345"})]})]}),s.jsxs("div",{style:Pt.modalActions,children:[s.jsx("button",{onClick:M,style:Pt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:D,style:Pt.saveBtn,disabled:!a.trim()||T.isPending,children:T.isPending?"Saving...":"Save Changes"})]})]})}),w&&s.jsx("div",{style:Pt.modalOverlay,onClick:()=>S(null),children:s.jsxs("div",{style:Pt.modal,onClick:I=>I.stopPropagation(),children:[s.jsx("h3",{children:"Delete Supplier?"}),s.jsx("p",{children:"Are you sure you want to delete this supplier?"}),s.jsx("p",{style:Pt.warningText,children:"Invoices linked to this supplier will have their supplier cleared."}),s.jsxs("div",{style:Pt.modalActions,children:[s.jsx("button",{onClick:()=>S(null),style:Pt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>F.mutate(w),style:Pt.confirmDeleteBtn,disabled:F.isPending,children:F.isPending?"Deleting...":"Delete"})]})]})})]})}const Pt={loading:{padding:"2rem",textAlign:"center",color:"#666"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},title:{color:"#1a1a2e",margin:0},addBtn:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontWeight:"bold",cursor:"pointer"},hint:{color:"#666",marginBottom:"1.5rem",background:"white",padding:"1rem",borderRadius:"8px"},empty:{background:"white",padding:"3rem",borderRadius:"12px",textAlign:"center",color:"#666"},emptyHint:{marginTop:"0.5rem",fontSize:"0.9rem",color:"#999"},list:{display:"flex",flexDirection:"column",gap:"0.75rem"},card:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",background:"white",padding:"1rem 1.5rem",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.05)"},cardMain:{display:"flex",flexDirection:"column",gap:"0.25rem",flex:1},supplierName:{fontWeight:"bold",fontSize:"1.1rem",color:"#1a1a2e"},aliasesList:{fontSize:"0.85rem",color:"#666",marginTop:"0.25rem"},aliasesLabel:{color:"#999"},aliasTag:{color:"#1a1a2e"},date:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},cardActions:{display:"flex",gap:"0.5rem",marginLeft:"1rem"},editBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},deleteBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #dc3545",color:"#dc3545",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"500px",width:"90%"},label:{display:"flex",flexDirection:"column",gap:"0.5rem",color:"#333",fontWeight:"500",marginTop:"1rem"},input:{padding:"0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"1rem"},aliasInputRow:{display:"flex",gap:"0.5rem"},addAliasBtn:{padding:"0.75rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},aliasTagsContainer:{display:"flex",flexWrap:"wrap",gap:"0.5rem",marginTop:"0.5rem"},aliasTagEditable:{display:"inline-flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",background:"#e9ecef",borderRadius:"4px",fontSize:"0.85rem"},removeAliasBtn:{background:"none",border:"none",color:"#999",cursor:"pointer",padding:"0 0.25rem",fontSize:"0.9rem",lineHeight:1},modalActions:{display:"flex",gap:"1rem",marginTop:"1.5rem"},cancelBtn:{flex:1,padding:"0.75rem",background:"#f0f0f0",border:"none",borderRadius:"6px",cursor:"pointer"},saveBtn:{flex:1,padding:"0.75rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},confirmDeleteBtn:{flex:1,padding:"0.75rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},warningText:{color:"#856404",background:"#fff3cd",padding:"0.75rem",borderRadius:"6px",fontSize:"0.9rem",marginTop:"0.5rem"},checkboxLabel:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0.5rem",marginTop:"1.25rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",cursor:"pointer"},checkbox:{width:"18px",height:"18px",cursor:"pointer"},checkboxHint:{width:"100%",fontSize:"0.8rem",color:"#666",marginLeft:"26px"},skipDextBadge:{display:"inline-block",fontSize:"0.7rem",padding:"0.2rem 0.5rem",background:"#28a745",color:"white",borderRadius:"4px",marginLeft:"0.5rem",fontWeight:"normal"},poDetails:{display:"flex",gap:"1.5rem",fontSize:"0.8rem",color:"#666",marginTop:"0.25rem"},poFieldsSection:{marginTop:"1.25rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},poFieldsTitle:{margin:"0 0 0.75rem 0",fontSize:"0.9rem",color:"#555",fontWeight:600}};function EJ(){const{user:n,token:e,logout:t,restrictedPages:r}=gn(),i=pi(),[o,a]=k.useState("account"),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState(null),[g,m]=k.useState(!1),[y,v]=k.useState(!1),[x,w]=k.useState(!1),[S,_]=k.useState(90),[b,C]=k.useState(""),[T,F]=k.useState("587"),[A,D]=k.useState(""),[P,L]=k.useState(""),[W,O]=k.useState(!0),[U,M]=k.useState(""),[I,H]=k.useState("Kitchen Invoice System"),[z,G]=k.useState(""),[te,re]=k.useState(null),[me,J]=k.useState(null),[ne,ye]=k.useState(""),[ke,Ye]=k.useState(!0),[De,qe]=k.useState(!0),[ue,Ze]=k.useState(!1),[ee,Z]=k.useState(!0),[ge,Te]=k.useState(!0),[Be,he]=k.useState(null),[He,Ge]=k.useState("£"),[ae,K]=k.useState("DD/MM/YYYY"),[de,Y]=k.useState(100),[Q,X]=k.useState(!0),[pe,we]=k.useState(!0),[Ne,st]=k.useState(null),[Ve,Re]=k.useState(""),[Le,rt]=k.useState(""),[$e,ce]=k.useState(""),[Je,jt]=k.useState(null),[ct,Se]=k.useState(null),[ot,ut]=k.useState(""),[Ot,An]=k.useState(""),[on,Ke]=k.useState(""),[Rt,vt]=k.useState("au"),[Cr,Qt]=k.useState(""),[Ci,Lr]=k.useState(""),[Gs,Ai]=k.useState(""),[Ks,un]=k.useState("10"),[Fr,zi]=k.useState("10"),[aa,Oi]=k.useState(null),[Vd,Gn]=k.useState(null),[Dr,xr]=k.useState(!1),[Ss,rs]=k.useState(!1),[Xs,Jt]=k.useState(!1),Ys=new Date;Ys.setDate(Ys.getDate()-1);const Ft=Ys.toISOString().split("T")[0],[Ea,zn]=k.useState(Ft),[gi,je]=k.useState(Ft),[bt,yn]=k.useState(""),[tn,ci]=k.useState(8),[hn,Ti]=k.useState(""),[js,Ar]=k.useState(""),[fs,Qs]=k.useState(null),[Lo,xn]=k.useState(null),[Pa,nn]=k.useState([]),[Zl,qu]=k.useState([]),[$s,Gd]=k.useState({}),[mo,Bc]=k.useState([]),[Kd,Zs]=k.useState(null),[Ra,Xd]=k.useState(!1),[No,Js]=k.useState([]),[Ba,Ic]=k.useState(!1),[al,ie]=k.useState(Ft),[nt,$]=k.useState(Ft),[ze,Qe]=k.useState(""),[pt,kt]=k.useState("1433"),[Ht,Gt]=k.useState(""),[Er,ar]=k.useState(""),[Kn,is]=k.useState(""),[On,sn]=k.useState(null),[ps,It]=k.useState(null),[Tn,Dt]=k.useState([]),[Ln,Fi]=k.useState(new Set),[Zr,ll]=k.useState(new Set),[Wo,Mc]=k.useState(new Set),[H0,Ia]=k.useState(null),[q0,A1]=k.useState(""),[V0,_e]=k.useState(""),[T1,G0]=k.useState(""),[Mf,Yt]=k.useState(""),[zc,Vu]=k.useState(5),[Li,ks]=k.useState([{name:"Starters",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20},{name:"Mains",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20},{name:"Desserts",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20}]),[ui,la]=k.useState(30),[F1,D1]=k.useState(60),[E1,P1]=k.useState(null),[Oc,Lc]=k.useState(null),[fC,Yd]=k.useState(""),[Ni,K0]=k.useState(""),[Gu,pC]=k.useState(""),[Jl,gC]=k.useState(""),[mC,yC]=k.useState(""),[X0,Y0]=k.useState(""),[xC,bC]=k.useState(""),[R1,B1]=k.useState(null),[I1,vC]=k.useState(""),[M1,z1]=k.useState(""),[wC,SC]=k.useState("65.00"),[jC,O1]=k.useState(4),[Q0,L1]=k.useState(null),[N1,W1]=k.useState(null),[kC,U1]=k.useState(""),[_C,CC]=k.useState(""),[$0,pD]=k.useState(""),[ed,AC]=k.useState("/Kitchen Invoices"),[H1,TC]=k.useState(!1),[Z0,J0]=k.useState(!1),[ex,q1]=k.useState(null),[V1,G1]=k.useState(null),[K1,X1]=k.useState(null),[Y1,Q1]=k.useState("manual"),[Ku,FC]=k.useState(7),[dl,DC]=k.useState("local"),[tx,qn]=k.useState("03:00"),[Qd,Nc]=k.useState("/Backups"),[Xu,$1]=k.useState(""),[Yu,Z1]=k.useState(""),[J1,ew]=k.useState(""),[nx,EC]=k.useState(""),[tw,B]=k.useState("/backups"),[oe,be]=k.useState(null),[Ae,it]=k.useState(null),[en,rn]=k.useState(30),[Nn,Qn]=k.useState(10),[gr,br]=k.useState(20),[mr,Wi]=k.useState(null),[er,lr]=k.useState(""),[Kt,Fn]=k.useState("993"),[Jr,ei]=k.useState(!0),[Ui,Uo]=k.useState(""),[da,zf]=k.useState(""),[nw,rw]=k.useState("INBOX"),[iw,sw]=k.useState(15),[ow,aw]=k.useState(!1),[rx,vr]=k.useState(50),[Gr,Ho]=k.useState(null),[Qu,Of]=k.useState(null),[lw,$u]=k.useState(null),[dw,Xg]=k.useState(null),[cw,uw]=k.useState(""),[Yg,ix]=k.useState("contains"),[Lf,hw]=k.useState(""),[PC,Zu]=k.useState("contains"),[Qg,fw]=k.useState(!1),[gD,Nf]=k.useState(null),[pw,X3]=k.useState(""),[Y3,Q3]=k.useState(""),[$3,Z3]=k.useState(""),[HK,mD]=k.useState(null),[RC,yD]=k.useState(""),[J3,xD]=k.useState(""),[e8,bD]=k.useState(""),[vD,Hi]=k.useState(null),[BC,t8]=k.useState(!1),[sx,wD]=k.useState(""),[qK,SD]=k.useState(null),[jD,gw]=k.useState(""),[VK,kD]=k.useState(null),[n8,r8]=k.useState(""),[i8,s8]=k.useState(0),[_D,CD]=k.useState(""),[o8,IC]=k.useState(0),[GK,AD]=k.useState(!1),[TD,yo]=k.useState(null),[FD,MC]=k.useState(null),[DD,zC]=k.useState(null),[a8,ED]=k.useState(!1),[$d,PD]=k.useState(null),[OC,l8]=k.useState(!1),[RD,Wf]=k.useState(null),[mw,d8]=k.useState(!1),[LC,c8]=k.useState(""),[BD,ID]=k.useState("claude-haiku-4-5-20251001"),[MD,u8]=k.useState(.8),[$g,h8]=k.useState(5e5),[f8,p8]=k.useState({label_parsing:!0,invoice_assist:!0,ingredient_match:!0,recipe_scanning:!0,line_item_reconciliation:!0,menu_description:!0,dispute_email:!0,duplicate_detection:!0,supplier_alias:!0,yield_estimation:!0}),[zD,OD]=k.useState(null),[LD,NC]=k.useState(null),{data:Lt,isLoading:KK}=Oe({queryKey:["settings"],queryFn:async()=>{const j=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch settings");return j.json()}}),{data:tr,error:g8,isLoading:XK}=Oe({queryKey:["newbook-settings"],queryFn:async()=>{const j=await fetch("/api/newbook/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const Pe=await j.text();throw console.error("Newbook settings fetch failed:",j.status,Pe),new Error(`Failed to fetch: ${j.status}`)}const V=await j.json();return console.log("[Newbook] GET settings response:",{upcoming_sync_enabled:V.newbook_upcoming_sync_enabled}),V},staleTime:0}),{data:Dn,error:YK,isLoading:QK}=Oe({queryKey:["resos-settings"],queryFn:async()=>{const j=await fetch("/api/resos/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const Pe=await j.text();throw console.error("Resos settings fetch failed:",j.status,Pe),new Error(`Failed to fetch: ${j.status}`)}return await j.json()},staleTime:0}),{data:Zd,refetch:ND}=Oe({queryKey:["gl-accounts"],queryFn:async()=>{const j=await fetch("/api/newbook/gl-accounts",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]}}),{data:cl,refetch:m8}=Oe({queryKey:["room-categories"],queryFn:async()=>{const j=await fetch("/api/newbook/room-categories",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]}}),{data:WD}=Oe({queryKey:["users"],queryFn:async()=>{const j=await fetch("/auth/users",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){if(j.status===403)return[];throw new Error("Failed to fetch users")}return j.json()},enabled:!!(n!=null&&n.is_admin)}),{data:$n}=Oe({queryKey:["sambapos-settings"],queryFn:async()=>{const j=await fetch("/api/sambapos/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch SambaPOS settings");return j.json()},enabled:!!e}),{data:Zg,refetch:y8,isLoading:$K,error:x8}=Oe({queryKey:["sambapos-categories"],queryFn:async()=>{const j=await fetch("/api/sambapos/categories",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch categories")}return j.json()},enabled:!!e&&!!($n!=null&&$n.sambapos_db_host)&&!!($n!=null&&$n.sambapos_db_password_set),retry:!1}),{data:UD,refetch:ZK,isLoading:JK}=Oe({queryKey:["sambapos-group-codes"],queryFn:async()=>{const j=await fetch("/api/sambapos/group-codes",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch group codes")}return j.json()},enabled:!!e&&!!($n!=null&&$n.sambapos_db_host)&&!!($n!=null&&$n.sambapos_db_password_set),retry:!1}),{data:WC,refetch:eX,isLoading:tX}=Oe({queryKey:["sambapos-gl-codes"],queryFn:async()=>{const j=await fetch("/api/sambapos/gl-codes",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch GL codes")}return j.json()},enabled:!!e&&!!($n!=null&&$n.sambapos_db_host)&&!!($n!=null&&$n.sambapos_db_password_set),retry:!1}),{data:UC}=Oe({queryKey:["sambapos-selected-gl-codes"],queryFn:async()=>{const j=await fetch("/api/sambapos/gl-codes/selected",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch selected GL codes");return j.json()},enabled:!!e}),{data:td}=Oe({queryKey:["kds-settings"],queryFn:async()=>{const j=await fetch("/api/kds/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch KDS settings");return j.json()},enabled:!!e}),{data:Ju}=Oe({queryKey:["kitchen-details"],queryFn:async()=>{const j=await fetch("/api/settings/kitchen-details",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch kitchen details");return j.json()},enabled:!!e}),{data:Jd}=Oe({queryKey:["budget-settings"],queryFn:async()=>{const j=await fetch("/api/budget/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch Budget settings");return j.json()},enabled:!!e}),{data:yw}=Oe({queryKey:["page-restrictions"],queryFn:async()=>{const j=await fetch("/api/settings/page-restrictions",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch page restrictions");return j.json()},enabled:!!e}),{data:ul}=Oe({queryKey:["nextcloud-settings"],queryFn:async()=>{const j=await fetch("/api/settings/nextcloud",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch Nextcloud settings");return j.json()},enabled:!!e}),{data:qo}=Oe({queryKey:["nextcloud-stats"],queryFn:async()=>{const j=await fetch("/api/settings/nextcloud/stats",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch Nextcloud stats");return j.json()},enabled:!!e}),{data:Nr}=Oe({queryKey:["backup-settings"],queryFn:async()=>{const j=await fetch("/api/backup/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch backup settings");return j.json()},enabled:!!e}),{data:HD}=Oe({queryKey:["backup-history"],queryFn:async()=>{const j=await fetch("/api/backup/history",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch backup history");return j.json()},enabled:!!e}),{data:xw}=Oe({queryKey:["search-settings"],queryFn:async()=>{const j=await fetch("/api/search/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch search settings");return j.json()},enabled:!!e}),{data:qi}=Oe({queryKey:["imap-settings"],queryFn:async()=>{const j=await fetch("/api/imap/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch IMAP settings");return j.json()},enabled:!!e&&!!(n!=null&&n.is_admin)}),{data:qD}=Oe({queryKey:["imap-logs"],queryFn:async()=>{const j=await fetch("/api/imap/logs?limit=20",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch IMAP logs");return j.json()},enabled:!!e&&!!(n!=null&&n.is_admin)&&o==="inbox"}),{data:Wc}=Oe({queryKey:["imap-stats"],queryFn:async()=>{const j=await fetch("/api/imap/logs/stats",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch IMAP stats");return j.json()},enabled:!!e&&!!(n!=null&&n.is_admin)&&o==="inbox"}),[eh,bw]=k.useState(new Set),[VD,GD]=k.useState(null);k.useEffect(()=>{yw!=null&&yw.restricted_pages&&bw(new Set(yw.restricted_pages))},[yw]),k.useEffect(()=>{Lt&&(d(Lt.azure_endpoint||""),Ge(Lt.currency_symbol),K(Lt.date_format),Y(Lt.high_quantity_threshold),C(Lt.smtp_host||""),F(String(Lt.smtp_port||587)),D(Lt.smtp_username||""),O(Lt.smtp_use_tls),M(Lt.smtp_from_email||""),H(Lt.smtp_from_name||"Kitchen Invoice System"),G(Lt.support_email||""),ye(Lt.dext_email||""),Ye(Lt.dext_include_notes),qe(Lt.dext_include_non_stock),Ze(Lt.dext_auto_send_enabled),Z(Lt.dext_manual_send_enabled),Te(Lt.dext_include_annotations),X(Lt.pdf_annotations_enabled),we(Lt.pdf_preview_show_annotations),m(Lt.ocr_clean_product_codes||!1),v(Lt.ocr_filter_subtotal_rows||!1),w(Lt.ocr_use_weight_as_quantity||!1),_(Lt.cost_distribution_max_days??90),d8(Lt.llm_enabled??!1),ID(Lt.llm_model||"claude-haiku-4-5-20251001"),u8(Lt.llm_confidence_threshold??.8),h8(Lt.llm_monthly_token_limit??5e5),Lt.llm_features_enabled&&p8(Lt.llm_features_enabled))},[Lt]),k.useEffect(()=>{ul&&(U1(ul.nextcloud_host||""),CC(ul.nextcloud_username||""),AC(ul.nextcloud_base_path||"/Kitchen Invoices"),TC(ul.nextcloud_enabled),J0(ul.nextcloud_delete_local))},[ul]),k.useEffect(()=>{Nr&&(Q1(Nr.backup_frequency||"manual"),FC(Nr.backup_retention_count||7),DC(Nr.backup_destination||"local"),qn(Nr.backup_time||"03:00"),Nc(Nr.backup_nextcloud_path||"/Backups"),$1(Nr.backup_smb_host||""),Z1(Nr.backup_smb_share||""),ew(Nr.backup_smb_username||""),B(Nr.backup_smb_path||"/backups"))},[Nr]),k.useEffect(()=>{xw&&(rn(xw.price_change_lookback_days||30),Qn(xw.price_change_amber_threshold||10),br(xw.price_change_red_threshold||20))},[xw]),k.useEffect(()=>{qi&&(lr(qi.imap_host||""),Fn(String(qi.imap_port||993)),ei(qi.imap_use_ssl),Uo(qi.imap_username||""),rw(qi.imap_folder||"INBOX"),sw(qi.imap_poll_interval||15),aw(qi.imap_enabled),vr((qi.imap_confidence_threshold||.5)*100))},[qi]),k.useEffect(()=>{tr&&(ut(tr.newbook_api_username||""),vt(tr.newbook_api_region||"au"),Qt(tr.newbook_instance_id||""),Lr(tr.newbook_breakfast_gl_codes||""),Ai(tr.newbook_dinner_gl_codes||""),un(tr.newbook_breakfast_vat_rate?String(parseFloat(tr.newbook_breakfast_vat_rate)*100):"10"),zi(tr.newbook_dinner_vat_rate?String(parseFloat(tr.newbook_dinner_vat_rate)*100):"10"))},[tr]),k.useEffect(()=>{$n&&(Qe($n.sambapos_db_host||""),kt(String($n.sambapos_db_port||1433)),Gt($n.sambapos_db_name||""),ar($n.sambapos_db_username||""),Dt($n.sambapos_tracked_categories||[]),Fi(new Set($n.sambapos_excluded_items||[])))},[$n]),k.useEffect(()=>{UC&&(ll(new Set(UC.food_codes||[])),Mc(new Set(UC.beverage_codes||[])))},[UC]),k.useEffect(()=>{if(td){A1(td.kds_graphql_url||""),_e(td.kds_graphql_username||""),Yt(td.kds_graphql_client_id||""),Vu(td.kds_poll_interval_seconds||6e3);const j=(td.kds_course_order||[]).map(V=>({name:V.name,prep_green:V.prep_green/60,prep_amber:V.prep_amber/60,prep_red:V.prep_red/60,away_green:V.away_green/60,away_amber:V.away_amber/60,away_red:V.away_red/60}));j.length>0&&ks(j),la(td.kds_show_completed_for_seconds||30),D1(td.kds_bookings_refresh_seconds||60)}},[td]),k.useEffect(()=>{Ju&&(Yd(Ju.kitchen_display_name||""),K0(Ju.kitchen_address_line1||""),pC(Ju.kitchen_address_line2||""),gC(Ju.kitchen_city||""),yC(Ju.kitchen_postcode||""),Y0(Ju.kitchen_phone||""),bC(Ju.kitchen_email||""))},[Ju]),k.useEffect(()=>{Jd&&(vC(Jd.forecast_api_url||""),SC(String(Jd.budget_gp_target||65)),O1(Jd.budget_lookback_weeks||4))},[Jd]),k.useEffect(()=>{if(Dn){ci(Dn.resos_large_group_threshold||8),Ti(Dn.resos_note_keywords||""),Ar(Dn.resos_allergy_keywords||""),Gd(Dn.resos_custom_field_mapping||{}),Zs(Dn.resos_arrival_widget_service_filter||null),Xd(Dn.resos_enable_manual_breakfast||!1),Js(Dn.resos_manual_breakfast_periods||[]);const j=(Dn.resos_opening_hours_mapping||[]).map(V=>({resos_id:V.resos_id,display_name:V.display_name,actual_end:V.actual_end,service_type:V.service_type||""}));Bc(j),Dn.resos_custom_field_mapping&&Object.keys(Dn.resos_custom_field_mapping).length>0&&Pa.length===0&&fetch("/api/resos/custom-fields",{headers:{Authorization:`Bearer ${e}`}}).then(V=>V.json()).then(V=>nn(V.custom_fields||[])).catch(V=>console.error("Failed to auto-fetch custom fields:",V)),Dn.resos_opening_hours_mapping&&Dn.resos_opening_hours_mapping.length>0&&Zl.length===0&&fetch("/api/resos/opening-hours",{headers:{Authorization:`Bearer ${e}`}}).then(V=>V.json()).then(V=>qu(V.opening_hours||[])).catch(V=>console.error("Failed to auto-fetch opening hours:",V))}},[Dn]);const{data:b8,refetch:ox}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const j=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]}}),{data:HC}=Oe({queryKey:["api-access-settings"],queryFn:async()=>{const j=await fetch("/api/settings/api-access",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():{api_key:null,api_key_enabled:!1}}});k.useEffect(()=>{HC&&(ED(HC.api_key_enabled),PD(HC.api_key))},[HC]);const KD=Ue({mutationFn:async j=>{const V=await fetch("/api/food-flags/categories",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to create category");return V.json()},onSuccess:()=>{ox(),hw(""),Zu("contains"),fw(!1),Hi("Category created"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error creating category")}),XD=Ue({mutationFn:async({id:j,data:V})=>{const Pe=await fetch(`/api/food-flags/categories/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Pe.ok)throw new Error("Failed to update category");return Pe.json()},onSuccess:()=>{ox(),Xg(null),Hi("Category updated"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error updating category")}),nX=Ue({mutationFn:async j=>{const V=await fetch(`/api/food-flags/categories/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok)throw new Error("Failed to delete category");return V.json()},onSuccess:()=>{ox(),Hi("Category deleted"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error deleting category")}),v8=Ue({mutationFn:async j=>{const V=await fetch("/api/food-flags/flags",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to create flag");return V.json()},onSuccess:()=>{ox(),mD(null),yD(""),xD(""),bD(""),Hi("Flag created"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error creating flag")}),w8=Ue({mutationFn:async({id:j,data:V})=>{const Pe=await fetch(`/api/food-flags/flags/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Pe.ok)throw new Error("Failed to update flag");return Pe.json()},onSuccess:()=>{ox(),Nf(null),Hi("Flag updated"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error updating flag")}),rX=Ue({mutationFn:async j=>{const V=await fetch(`/api/food-flags/flags/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok)throw new Error("Failed to delete flag");return V.json()},onSuccess:()=>{ox(),Hi("Flag deleted"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error deleting flag")}),{data:YD,refetch:QD}=Oe({queryKey:["allergen-keywords"],queryFn:async()=>{const j=await fetch("/api/food-flags/keywords",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="allergen_keywords"}),$D=Ue({mutationFn:async({food_flag_id:j,keyword:V})=>{const Pe=await fetch("/api/food-flags/keywords",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_id:j,keyword:V})});if(!Pe.ok){const St=await Pe.json().catch(()=>({}));throw new Error(St.detail||"Failed to add keyword")}return Pe.json()},onSuccess:()=>{QD(),wD(""),SD(null),gw("Keyword added"),setTimeout(()=>gw(""),2e3)},onError:j=>{gw(`Error: ${j.message}`)}}),iX=Ue({mutationFn:async j=>{if(!(await fetch(`/api/food-flags/keywords/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})).ok)throw new Error("Failed to delete keyword")},onSuccess:()=>{QD()}}),ZD=Ue({mutationFn:async()=>{if(!(await fetch("/api/food-flags/keywords/reset-defaults",{method:"POST",headers:{Authorization:`Bearer ${e}`}})).ok)throw new Error("Failed to reset keywords")},onSuccess:()=>{QD(),gw("Default keywords restored (custom keywords preserved)"),setTimeout(()=>gw(""),3e3)}}),{data:Ps,refetch:qC}=Oe({queryKey:["ingredient-categories-settings"],queryFn:async()=>{const j=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="ingredient_categories"}),JD=Ue({mutationFn:async j=>{const V=await fetch("/api/ingredients/categories",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json().catch(()=>null);throw new Error((Pe==null?void 0:Pe.detail)||"Failed to create category")}return V.json()},onSuccess:()=>{qC(),CD(""),IC((Ps==null?void 0:Ps.length)||0),AD(!1),yo("Category created"),setTimeout(()=>yo(null),3e3)},onError:j=>{yo(`Error: ${j.message}`),setTimeout(()=>yo(null),5e3)}}),VC=Ue({mutationFn:async({id:j,data:V})=>{const Pe=await fetch(`/api/ingredients/categories/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Pe.ok){const St=await Pe.json().catch(()=>null);throw new Error((St==null?void 0:St.detail)||"Failed to update category")}return Pe.json()},onSuccess:()=>{qC(),kD(null),yo("Category updated"),setTimeout(()=>yo(null),3e3)},onError:j=>{yo(`Error: ${j.message}`),setTimeout(()=>yo(null),5e3)}}),sX=Ue({mutationFn:async j=>{const V=await fetch(`/api/ingredients/categories/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok)throw new Error("Failed to delete category");return V.json()},onSuccess:()=>{qC(),yo("Category deleted"),setTimeout(()=>yo(null),3e3)},onError:()=>{yo("Error deleting category"),setTimeout(()=>yo(null),5e3)}}),S8=(j,V)=>{if(!Ps)return;const Pe=Ps.findIndex(xo=>xo.id===j);if(Pe<0)return;const St=V==="up"?Pe-1:Pe+1;if(St<0||St>=Ps.length)return;const yr=Ps[Pe].sort_order,dr=Ps[St].sort_order;VC.mutate({id:Ps[Pe].id,data:{sort_order:dr}}),VC.mutate({id:Ps[St].id,data:{sort_order:yr}})},{data:th,refetch:GC}=Oe({queryKey:["recipe-sections-settings"],queryFn:async()=>{const j=await fetch("/api/recipes/menu-sections?section_type=recipe",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="recipe_sections"}),{data:nh,refetch:KC}=Oe({queryKey:["dish-courses-settings"],queryFn:async()=>{const j=await fetch("/api/recipes/menu-sections?section_type=dish",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="dish_courses"}),oX=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/api-access",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save API access settings");return V.json()},onSuccess:j=>{j.api_key&&PD(j.api_key),ED(j.api_key_enabled),Wf("Settings saved"),setTimeout(()=>Wf(null),3e3)},onError:()=>Wf("Error saving settings")}),XC=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/api-access/regenerate",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to regenerate API key");return j.json()},onSuccess:j=>{PD(j.api_key),l8(!0),Wf("API key regenerated. Copy it now - it will be masked next time you visit."),setTimeout(()=>Wf(null),8e3)},onError:()=>Wf("Error regenerating API key")}),{data:ec,refetch:aX}=Oe({queryKey:["llm-usage"],queryFn:async()=>{const j=await fetch("/api/settings/llm-usage",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():{total_calls:0,successful_calls:0,failed_calls:0,total_input_tokens:0,total_output_tokens:0,total_tokens:0,estimated_cost_usd:0,cache_entries_this_month:0}},enabled:!!(Lt!=null&&Lt.llm_enabled)}),{data:Uf,isLoading:lX,refetch:dX,isFetching:j8}=Oe({queryKey:["llm-models"],queryFn:async()=>{const j=await fetch("/api/settings/llm-models",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():{models:[],default:"claude-haiku-4-5-20251001",current:"claude-haiku-4-5-20251001"}},enabled:!!(Lt!=null&&Lt.llm_enabled)&&!!(Lt!=null&&Lt.anthropic_api_key_set),staleTime:3e5}),eE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save LLM settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["settings"]}),c8(""),OD("AI settings saved successfully"),setTimeout(()=>OD(null),3e3)},onError:j=>OD(`Error: ${j.message}`)}),tE=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/test-llm",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{NC(j.message||"Connection successful"),setTimeout(()=>NC(null),5e3)},onError:j=>{NC(`Error: ${j.message}`),setTimeout(()=>NC(null),8e3)}}),cX=()=>{const j={llm_enabled:mw,llm_model:BD,llm_confidence_threshold:MD,llm_monthly_token_limit:$g,llm_features_enabled:f8};LC&&(j.anthropic_api_key=LC),eE.mutate(j)},Jg=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to update settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["settings"]}),st("Settings saved successfully"),u(""),setTimeout(()=>st(null),3e3)},onError:j=>{st(`Error: ${j.message}`)}}),uX=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/test-azure",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{p(j.message),setTimeout(()=>p(null),5e3)},onError:j=>{p(`Error: ${j.message}`)}}),nE=Ue({mutationFn:async j=>{const V=await fetch("/auth/change-password",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to change password")}return V.json()},onSuccess:()=>{jt("Password changed successfully"),Re(""),rt(""),ce(""),setTimeout(()=>jt(null),5e3)},onError:j=>{jt(`Error: ${j.message}`)}}),hX=Ue({mutationFn:async j=>{const V=await fetch(`/auth/users/${j}/toggle-active`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to toggle user")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["users"]})}}),fX=Ue({mutationFn:async j=>{const V=await fetch(`/auth/users/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to delete user")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["users"]})}}),pX=Ue({mutationFn:async j=>{const V=await fetch(`/auth/users/${j}/toggle-admin`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to toggle admin status")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["users"]})}}),rE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/page-restrictions",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({restricted_pages:j})});if(!V.ok)throw new Error("Failed to save page restrictions");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["page-restrictions"]}),GD("Page restrictions saved successfully"),setTimeout(()=>GD(null),3e3)},onError:j=>{GD(`Error: ${j.message}`)}}),iE=Ue({mutationFn:async()=>{const j=await fetch("/api/invoices/reprocess-all",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to reprocess invoices")}return j.json()},onSuccess:j=>{Se(j.message),i.invalidateQueries({queryKey:["invoices"]}),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),sE=Ue({mutationFn:async()=>{const j=await fetch("/api/recipes/cleanup-false-price-changes",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to cleanup")}return j.json()},onSuccess:j=>{Se(j.message),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),oE=Ue({mutationFn:async()=>{const j=await fetch("/api/recipes/backfill-invoice-references",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to backfill")}return j.json()},onSuccess:j=>{Se(j.message),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),aE=Ue({mutationFn:async()=>{const j=await fetch("/api/suppliers/rematch-fuzzy",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to rematch invoices")}return j.json()},onSuccess:j=>{Se(j.message),i.invalidateQueries({queryKey:["invoices"]}),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),rh=Ue({mutationFn:async j=>{console.log("[Newbook] Sending PATCH with data:",j);const V=await fetch("/api/newbook/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const St=await V.text();throw console.error("[Newbook] PATCH failed:",V.status,St),new Error("Failed to update Newbook settings")}const Pe=await V.json();return console.log("[Newbook] PATCH response:",Pe),Pe},onSuccess:j=>{console.log("[Newbook] Mutation success, response data:",j),i.invalidateQueries({queryKey:["newbook-settings"]}),Gn("Newbook settings saved"),An(""),Ke(""),setTimeout(()=>Gn(null),3e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),k8=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/test-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{Oi(j.message),setTimeout(()=>Oi(null),5e3)},onError:j=>{Oi(`Error: ${j.message}`)}}),lE=Ue({mutationFn:async j=>{console.log("[Resos] Sending PATCH with data:",j);const V=await fetch("/api/resos/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const St=await V.text();throw console.error("[Resos] PATCH failed:",V.status,St),new Error("Failed to update Resos settings")}const Pe=await V.json();return console.log("[Resos] PATCH response:",Pe),Pe},onSuccess:()=>{i.invalidateQueries({queryKey:["resos-settings"]}),xn("✓ Sync settings saved"),setTimeout(()=>xn(null),3e3)},onError:j=>{xn(`✗ Error: ${j.message}`),setTimeout(()=>xn(null),5e3)}}),dE=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/gl-accounts/fetch",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch GL accounts")}return j.json()},onSuccess:()=>{ND(),Gn("GL accounts fetched successfully"),setTimeout(()=>Gn(null),3e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),cE=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/sync/forecast",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Sync failed")}return j.json()},onSuccess:j=>{Gn(`Forecast sync complete: ${JSON.stringify(j.results)}`),i.invalidateQueries({queryKey:["newbook-settings"]}),setTimeout(()=>Gn(null),5e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),uE=Ue({mutationFn:async j=>{const V=await fetch("/api/newbook/sync/historical",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Sync failed")}return V.json()},onSuccess:j=>{Gn(`Historical sync complete: ${JSON.stringify(j.results)}`),Jt(!1),i.invalidateQueries({queryKey:["newbook-settings"]}),setTimeout(()=>Gn(null),5e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),gX=Ue({mutationFn:async({id:j,is_tracked:V})=>{const Pe=await fetch(`/api/newbook/gl-accounts/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({is_tracked:V})});if(!Pe.ok)throw new Error("Failed to update GL account");return Pe.json()},onSuccess:()=>{ND()}}),mX=Ue({mutationFn:async j=>{const V=await fetch("/api/newbook/gl-accounts/bulk-update",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({updates:j})});if(!V.ok)throw new Error("Failed to update GL accounts");return V.json()},onSuccess:()=>{ND()}}),hE=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/room-categories/fetch",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch room categories")}return j.json()},onSuccess:()=>{m8(),Gn("Room categories fetched successfully"),setTimeout(()=>Gn(null),3e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),fE=Ue({mutationFn:async j=>{const V=await fetch("/api/newbook/room-categories/bulk-update",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({updates:j})});if(!V.ok)throw new Error("Failed to update room categories");return V.json()},onSuccess:()=>{m8()}}),pE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save SambaPOS settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-settings"]}),It("Settings saved successfully"),is(""),setTimeout(()=>It(null),3e3)},onError:j=>{It(`Error: ${j.message}`)}}),gE=Ue({mutationFn:async()=>{const j=await fetch("/api/sambapos/test-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{sn(j.message),y8(),setTimeout(()=>sn(null),5e3)},onError:j=>{sn(`Error: ${j.message}`)}}),mE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/tracked-categories",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({categories:j})});if(!V.ok)throw new Error("Failed to save courses");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-settings"]}),It("Courses saved successfully"),setTimeout(()=>It(null),3e3)},onError:j=>{It(`Error: ${j.message}`)}}),yE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/excluded-items",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({items:j})});if(!V.ok)throw new Error("Failed to save excluded categories");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-settings"]}),It("Excluded categories saved successfully"),setTimeout(()=>It(null),3e3)},onError:j=>{It(`Error: ${j.message}`)}}),xE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/gl-codes",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save GL codes");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-selected-gl-codes"]}),Ia("GL codes saved successfully"),setTimeout(()=>Ia(null),3e3)},onError:j=>{Ia(`Error: ${j.message}`)}}),ax=Ue({mutationFn:async j=>{const V=await fetch("/api/kds/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save KDS settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["kds-settings"]}),Lc("Settings saved successfully"),G0(""),setTimeout(()=>Lc(null),3e3)},onError:j=>{Lc(`Error: ${j.message}`)}}),bE=Ue({mutationFn:async()=>{const V=await(await fetch("/api/kds/test-connection",{headers:{Authorization:`Bearer ${e}`}})).json();if(!V.success)throw new Error(V.error||"Connection test failed");return V},onSuccess:j=>{P1(j.message),setTimeout(()=>P1(null),5e3)},onError:j=>{P1(`Error: ${j.message}`)}}),vE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/kitchen-details",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save kitchen details")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["kitchen-details"]}),B1("Kitchen details saved successfully"),setTimeout(()=>B1(null),3e3)},onError:j=>{B1(`Error: ${j.message}`)}}),wE=Ue({mutationFn:async j=>{const V=await fetch("/api/budget/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save Budget settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["budget-settings"]}),W1("Budget settings saved successfully"),z1(""),setTimeout(()=>W1(null),3e3)},onError:j=>{W1(`Error: ${j.message}`)}}),SE=Ue({mutationFn:async()=>{const V=await(await fetch("/api/budget/test-forecast-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}})).json();if(!V.success)throw new Error(V.message||"Connection test failed");return V},onSuccess:j=>{L1(j.message),setTimeout(()=>L1(null),5e3)},onError:j=>{L1(`Error: ${j.message}`)}}),jE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/nextcloud",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save Nextcloud settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["nextcloud-settings"]}),i.invalidateQueries({queryKey:["nextcloud-stats"]}),G1("Nextcloud settings saved successfully"),setTimeout(()=>G1(null),3e3)},onError:j=>{G1(`Error: ${j.message}`)}}),kE=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/nextcloud/test",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:()=>{q1("Connection successful"),setTimeout(()=>q1(null),5e3)},onError:j=>{q1(`Error: ${j.message}`)}}),_E=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/nextcloud/archive-all",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Archive failed")}return j.json()},onSuccess:j=>{i.invalidateQueries({queryKey:["nextcloud-stats"]}),X1(`Archived ${j.success_count} invoices${j.failed_count>0?`, ${j.failed_count} failed`:""}`),setTimeout(()=>X1(null),5e3)},onError:j=>{X1(`Error: ${j.message}`)}}),CE=Ue({mutationFn:async j=>{const V=await fetch("/api/backup/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save backup settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["backup-settings"]}),be("Backup settings saved successfully"),setTimeout(()=>be(null),3e3)},onError:j=>{be(`Error: ${j.message}`)}}),AE=Ue({mutationFn:async()=>{const j=await fetch("/api/backup/create",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Backup creation failed")}return j.json()},onSuccess:j=>{i.invalidateQueries({queryKey:["backup-history"]}),i.invalidateQueries({queryKey:["backup-settings"]}),it(j.message),setTimeout(()=>it(null),5e3)},onError:j=>{it(`Error: ${j.message}`)}}),_8=Ue({mutationFn:async j=>{const V=await fetch(`/api/backup/${j}/restore`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Restore failed")}return V.json()},onSuccess:j=>{it(j.message),setTimeout(()=>it(null),5e3),i.invalidateQueries()},onError:j=>{it(`Error: ${j.message}`)}}),C8=Ue({mutationFn:async j=>{const V=await fetch(`/api/backup/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Delete failed")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["backup-history"]}),it("Backup deleted"),setTimeout(()=>it(null),3e3)},onError:j=>{it(`Error: ${j.message}`)}}),YC=Ue({mutationFn:async j=>{const V=new FormData;V.append("file",j);const Pe=await fetch("/api/backup/upload",{method:"POST",headers:{Authorization:`Bearer ${e}`},body:V});if(!Pe.ok){const St=await Pe.json();throw new Error(St.detail||"Upload failed")}return Pe.json()},onSuccess:j=>{i.invalidateQueries({queryKey:["backup-history"]}),it(j.message),setTimeout(()=>it(null),5e3)},onError:j=>{it(`Error: ${j.message}`)}}),TE=Ue({mutationFn:async j=>{const V=await fetch("/api/search/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save search settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["search-settings"]}),Wi("Search settings saved successfully"),setTimeout(()=>Wi(null),3e3)},onError:j=>{Wi(`Error: ${j.message}`)}}),yX=()=>{if(!Ve||!Le||!$e){jt("Error: Please fill in all password fields");return}if(Le!==$e){jt("Error: New passwords do not match");return}if(Le.length<6){jt("Error: Password must be at least 6 characters");return}nE.mutate({current_password:Ve,new_password:Le})},A8=()=>{const j={azure_endpoint:l,currency_symbol:He,date_format:ae,high_quantity_threshold:de,pdf_annotations_enabled:Q,pdf_preview_show_annotations:pe,ocr_clean_product_codes:g,ocr_filter_subtotal_rows:y,ocr_use_weight_as_quantity:x,cost_distribution_max_days:S};c&&(j.azure_key=c),Jg.mutate(j)},xX=()=>{const j={newbook_api_username:ot,newbook_api_region:Rt,newbook_instance_id:Cr};Ot&&(j.newbook_api_password=Ot),on&&(j.newbook_api_key=on),rh.mutate(j)},bX=()=>{const j={sambapos_db_host:ze,sambapos_db_port:parseInt(pt)||1433,sambapos_db_name:Ht,sambapos_db_username:Er};Kn&&(j.sambapos_db_password=Kn),pE.mutate(j)},T8=j=>{Tn.includes(j)?Dt(Tn.filter(V=>V!==j)):Dt([...Tn,j])},vX=j=>{if(j<=0)return;const V=[...Tn];[V[j-1],V[j]]=[V[j],V[j-1]],Dt(V)},wX=j=>{if(j>=Tn.length-1)return;const V=[...Tn];[V[j],V[j+1]]=[V[j+1],V[j]],Dt(V)},SX=()=>{mE.mutate(Tn)},jX=j=>{const V=new Set(Ln);V.has(j)?V.delete(j):V.add(j),Fi(V)},kX=()=>{yE.mutate(Array.from(Ln))},_X=j=>{const V=new Set(Zr);if(V.has(j))V.delete(j);else if(V.add(j),Wo.has(j)){const Pe=new Set(Wo);Pe.delete(j),Mc(Pe)}ll(V)},CX=j=>{const V=new Set(Wo);if(V.has(j))V.delete(j);else if(V.add(j),Zr.has(j)){const Pe=new Set(Zr);Pe.delete(j),ll(Pe)}Mc(V)},AX=()=>{xE.mutate({food_codes:Array.from(Zr),beverage_codes:Array.from(Wo)})},FE=($n==null?void 0:$n.sambapos_db_host)&&($n==null?void 0:$n.sambapos_db_password_set),TX=()=>{const j={kds_graphql_url:q0,kds_graphql_username:V0,kds_graphql_client_id:Mf};T1&&(j.kds_graphql_password=T1),ax.mutate(j)},FX=()=>{const j=Li.map(V=>({name:V.name,prep_green:Math.round(V.prep_green*60),prep_amber:Math.round(V.prep_amber*60),prep_red:Math.round(V.prep_red*60),away_green:Math.round(V.away_green*60),away_amber:Math.round(V.away_amber*60),away_red:Math.round(V.away_red*60)}));ax.mutate({kds_poll_interval_seconds:zc,kds_course_order:j,kds_show_completed_for_seconds:ui,kds_bookings_refresh_seconds:F1})},DX=()=>{vE.mutate({kitchen_display_name:fC||null,kitchen_address_line1:Ni||null,kitchen_address_line2:Gu||null,kitchen_city:Jl||null,kitchen_postcode:mC||null,kitchen_phone:X0||null,kitchen_email:xC||null})},EX=()=>{const j={forecast_api_url:I1||null,budget_gp_target:parseFloat(wC)||65,budget_lookback_weeks:jC};M1&&(j.forecast_api_key=M1),wE.mutate(j)},em=(j,V,Pe)=>{ks(St=>St.map((yr,dr)=>dr===j?{...yr,[V]:Pe}:yr))},F8=(j,V)=>{const Pe=j+V;Pe<0||Pe>=Li.length||ks(St=>{const yr=[...St];return[yr[j],yr[Pe]]=[yr[Pe],yr[j]],yr})},PX=j=>{ks(V=>V.filter((Pe,St)=>St!==j))},RX=()=>{ks(j=>[...j,{name:"",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20}])};if(KK)return s.jsx("div",{style:E.loading,children:"Loading settings..."});const BX=j=>!j||n!=null&&n.is_admin?!0:!r.includes(j),IX=[{id:"account",label:"Account"},{id:"users",label:"Users",adminOnly:!0,restrictPath:"/settings-users"},{id:"access",label:"Access Control",adminOnly:!0,restrictPath:"/settings-access"},{id:"display",label:"Display",restrictPath:"/settings-display"},{id:"azure",label:"Azure OCR",restrictPath:"/settings-azure"},{id:"email",label:"Email Configuration",restrictPath:"/settings-email"},{id:"inbox",label:"Email Inbox",adminOnly:!0,restrictPath:"/settings-inbox"},{id:"dext",label:"Dext Integration",restrictPath:"/settings-dext"},{id:"newbook",label:"Newbook PMS",restrictPath:"/settings-newbook"},{id:"resos",label:"Resos Bookings",restrictPath:"/settings-resos"},{id:"sambapos",label:"SambaPOS EPOS",restrictPath:"/settings-sambapos"},{id:"kds",label:"Kitchen Display",restrictPath:"/settings-kds"},{id:"budget",label:"Spend Budget",restrictPath:"/settings-budget"},{id:"kitchen",label:"Kitchen Details",restrictPath:"/settings-kitchen"},{id:"suppliers",label:"Suppliers",restrictPath:"/settings-suppliers"},{id:"search",label:"Search & Pricing",restrictPath:"/settings-search"},{id:"nextcloud",label:"Nextcloud Storage",restrictPath:"/settings-nextcloud"},{id:"backup",label:"Backup & Restore",restrictPath:"/settings-backup"},{id:"food_flags",label:"Food Flags",restrictPath:"/settings-food-flags"},{id:"allergen_keywords",label:"Allergen Keywords",restrictPath:"/settings-food-flags"},{id:"ingredient_categories",label:"Ingredient Categories",restrictPath:"/settings-ingredient-categories"},{id:"recipe_sections",label:"Recipe Sections",restrictPath:"/settings-recipe-sections"},{id:"dish_courses",label:"Dish Courses",restrictPath:"/settings-dish-courses"},{id:"api_access",label:"API Access",restrictPath:"/settings-api-access"},{id:"llm",label:"AI Features",adminOnly:!0,restrictPath:"/settings-llm"},{id:"data",label:"Data Management",restrictPath:"/settings-data"}];return s.jsxs("div",{style:E.layout,children:[s.jsxs("div",{style:E.sidebar,children:[s.jsx("h3",{style:E.sidebarTitle,children:"Settings"}),s.jsx("nav",{style:E.nav,children:IX.map(j=>j.adminOnly&&!(n!=null&&n.is_admin)||!BX(j.restrictPath)?null:j.href?s.jsx("a",{href:j.href,style:E.navItem,children:j.label},j.id):s.jsx("button",{onClick:()=>a(j.id),style:{...E.navItem,...o===j.id?E.navItemActive:{}},children:j.label},j.id))}),s.jsx("button",{onClick:async()=>{var j;try{const V=await caches.keys();await Promise.all(V.map(St=>caches.delete(St)));const Pe=await((j=navigator.serviceWorker)==null?void 0:j.getRegistrations());Pe&&await Promise.all(Pe.map(St=>St.unregister()))}catch{}window.location.reload()},title:"Clear cached files and reload with fresh assets",style:{marginTop:"1rem",padding:"0.6rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"#f9fafb",cursor:"pointer",fontSize:"0.85rem",color:"#666",textAlign:"left",width:"100%"},children:"↻ Refresh App"})]}),s.jsxs("div",{style:E.content,children:[o==="account"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Account"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Account Information"}),s.jsxs("div",{style:E.infoGrid,children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Email:"})," ",n==null?void 0:n.email]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Name:"})," ",n==null?void 0:n.name]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Kitchen:"})," ",n==null?void 0:n.kitchen_name]}),(n==null?void 0:n.is_admin)&&s.jsxs("p",{children:[s.jsx("strong",{children:"Role:"})," Admin"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Change Password"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Current Password",s.jsx("input",{type:"password",value:Ve,onChange:j=>Re(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["New Password",s.jsx("input",{type:"password",value:Le,onChange:j=>rt(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Confirm New Password",s.jsx("input",{type:"password",value:$e,onChange:j=>ce(j.target.value),style:E.input})]})]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("button",{onClick:yX,style:E.btn,disabled:nE.isPending,children:nE.isPending?"Changing...":"Change Password"}),Je&&s.jsx("div",{style:{...E.statusMessage,background:Je.startsWith("Error")?"#fee":"#efe",marginTop:"0.5rem"},children:Je})]}),s.jsx("div",{children:s.jsx("button",{onClick:()=>{window.confirm("Are you sure you want to logout?")&&(t(),window.location.href="/login")},style:{background:"#e94560",color:"white",border:"none",padding:"0.75rem 1.5rem",borderRadius:"4px",cursor:"pointer",fontSize:"16px",fontWeight:"bold"},children:"Logout"})})]}),o==="users"&&(n==null?void 0:n.is_admin)&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"User Management"}),s.jsx("p",{style:E.hint,children:"Manage users who have access to this kitchen."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Users"}),WD&&WD.length>0&&s.jsxs("table",{style:E.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:E.th,children:"Email"}),s.jsx("th",{style:E.th,children:"Name"}),s.jsx("th",{style:E.th,children:"Status"}),s.jsx("th",{style:E.th,children:"Role"}),s.jsx("th",{style:E.th,children:"Actions"})]})}),s.jsx("tbody",{children:WD.map(j=>s.jsxs("tr",{style:j.is_active?void 0:E.disabledRow,children:[s.jsx("td",{style:E.td,children:j.email}),s.jsx("td",{style:E.td,children:j.name||"-"}),s.jsx("td",{style:E.td,children:s.jsx("span",{style:j.is_active?E.activeStatus:E.inactiveStatus,children:j.is_active?"Active":"Disabled"})}),s.jsx("td",{style:E.td,children:j.is_admin?"Admin":"User"}),s.jsx("td",{style:E.td,children:j.id!==n.id?s.jsxs("div",{style:E.actionButtons,children:[s.jsx("button",{onClick:()=>hX.mutate(j.id),style:j.is_active?E.disableBtn:E.enableBtn,children:j.is_active?"Disable":"Enable"}),s.jsx("button",{onClick:()=>{confirm(`${j.is_admin?"Remove admin rights from":"Make admin"} ${j.email}?`)&&pX.mutate(j.id)},style:j.is_admin?E.demoteBtn:E.promoteBtn,children:j.is_admin?"Demote":"Make Admin"}),!j.is_admin&&s.jsx("button",{onClick:()=>{confirm(`Delete user ${j.email}?`)&&fX.mutate(j.id)},style:E.deleteBtn,children:"Delete"})]}):s.jsx("span",{style:E.youLabel,children:"(You)"})})]},j.id))})]})]})]}),o==="access"&&(n==null?void 0:n.is_admin)&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Access Control"}),s.jsx("p",{style:E.hint,children:"Restrict pages to admin users only. Non-admin users will not see restricted pages in the navigation."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Invoice & Data"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/upload",label:"Upload Invoices"},{path:"/invoices",label:"Invoice List & Disputes"},{path:"/purchases",label:"Purchase Chart"},{path:"/logbook",label:"Allowance Logbook"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Reports"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/gp-report",label:"Kitchen Flash & Purchase Reports"},{path:"/newbook",label:"Newbook Data"},{path:"/resos",label:"Resos Bookings & Stats"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Search & Tools"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/search",label:"Search (Invoices, Line Items, Definitions)"},{path:"/kds",label:"Kitchen Display System (KDS)"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Settings Sections"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/settings",label:"Settings Page (entire page)"},{path:"/settings-users",label:"Users Management"},{path:"/settings-access",label:"Access Control"},{path:"/settings-display",label:"Display Settings"},{path:"/settings-azure",label:"Azure OCR"},{path:"/settings-email",label:"Email Configuration"},{path:"/settings-inbox",label:"Email Inbox"},{path:"/settings-dext",label:"Dext Integration"},{path:"/settings-newbook",label:"Newbook PMS"},{path:"/settings-resos",label:"Resos Bookings"},{path:"/settings-sambapos",label:"SambaPOS EPOS"},{path:"/settings-kds",label:"Kitchen Display"},{path:"/settings-suppliers",label:"Suppliers"},{path:"/settings-search",label:"Search & Pricing"},{path:"/settings-nextcloud",label:"Nextcloud Storage"},{path:"/settings-backup",label:"Backup & Restore"},{path:"/settings-data",label:"Data Management"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsx("div",{style:{marginTop:"1.5rem"},children:s.jsx("button",{onClick:()=>rE.mutate(Array.from(eh)),style:E.saveBtn,disabled:rE.isPending,children:rE.isPending?"Saving...":"Save Restrictions"})}),VD&&s.jsx("div",{style:{...E.statusMessage,background:VD.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:VD}),s.jsxs("div",{style:{marginTop:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},children:[s.jsx("strong",{children:"Note:"})," Restricting a page will hide it from non-admin users. Admin users always have access to all pages. The Dashboard is always accessible to all users."]})]}),o==="display"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Display Settings"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Display Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Currency Symbol",s.jsxs("select",{value:He,onChange:j=>Ge(j.target.value),style:E.input,children:[s.jsx("option",{value:"£",children:"£ (GBP)"}),s.jsx("option",{value:"$",children:"$ (USD)"}),s.jsx("option",{value:"€",children:"€ (EUR)"})]})]}),s.jsxs("label",{style:E.label,children:["Date Format",s.jsxs("select",{value:ae,onChange:j=>K(j.target.value),style:E.input,children:[s.jsx("option",{value:"DD/MM/YYYY",children:"DD/MM/YYYY"}),s.jsx("option",{value:"MM/DD/YYYY",children:"MM/DD/YYYY"}),s.jsx("option",{value:"YYYY-MM-DD",children:"YYYY-MM-DD"})]})]}),s.jsxs("label",{style:E.label,children:["High Quantity Warning Threshold",s.jsx("input",{type:"number",min:"1",value:de,onChange:j=>Y(parseInt(j.target.value)||100),style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"Line items with quantity above this value will be highlighted amber"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"PDF Annotations"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:Q,onChange:j=>X(j.target.checked)}),"Enable PDF annotations",s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When enabled, the system will add visual annotations (highlights, labels) to PDFs"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:pe,onChange:j=>we(j.target.checked)}),"Show annotations in PDF preview",s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When enabled, annotations will be visible in the preview window on the review page"})]})]})]}),s.jsx("button",{onClick:A8,style:E.saveBtn,disabled:Jg.isPending,children:Jg.isPending?"Saving...":"Save Settings"}),Ne&&s.jsx("div",{style:{...E.statusMessage,background:Ne.startsWith("Error")?"#fee":"#efe"},children:Ne})]}),o==="azure"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Azure Document Intelligence"}),s.jsx("p",{style:E.hint,children:"Configure Azure credentials for invoice OCR processing."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Endpoint URL",s.jsx("input",{type:"text",value:l,onChange:j=>d(j.target.value),style:E.input,placeholder:"https://your-resource.cognitiveservices.azure.com/"})]}),s.jsxs("label",{style:E.label,children:["API Key",s.jsx("input",{type:"password",value:c,onChange:j=>u(j.target.value),style:E.input,placeholder:Lt!=null&&Lt.azure_key_set?"••••••••••••••••":"Enter your API key"}),(Lt==null?void 0:Lt.azure_key_set)&&!c&&s.jsx("span",{style:E.keyStatus,children:"Key is configured"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Post-Processing Options"}),s.jsx("p",{style:E.hint,children:"Optional cleanup of OCR results for common invoice quirks."}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:g,onChange:j=>m(j.target.checked),style:E.checkbox}),'Clean product codes (strip section headers like "CHILL/AMBIENT")']}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:y,onChange:j=>v(j.target.checked),style:E.checkbox}),'Filter subtotal rows (remove "Sub Total" lines from line items)']}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:x,onChange:j=>w(j.target.checked),style:E.checkbox}),"Use weight as quantity for KG items (when weight × price matches total)"]})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>uX.mutate(),style:E.testBtn,disabled:!(Lt!=null&&Lt.azure_key_set),children:"Test Connection"}),s.jsx("button",{onClick:A8,style:E.saveBtn,disabled:Jg.isPending,children:"Save"})]}),f&&s.jsx("div",{style:{...E.statusMessage,background:f.startsWith("Error")?"#fee":"#efe"},children:f})]}),o==="email"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Email Configuration (SMTP)"}),s.jsx("p",{style:E.hint,children:"Configure SMTP settings for sending emails."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"SMTP Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["SMTP Server",s.jsx("input",{type:"text",value:b,onChange:j=>C(j.target.value),style:E.input,placeholder:"smtp.gmail.com"})]}),s.jsxs("label",{style:E.label,children:["SMTP Port",s.jsx("input",{type:"number",value:T,onChange:j=>F(j.target.value),style:E.input,placeholder:"587"})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:A,onChange:j=>D(j.target.value),style:E.input,placeholder:"your-email@example.com"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:P,onChange:j=>L(j.target.value),style:E.input,placeholder:Lt!=null&&Lt.smtp_password_set?"••••••••••••••••":"Enter password"}),(Lt==null?void 0:Lt.smtp_password_set)&&!P&&s.jsx("span",{style:E.keyStatus,children:"Password is configured"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:W,onChange:j=>O(j.target.checked)}),"Use TLS/STARTTLS"]}),s.jsxs("label",{style:E.label,children:["From Email",s.jsx("input",{type:"email",value:U,onChange:j=>M(j.target.value),style:E.input,placeholder:"invoices@yourcompany.com"})]}),s.jsxs("label",{style:E.label,children:["From Name",s.jsx("input",{type:"text",value:I,onChange:j=>H(j.target.value),style:E.input,placeholder:"Kitchen Invoice System"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Support Request Settings"}),s.jsx("p",{style:E.hint,children:"Configure where user support requests (with screenshots) are sent."}),s.jsx("div",{style:E.form,children:s.jsxs("label",{style:E.label,children:["Support Email",s.jsx("input",{type:"email",value:z,onChange:j=>G(j.target.value),style:E.input,placeholder:"support@yourcompany.com"}),s.jsx("small",{style:{color:"#666",fontSize:"0.9em"},children:"Users can report issues with a screenshot using the ? button (visible when configured)"})]})})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:async()=>{re("Saving settings...");try{const j={smtp_host:b||null,smtp_port:parseInt(T)||587,smtp_username:A||null,smtp_password:P||void 0,smtp_use_tls:W,smtp_from_email:U||null,smtp_from_name:I||null,support_email:z||null};if(!(await fetch("/api/settings/",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(j)})).ok){re("Error: Failed to save settings");return}await i.invalidateQueries({queryKey:["settings"]}),re("Testing connection...");const Pe=await fetch("/api/settings/test-smtp",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(Pe.ok){const St=await Pe.json();re(`✓ ${St.message}`)}else{const St=await Pe.json();console.error("SMTP test error:",St),re(`Error: ${St.detail}`)}}catch(j){console.error("SMTP test exception:",j),re(`Error: ${j}`)}},style:E.testBtn,disabled:!b||!U,children:"Test Connection"}),s.jsx("button",{onClick:async()=>{try{(await fetch("/api/settings/",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({smtp_host:b||null,smtp_port:parseInt(T)||587,smtp_username:A||null,smtp_password:P||void 0,smtp_use_tls:W,smtp_from_email:U||null,smtp_from_name:I||null,support_email:z||null})})).ok?(J("✓ Saved successfully"),i.invalidateQueries({queryKey:["settings"]}),setTimeout(()=>J(null),3e3)):J("Error: Failed to save")}catch(j){J(`Error: ${j}`)}},style:E.saveBtn,children:"Save"})]}),te&&s.jsx("div",{style:{...E.statusMessage,background:te.startsWith("Error")?"#fee":"#efe"},children:te}),me&&s.jsx("div",{style:{...E.statusMessage,background:me.startsWith("Error")?"#fee":"#efe"},children:me})]}),o==="inbox"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Email Inbox (IMAP)"}),s.jsx("p",{style:E.hint,children:"Configure an email inbox to automatically process invoice attachments. Emails with confident invoice attachments will be marked as read."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"IMAP Connection"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["IMAP Server",s.jsx("input",{type:"text",value:er,onChange:j=>lr(j.target.value),style:E.input,placeholder:"imap.gmail.com"})]}),s.jsxs("label",{style:E.label,children:["Port",s.jsx("input",{type:"number",value:Kt,onChange:j=>Fn(j.target.value),style:E.input,placeholder:"993"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:Jr,onChange:j=>ei(j.target.checked)}),"Use SSL"]}),s.jsxs("label",{style:E.label,children:["Username / Email",s.jsx("input",{type:"text",value:Ui,onChange:j=>Uo(j.target.value),style:E.input,placeholder:"invoices@yourcompany.com"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:da,onChange:j=>zf(j.target.value),style:E.input,placeholder:qi!=null&&qi.imap_password_set?"••••••••••••••••":"Enter password"}),(qi==null?void 0:qi.imap_password_set)&&!da&&s.jsx("span",{style:E.keyStatus,children:"Password is configured"})]}),s.jsxs("label",{style:E.label,children:["Folder",s.jsx("input",{type:"text",value:nw,onChange:j=>rw(j.target.value),style:E.input,placeholder:"INBOX"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Processing Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Poll Interval",s.jsxs("select",{value:iw,onChange:j=>sw(parseInt(j.target.value)),style:E.input,children:[s.jsx("option",{value:5,children:"Every 5 minutes"}),s.jsx("option",{value:10,children:"Every 10 minutes"}),s.jsx("option",{value:15,children:"Every 15 minutes"}),s.jsx("option",{value:30,children:"Every 30 minutes"}),s.jsx("option",{value:60,children:"Every hour"})]})]}),s.jsxs("label",{style:E.label,children:["Confidence Threshold: ",rx,"%",s.jsx("input",{type:"range",min:30,max:90,value:rx,onChange:j=>vr(parseInt(j.target.value)),style:{width:"100%"}}),s.jsx("span",{style:E.hint,children:"Emails are marked as read when any attachment has confidence above this threshold"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ow,onChange:j=>aw(j.target.checked)}),"Enable Automatic Polling"]})]})]}),(qi==null?void 0:qi.imap_last_sync)&&s.jsxs("div",{style:{...E.hint,marginBottom:"1rem"},children:["Last sync: ",new Date(qi.imap_last_sync).toLocaleString()]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:async()=>{var j;Ho("Testing connection...");try{const Pe=await(await fetch("/api/imap/test-connection",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({imap_host:er||void 0,imap_port:parseInt(Kt)||void 0,imap_use_ssl:Jr,imap_username:Ui||void 0,imap_password:da||void 0})})).json();Pe.success?Ho(`✓ Connected! Available folders: ${((j=Pe.folders)==null?void 0:j.join(", "))||"INBOX"}`):Ho(`Error: ${Pe.error}`)}catch(V){Ho(`Error: ${V}`)}},style:E.testBtn,disabled:!er,children:"Test Connection"}),s.jsx("button",{onClick:async()=>{$u("Syncing...");try{const V=await(await fetch("/api/imap/sync-now",{method:"POST",headers:{Authorization:`Bearer ${e}`}})).json();if(V.success){const Pe=V.results;$u(`✓ Sync complete: ${Pe.emails_processed} emails processed, ${Pe.invoices_created} invoices created, ${Pe.emails_marked_read} marked as read`),i.invalidateQueries({queryKey:["imap-settings"]}),i.invalidateQueries({queryKey:["imap-logs"]}),i.invalidateQueries({queryKey:["imap-stats"]})}else $u(`Error: ${V.error}`)}catch(j){$u(`Error: ${j}`)}},style:E.testBtn,disabled:!(qi!=null&&qi.imap_password_set)&&!da,children:"Sync Now"}),s.jsx("button",{onClick:async()=>{Of("Saving...");try{const j=await fetch("/api/imap/settings",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({imap_host:er||null,imap_port:parseInt(Kt)||993,imap_use_ssl:Jr,imap_username:Ui||null,imap_password:da||void 0,imap_folder:nw||"INBOX",imap_poll_interval:iw,imap_enabled:ow,imap_confidence_threshold:rx/100})});if(j.ok)Of("✓ Settings saved"),zf(""),i.invalidateQueries({queryKey:["imap-settings"]});else{const V=await j.json();Of(`Error: ${V.detail}`)}}catch(j){Of(`Error: ${j}`)}},style:E.saveBtn,children:"Save Settings"})]}),Gr&&s.jsx("div",{style:{...E.statusMessage,background:Gr.startsWith("Error")?"#fee":"#efe"},children:Gr}),lw&&s.jsx("div",{style:{...E.statusMessage,background:lw.startsWith("Error")?"#fee":"#efe"},children:lw}),Qu&&s.jsx("div",{style:{...E.statusMessage,background:Qu.startsWith("Error")?"#fee":"#efe"},children:Qu}),Wc&&s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Sync Statistics"}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Last 24 Hours"}),s.jsxs("p",{children:[Wc.last_24h.emails_processed," emails"]}),s.jsxs("p",{children:[Wc.last_24h.invoices_created," invoices"]}),s.jsxs("p",{children:[Wc.last_24h.confident_invoices," confident"]})]}),s.jsxs("div",{children:[s.jsx("strong",{children:"Last 7 Days"}),s.jsxs("p",{children:[Wc.last_7d.emails_processed," emails"]}),s.jsxs("p",{children:[Wc.last_7d.invoices_created," invoices"]}),s.jsxs("p",{children:[Wc.last_7d.confident_invoices," confident"]})]}),s.jsxs("div",{children:[s.jsx("strong",{children:"Last 30 Days"}),s.jsxs("p",{children:[Wc.last_30d.emails_processed," emails"]}),s.jsxs("p",{children:[Wc.last_30d.invoices_created," invoices"]}),s.jsxs("p",{children:[Wc.last_30d.confident_invoices," confident"]})]})]})]}),qD&&qD.length>0&&s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Recent Processing Logs"}),s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #ddd"},children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem"},children:"Date"}),s.jsx("th",{style:{textAlign:"left",padding:"0.5rem"},children:"Subject"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem"},children:"Attachments"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem"},children:"Invoices"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem"},children:"Status"})]})}),s.jsx("tbody",{children:qD.map(j=>s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem"},children:new Date(j.processed_at).toLocaleString()}),s.jsx("td",{style:{padding:"0.5rem",maxWidth:"250px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.email_subject||"(no subject)"}),s.jsx("td",{style:{textAlign:"center",padding:"0.5rem"},children:j.attachments_count}),s.jsxs("td",{style:{textAlign:"center",padding:"0.5rem"},children:[j.invoices_created,j.confident_invoices>0&&s.jsxs("span",{style:{color:"#27ae60"},children:[" (",j.confident_invoices," confident)"]})]}),s.jsx("td",{style:{textAlign:"center",padding:"0.5rem"},children:j.marked_as_read?s.jsx("span",{style:{color:"#27ae60"},children:"Read"}):j.processing_status==="skipped"?s.jsx("span",{style:{color:"#95a5a6"},children:"Skipped"}):s.jsx("span",{style:{color:"#e67e22"},children:"Unread"})})]},j.id))})]})]})]}),o==="dext"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Dext Integration"}),s.jsx("p",{style:E.hint,children:"Configure automatic invoice submission to Dext."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Dext Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Dext Email Address",s.jsx("input",{type:"email",value:ne,onChange:j=>ye(j.target.value),style:E.input,placeholder:"yourcompany@dext.com"}),s.jsx("small",{style:{color:"#666",fontSize:"0.9em"},children:"Invoices will be sent to this email address"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ke,onChange:j=>Ye(j.target.checked)}),"Include invoice notes in email body"]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:De,onChange:j=>qe(j.target.checked)}),"Include non-stock items table in email body"]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ue,onChange:j=>Ze(j.target.checked)}),"Automatically send to Dext when invoice is confirmed",s.jsx("small",{style:{color:"#e67e22",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"⚠️ Leave disabled for testing. Enable only when ready for production."})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ee,onChange:j=>Z(j.target.checked)}),'Enable manual "Send to Dext" button on invoice review page',s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When disabled, only the send status will be displayed (without send/resend buttons)"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ge,onChange:j=>Te(j.target.checked)}),"Include PDF annotations (highlights) when sending to Dext",s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When enabled, non-stock items will be highlighted in yellow on the PDF attachment"})]})]})]}),s.jsx("button",{onClick:async()=>{try{(await fetch("/api/settings/",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({dext_email:ne||null,dext_include_notes:ke,dext_include_non_stock:De,dext_auto_send_enabled:ue,dext_manual_send_enabled:ee,dext_include_annotations:ge})})).ok?(he("✓ Saved successfully"),i.invalidateQueries({queryKey:["settings"]}),setTimeout(()=>he(null),3e3)):he("Error: Failed to save")}catch(j){he(`Error: ${j}`)}},style:E.saveBtn,children:"Save Settings"}),Be&&s.jsx("div",{style:{...E.statusMessage,background:Be.startsWith("Error")?"#fee":"#efe"},children:Be}),s.jsxs("div",{style:{...E.settingsBlock,marginTop:"2rem",borderTop:"1px solid #ddd",paddingTop:"1.5rem"},children:[s.jsx("h3",{style:E.blockTitle,children:"Bulk Operations"}),s.jsx("p",{style:E.hint,children:"Mark all existing invoices as sent to Dext without actually sending them. Useful for migrating to the system."}),s.jsx("button",{onClick:async()=>{if(window.confirm(`Mark ALL invoices not yet sent to Dext as sent? This will mark all existing unsent invoices as already sent to Dext. Use this when migrating to the system or if invoices were sent outside the system. This action cannot be undone.`))try{const j=await fetch("/api/invoices/bulk/mark-all-dext-sent",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();he(`✓ ${V.message}`),setTimeout(()=>he(null),5e3)}else{const V=await j.json();he(`Error: ${V.detail||"Failed to mark invoices"}`)}}catch(j){he(`Error: ${j}`)}},style:{...E.saveBtn,background:"#6c757d"},children:"Mark All Invoices as Sent to Dext"})]})]}),o==="newbook"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Newbook PMS Integration"}),s.jsx("p",{style:E.hint,children:"Connect to Newbook to fetch revenue and occupancy data for GP calculations."}),XK&&s.jsx("div",{style:{padding:"0.5rem",background:"#fff3cd",borderRadius:"4px",marginBottom:"1rem"},children:"Loading Newbook settings..."}),g8&&s.jsxs("div",{style:{padding:"0.5rem",background:"#f8d7da",borderRadius:"4px",marginBottom:"1rem"},children:["Error loading settings: ",g8.message]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Credentials"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:ot,onChange:j=>ut(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:Ot,onChange:j=>An(j.target.value),style:E.input,placeholder:tr!=null&&tr.newbook_api_password_set?"••••••••":"Enter password"})]}),s.jsxs("label",{style:E.label,children:["API Key",s.jsx("input",{type:"password",value:on,onChange:j=>Ke(j.target.value),style:E.input,placeholder:tr!=null&&tr.newbook_api_key_set?"••••••••":"Enter API key"})]}),s.jsxs("label",{style:E.label,children:["Region",s.jsxs("select",{value:Rt,onChange:j=>vt(j.target.value),style:E.input,children:[s.jsx("option",{value:"au",children:"Australia (au)"}),s.jsx("option",{value:"ap",children:"Asia Pacific (ap)"}),s.jsx("option",{value:"eu",children:"Europe (eu)"}),s.jsx("option",{value:"us",children:"United States (us)"})]})]}),s.jsxs("label",{style:E.label,children:["Instance ID (optional)",s.jsx("input",{type:"text",value:Cr,onChange:j=>Qt(j.target.value),style:E.input,placeholder:"Property/Hotel ID"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>k8.mutate(),style:E.testBtn,disabled:k8.isPending,children:"Test Connection"}),s.jsx("button",{onClick:xX,style:E.saveBtn,disabled:rh.isPending,children:"Save Credentials"})]}),aa&&s.jsx("div",{style:{...E.statusMessage,background:aa.startsWith("Error")?"#fee":"#efe"},children:aa})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"GL Account Tracking (for Revenue)"}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>dE.mutate(),style:E.actionBtn,disabled:dE.isPending,children:dE.isPending?"Fetching...":"Fetch GL Accounts"}),s.jsxs("button",{onClick:()=>xr(!0),style:E.actionBtn,disabled:!(Zd!=null&&Zd.length),children:["Select Accounts (",(Zd==null?void 0:Zd.filter(j=>j.is_tracked).length)||0," selected)"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Meal Allocation GL Mapping"}),s.jsx("p",{style:E.hint,children:"Select from tracked GL accounts above to map meal allocations."}),(()=>{const j=(Zd==null?void 0:Zd.filter(dr=>dr.is_tracked))||[],V=Ci?Ci.split(",").map(dr=>dr.trim()):[],Pe=Gs?Gs.split(",").map(dr=>dr.trim()):[],St=dr=>{const xo=new Set(V);xo.has(dr)?xo.delete(dr):xo.add(dr);const Vi=Array.from(xo).join(",");Lr(Vi),rh.mutate({newbook_breakfast_gl_codes:Vi})},yr=dr=>{const xo=new Set(Pe);xo.has(dr)?xo.delete(dr):xo.add(dr);const Vi=Array.from(xo).join(",");Ai(Vi),rh.mutate({newbook_dinner_gl_codes:Vi})};return s.jsxs("div",{style:{display:"flex",gap:"2rem",flexWrap:"wrap"},children:[s.jsxs("div",{style:{flex:1,minWidth:"200px"},children:[s.jsx("strong",{children:"Breakfast Allocations"}),s.jsx("div",{style:E.mealMappingList,children:j.length===0?s.jsx("span",{style:E.mealMappingEmpty,children:"No tracked accounts - select GL accounts above first"}):j.map(dr=>s.jsxs("label",{style:E.mealMappingItem,children:[s.jsx("input",{type:"checkbox",checked:V.includes(dr.gl_code||""),onChange:()=>St(dr.gl_code||"")}),s.jsx("span",{children:dr.gl_name})]},dr.id))})]}),s.jsxs("div",{style:{flex:1,minWidth:"200px"},children:[s.jsx("strong",{children:"Dinner Allocations"}),s.jsx("div",{style:E.mealMappingList,children:j.length===0?s.jsx("span",{style:E.mealMappingEmpty,children:"No tracked accounts - select GL accounts above first"}):j.map(dr=>s.jsxs("label",{style:E.mealMappingItem,children:[s.jsx("input",{type:"checkbox",checked:Pe.includes(dr.gl_code||""),onChange:()=>yr(dr.gl_code||"")}),s.jsx("span",{children:dr.gl_name})]},dr.id))})]})]})})()]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"VAT Rates"}),s.jsx("p",{style:E.hint,children:"Set VAT rates to calculate net values from gross amounts in Newbook inventory items."}),s.jsxs("div",{style:{display:"flex",gap:"2rem",flexWrap:"wrap",marginBottom:"1rem"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"150px"},children:["Breakfast VAT Rate (%)",s.jsx("input",{type:"number",value:Ks,onChange:j=>un(j.target.value),onBlur:()=>{const j=parseFloat(Ks)/100;!isNaN(j)&&j>=0&&j<=1&&rh.mutate({newbook_breakfast_vat_rate:j.toString()})},style:E.input,min:"0",max:"100",step:"0.1"})]}),s.jsxs("label",{style:{...E.label,flex:1,minWidth:"150px"},children:["Dinner VAT Rate (%)",s.jsx("input",{type:"number",value:Fr,onChange:j=>zi(j.target.value),onBlur:()=>{const j=parseFloat(Fr)/100;!isNaN(j)&&j>=0&&j<=1&&rh.mutate({newbook_dinner_vat_rate:j.toString()})},style:E.input,min:"0",max:"100",step:"0.1"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Room Categories (for Occupancy)"}),s.jsx("p",{style:E.hint,children:"Select which room types to include in occupancy and guest calculations. Exclude overflow rooms etc."}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>hE.mutate(),style:E.actionBtn,disabled:hE.isPending,children:hE.isPending?"Fetching...":"Fetch Room Categories"}),s.jsxs("button",{onClick:()=>rs(!0),style:E.actionBtn,disabled:!(cl!=null&&cl.length),children:["Select Types (",(cl==null?void 0:cl.filter(j=>j.is_included).reduce((j,V)=>j+(V.room_count||0),0))||0," rooms in ",(cl==null?void 0:cl.filter(j=>j.is_included).length)||0," types)"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Data Sync"}),s.jsxs("p",{style:E.hint,children:["Last sync: ",tr!=null&&tr.newbook_last_sync?new Date(tr.newbook_last_sync).toLocaleString():"Never"]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>cE.mutate(),style:E.actionBtn,disabled:cE.isPending,children:cE.isPending?"Syncing...":"Update Forecast Data"}),s.jsx("button",{onClick:()=>Jt(!0),style:E.actionBtn,children:"Fetch Historical Data"})]}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:(tr==null?void 0:tr.newbook_auto_sync_enabled)||!1,onChange:j=>rh.mutate({newbook_auto_sync_enabled:j.target.checked})}),"Enable automatic daily sync (4:00 AM)"]}),s.jsxs("div",{style:{marginTop:"1rem",paddingTop:"1rem",borderTop:"1px solid #eee"},children:[s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:(tr==null?void 0:tr.newbook_upcoming_sync_enabled)||!1,onChange:j=>{const V=j.target.checked;console.log("[DEBUG] Checkbox onChange fired, newValue:",V),rh.mutate({newbook_upcoming_sync_enabled:V})}}),"Enable frequent upcoming sync (next 7 days)"]}),s.jsx("small",{style:E.hint,children:"Keeps ResidentsTableChart fresh with more frequent updates"})]}),(tr==null?void 0:tr.newbook_upcoming_sync_enabled)&&s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"Sync interval (minutes)"}),s.jsx("input",{type:"number",value:(tr==null?void 0:tr.newbook_upcoming_sync_interval)||15,onChange:j=>rh.mutate({newbook_upcoming_sync_interval:parseInt(j.target.value)||15}),min:5,max:60,style:{...E.input,width:"100px"}}),s.jsx("small",{style:E.hint,children:"Recommended: 15 minutes"})]}),(tr==null?void 0:tr.newbook_last_upcoming_sync)&&s.jsx("div",{style:E.formGroup,children:s.jsxs("small",{style:E.hint,children:["Last frequent sync: ",new Date(tr.newbook_last_upcoming_sync).toLocaleString()]})})]}),Vd&&s.jsx("div",{style:{...E.statusMessage,background:Vd.startsWith("Error")?"#fee":"#efe"},children:Vd}),s.jsxs("div",{style:{marginTop:"1rem",paddingTop:"1.5rem",borderTop:"1px solid #e0e0e0"},children:[s.jsx("a",{href:"/newbook",style:{display:"inline-block",padding:"0.75rem 1.5rem",background:"#4a90d9",color:"white",textDecoration:"none",borderRadius:"6px",fontWeight:500},children:"View Newbook Data"}),s.jsx("p",{style:{...E.hint,marginTop:"0.5rem"},children:"View synced revenue, charges, and occupancy data from Newbook."})]})]}),o==="resos"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Resos Restaurant Bookings Integration"}),s.jsx("p",{style:E.hint,children:"Connect to Resos to fetch booking data, flag notable reservations, and track covers."}),QK&&s.jsx("div",{style:{padding:"0.5rem",background:"#fff3cd",borderRadius:"4px",marginBottom:"1rem"},children:"Loading Resos settings..."}),YK&&s.jsx("div",{style:{padding:"0.5rem",background:"#f8d7da",color:"#721c24",borderRadius:"4px",marginBottom:"1rem"},children:"Failed to load Resos settings"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Configuration"}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{style:E.label,children:"Resos API Key *"}),s.jsx("input",{type:"password",value:bt,onChange:j=>yn(j.target.value),placeholder:Dn!=null&&Dn.resos_api_key_set?"••••••••••••":"Enter API key",style:E.input}),(Dn==null?void 0:Dn.resos_api_key_set)&&s.jsx("small",{style:E.hint,children:"API key is configured (enter new value to update)"})]}),s.jsx("button",{onClick:async()=>{try{Qs("Testing...");const j=await fetch("/api/resos/test-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok)Qs("✓ Connection successful");else{const V=await j.json();Qs(`✗ Connection failed: ${V.detail||"Unknown error"}`)}}catch(j){Qs(`✗ Connection failed: ${j}`)}setTimeout(()=>Qs(null),5e3)},style:E.secondaryButton,children:"Test Connection"}),fs&&s.jsx("div",{style:{marginTop:"0.5rem",fontSize:"0.9rem"},children:fs})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Flagging Configuration"}),s.jsxs("div",{style:{...E.formGroup,marginBottom:"1.5rem"},children:[s.jsx("label",{style:E.label,children:"Large Group Threshold"}),s.jsx("input",{type:"number",value:tn,onChange:j=>ci(parseInt(j.target.value)||8),style:{...E.input,maxWidth:"150px"}}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:"Flag bookings with this many people or more (default: 8)"})]}),s.jsxs("div",{style:{...E.formGroup,marginBottom:"1.5rem"},children:[s.jsx("label",{style:E.label,children:"Note Keywords (pipe-separated)"}),s.jsx("input",{type:"text",value:hn,onChange:j=>Ti(j.target.value),placeholder:"birthday|anniversary|proposal|vip",style:{...E.input,maxWidth:"600px"}}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:"Flag bookings with these keywords in notes"})]}),s.jsxs("div",{style:{...E.formGroup,marginBottom:"1.5rem"},children:[s.jsx("label",{style:E.label,children:"Allergy Keywords (pipe-separated)"}),s.jsx("input",{type:"text",value:js,onChange:j=>Ar(j.target.value),placeholder:"gluten|dairy|nut|shellfish|vegan",style:{...E.input,maxWidth:"600px"}}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:'Additional allergy terms to detect in notes (for "Other Allergies" free-text field)'})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Custom Field Mapping"}),s.jsx("p",{style:E.hint,children:"Map Resos custom fields to system fields. Fetch from API to populate available fields."}),s.jsx("button",{onClick:async()=>{try{const j=await fetch("/api/resos/custom-fields",{headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();nn(V.custom_fields||[]),xn("Custom fields fetched successfully")}else xn("Failed to fetch custom fields")}catch(j){xn(`Error: ${j}`)}setTimeout(()=>xn(null),5e3)},style:E.secondaryButton,children:"Fetch Custom Fields from Resos"}),Pa.length>0&&s.jsx("div",{style:{marginTop:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},children:[{key:"booking_number",label:"Hotel Booking #",hint:"Newbook/hotel booking reference number from Resos custom field"},{key:"hotel_guest",label:"Hotel Guest",hint:"Yes/No field indicating if diner is a hotel guest"},{key:"dbb",label:"DBB (Dinner B&B)",hint:"Yes/No field indicating Dinner Bed & Breakfast package guests"},{key:"package",label:"Package",hint:"Yes/No field indicating package deal bookings (e.g., special offers)"},{key:"exclude",label:"Group/Exclude",hint:'Free-text field for group codes and exclusions (e.g., "G#123" for groups)'},{key:"allergies",label:"Allergies (Predefined)",hint:"Multi-select field with predefined allergy options (e.g., Gluten, Dairy, Nuts)"},{key:"allergies_other",label:"Other Allergies",hint:"Free-text field for custom allergy notes not in predefined list"}].map(j=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},children:[s.jsx("label",{style:{fontWeight:"500",color:"#333",fontSize:"0.9rem"},children:j.label}),s.jsxs("select",{value:$s[j.key]||"",onChange:V=>Gd({...$s,[j.key]:V.target.value}),style:{...E.input,maxWidth:"400px",fontSize:"0.85rem"},children:[s.jsx("option",{value:"",children:"-- Select Field --"}),Pa.map(V=>s.jsx("option",{value:V._id,children:V.name},V._id))]}),s.jsx("small",{style:{...E.hint,marginTop:0,fontSize:"0.75rem"},children:j.hint})]},j.key))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Opening Hours Mapping"}),s.jsx("p",{style:E.hint,children:"Map regular service periods (excludes special/one-off periods). Resos extends closing times by the default booking length to allow late bookings - the Actual End field shows the calculated time when kitchen closes for new arrivals."}),s.jsx("button",{onClick:async()=>{try{const j=await fetch("/api/resos/sync/opening-hours",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){xn("Failed to sync opening hours to database"),setTimeout(()=>xn(null),5e3);return}const V=await j.json(),Pe=await fetch("/api/resos/opening-hours",{headers:{Authorization:`Bearer ${e}`}});if(Pe.ok){const St=await Pe.json();qu(St.opening_hours||[]),xn(`Opening hours synced to database: ${V.count} service periods`)}else xn("Synced to database but failed to fetch for display")}catch(j){xn(`Error: ${j}`)}setTimeout(()=>xn(null),5e3)},style:E.secondaryButton,children:"Fetch Opening Hours from Resos"}),Zl.length>0&&s.jsx("div",{style:{marginTop:"1rem",overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"2px solid #ddd"},children:[s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Period Name"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Start Time"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"End Time (Resos)"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Actual End"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Display Name"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Service Type"})]})}),s.jsx("tbody",{children:Zl.map(j=>{const V=mo.find(Pe=>Pe.resos_id===j._id);return s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem"},children:j.name}),s.jsx("td",{style:{padding:"0.5rem"},children:j.startTime||"-"}),s.jsx("td",{style:{padding:"0.5rem"},children:j.endTime||"-"}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"time",value:(V==null?void 0:V.actual_end)||"",onChange:Pe=>{const St=mo.filter(yr=>yr.resos_id!==j._id);St.push({resos_id:j._id,display_name:(V==null?void 0:V.display_name)||j.name,actual_end:Pe.target.value,service_type:(V==null?void 0:V.service_type)||""}),Bc(St)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px"},placeholder:"Enter actual end time"})}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"text",value:(V==null?void 0:V.display_name)||"",onChange:Pe=>{const St=mo.filter(yr=>yr.resos_id!==j._id);St.push({resos_id:j._id,display_name:Pe.target.value,actual_end:(V==null?void 0:V.actual_end)||"",service_type:(V==null?void 0:V.service_type)||""}),Bc(St)},placeholder:j.name,style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px",width:"100%"}})}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsxs("select",{value:(V==null?void 0:V.service_type)||"",onChange:Pe=>{const St=mo.filter(yr=>yr.resos_id!==j._id);St.push({resos_id:j._id,display_name:(V==null?void 0:V.display_name)||j.name,actual_end:(V==null?void 0:V.actual_end)||"",service_type:Pe.target.value}),Bc(St)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px",width:"120px"},children:[s.jsx("option",{value:"",children:"-- Select --"}),s.jsx("option",{value:"breakfast",children:"Breakfast"}),s.jsx("option",{value:"lunch",children:"Lunch"}),s.jsx("option",{value:"afternoon",children:"Afternoon"}),s.jsx("option",{value:"dinner",children:"Dinner"}),s.jsx("option",{value:"other",children:"Other"})]})})]},j._id)})})]})})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Manual Breakfast Configuration"}),s.jsx("p",{style:E.hint,children:"Since breakfast bookings are not taken through Resos, you can define manual breakfast periods to properly categorize early morning restaurant tickets. Configure different times for each day of the week."}),s.jsx("div",{style:E.formGroup,children:s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:Ra,onChange:j=>Xd(j.target.checked),style:{cursor:"pointer"}}),s.jsx("span",{style:{fontWeight:"bold"},children:"Enable Manual Breakfast Periods"})]})}),Ra&&s.jsxs("div",{style:{marginTop:"1rem"},children:[s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"2px solid #ddd",background:"#f9f9f9"},children:[s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Day"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Start Time"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"End Time"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Actions"})]})}),s.jsx("tbody",{children:["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"].map((j,V)=>{const Pe=V+1,St=No.find(yr=>yr.day===Pe);return s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem",fontWeight:"bold"},children:j}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"time",value:(St==null?void 0:St.start)||"",onChange:yr=>{const dr=No.filter(xo=>xo.day!==Pe);(yr.target.value||St!=null&&St.end)&&dr.push({day:Pe,start:yr.target.value,end:(St==null?void 0:St.end)||""}),Js(dr)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px"}})}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"time",value:(St==null?void 0:St.end)||"",onChange:yr=>{const dr=No.filter(xo=>xo.day!==Pe);(yr.target.value||St!=null&&St.start)&&dr.push({day:Pe,start:(St==null?void 0:St.start)||"",end:yr.target.value}),Js(dr)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px"}})}),s.jsx("td",{style:{padding:"0.5rem"},children:St&&s.jsx("button",{onClick:()=>{Js(No.filter(yr=>yr.day!==Pe))},style:{padding:"0.25rem 0.5rem",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"Clear"})})]},Pe)})})]}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:"Leave times blank for days without breakfast service. Times are in 24-hour format (e.g., 07:00 - 11:00)."})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Hotel Arrivals Widget Configuration"}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{style:{fontWeight:"bold",display:"block",marginBottom:"0.5rem"},children:"Service Filter for Arrivals Widget"}),s.jsxs("select",{value:Kd||"",onChange:j=>Zs(j.target.value||null),style:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",width:"300px"},children:[s.jsx("option",{value:"",children:"All Services"}),Array.from(new Set(mo.map(j=>j.service_type).filter(j=>j))).sort().map(j=>s.jsx("option",{value:j,children:j.charAt(0).toUpperCase()+j.slice(1)},j))]}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:'Filter the "Hotel Arrivals & Restaurant Bookings" dashboard widget to show only bookings for a specific service type (e.g., Dinner only). This filter spans all opening hours mapped to the selected service type across different days/times.'})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Sync Configuration"}),s.jsxs("div",{style:E.formGroup,children:[s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:(Dn==null?void 0:Dn.resos_auto_sync_enabled)||!1,onChange:j=>lE.mutate({resos_auto_sync_enabled:j.target.checked})}),"Enable automatic daily sync (4:30 AM)"]}),s.jsx("small",{style:E.hint,children:"Syncs all historical and forecast data (past 30 days + next 60 days)"})]}),(Dn==null?void 0:Dn.resos_last_sync)&&s.jsx("div",{style:E.formGroup,children:s.jsxs("small",{style:E.hint,children:["Last full sync: ",new Date(Dn.resos_last_sync).toLocaleString()]})}),s.jsxs("div",{style:E.formGroup,children:[s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:(Dn==null?void 0:Dn.resos_upcoming_sync_enabled)||!1,onChange:j=>lE.mutate({resos_upcoming_sync_enabled:j.target.checked})}),"Enable frequent upcoming sync (next 7 days)"]}),s.jsx("small",{style:E.hint,children:"Keeps upcoming bookings fresh with more frequent updates"})]}),(Dn==null?void 0:Dn.resos_upcoming_sync_enabled)&&s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"Sync interval (minutes)"}),s.jsx("input",{type:"number",value:(Dn==null?void 0:Dn.resos_upcoming_sync_interval)||15,onChange:j=>lE.mutate({resos_upcoming_sync_interval:parseInt(j.target.value)||15}),min:5,max:60,style:E.textInput}),s.jsx("small",{style:E.hint,children:"How often to sync upcoming bookings (5-60 minutes, default 15)"})]}),(Dn==null?void 0:Dn.resos_last_upcoming_sync)&&s.jsx("div",{style:E.formGroup,children:s.jsxs("small",{style:E.hint,children:["Last frequent sync: ",new Date(Dn.resos_last_upcoming_sync).toLocaleString()]})}),(Dn==null?void 0:Dn.resos_upcoming_sync_enabled)&&s.jsx("div",{style:E.formGroup,children:s.jsx("button",{onClick:async()=>{var j;try{xn("Syncing upcoming bookings...");const V=await fetch("/api/resos/sync/upcoming",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(V.ok){const Pe=await V.json();xn(`✓ Upcoming sync complete: ${((j=Pe.upcoming)==null?void 0:j.bookings_fetched)||0} bookings`),i.invalidateQueries({queryKey:["resos-settings"]})}else xn("✗ Upcoming sync failed")}catch(V){xn(`✗ Error: ${V}`)}setTimeout(()=>xn(null),1e4)},style:E.secondaryButton,children:"Sync Now (Next 7 Days)"})}),s.jsxs("div",{style:{display:"flex",gap:"1rem",marginTop:"1rem"},children:[s.jsx("button",{onClick:async()=>{try{xn("Syncing forecast...");const j=await fetch("/api/resos/sync/forecast",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();xn(`✓ Forecast synced: ${V.bookings_fetched} bookings`),i.invalidateQueries({queryKey:["resos-settings"]})}else xn("✗ Forecast sync failed")}catch(j){xn(`✗ Error: ${j}`)}setTimeout(()=>xn(null),1e4)},style:E.secondaryButton,children:"Sync Forecast (Next 60 Days)"}),s.jsx("button",{onClick:()=>Ic(!0),style:E.secondaryButton,children:"Sync Historical (Custom Range)"})]}),Lo&&s.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem",background:Lo.includes("✓")?"#d4edda":"#f8d7da",borderRadius:"4px"},children:Lo})]}),s.jsx("button",{onClick:async()=>{try{(await fetch("/api/resos/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({resos_api_key:bt||void 0,resos_large_group_threshold:tn,resos_note_keywords:hn,resos_allergy_keywords:js,resos_custom_field_mapping:$s,resos_opening_hours_mapping:mo,resos_arrival_widget_service_filter:Kd||null,resos_enable_manual_breakfast:Ra,resos_manual_breakfast_periods:No})})).ok?(xn("✓ Settings saved successfully"),i.invalidateQueries({queryKey:["resos-settings"]})):xn("✗ Failed to save settings")}catch(j){xn(`✗ Error: ${j}`)}setTimeout(()=>xn(null),5e3)},style:{...E.button,marginTop:"2rem"},children:"Save Resos Settings"}),s.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid #e0e0e0"},children:[s.jsx("a",{href:"/resos",style:{display:"inline-block",padding:"0.75rem 1.5rem",background:"#0066cc",color:"white",textDecoration:"none",borderRadius:"6px",fontWeight:500},children:"View Resos Booking Data"}),s.jsx("p",{style:{...E.hint,marginTop:"0.5rem"},children:"View synced booking data, covers, and flagged reservations from Resos."})]}),Ba&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Sync Historical Bookings"}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"From Date:"}),s.jsx("input",{type:"date",value:al,onChange:j=>ie(j.target.value),style:E.input})]}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"To Date:"}),s.jsx("input",{type:"date",value:nt,onChange:j=>$(j.target.value),style:E.input})]}),s.jsxs("div",{style:{display:"flex",gap:"1rem",marginTop:"1rem"},children:[s.jsx("button",{onClick:async()=>{try{xn("Syncing historical data...");const j=await fetch(`/api/resos/sync/historical?from_date=${al}&to_date=${nt}`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();xn(`✓ Historical synced: ${V.bookings_fetched} bookings`),Ic(!1),i.invalidateQueries({queryKey:["resos-settings"]})}else xn("✗ Historical sync failed")}catch(j){xn(`✗ Error: ${j}`)}setTimeout(()=>xn(null),1e4)},style:E.button,children:"Start Sync"}),s.jsx("button",{onClick:()=>Ic(!1),style:E.secondaryButton,children:"Cancel"})]})]})})]}),o==="sambapos"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"SambaPOS EPOS Settings"}),s.jsx("p",{style:E.hint,children:"Connect to your SambaPOS MSSQL database to fetch kitchen courses and sales data for Top Sellers reports."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Database Connection"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Server Host",s.jsx("input",{type:"text",value:ze,onChange:j=>Qe(j.target.value),style:E.input,placeholder:"localhost\\SQLEXPRESS17"}),s.jsx("span",{style:{fontSize:"0.8rem",color:"#888"},children:"For named instances, use format: hostname\\instancename"})]}),s.jsxs("label",{style:E.label,children:["Port",s.jsx("input",{type:"number",value:pt,onChange:j=>kt(j.target.value),style:E.input,placeholder:"1433"}),s.jsx("span",{style:{fontSize:"0.8rem",color:"#888"},children:"Default SQL Server port is 1433 (ignored for named instances)"})]}),s.jsxs("label",{style:E.label,children:["Database Name",s.jsx("input",{type:"text",value:Ht,onChange:j=>Gt(j.target.value),style:E.input,placeholder:"SambaPOS5"})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:Er,onChange:j=>ar(j.target.value),style:E.input,placeholder:"sa"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:Kn,onChange:j=>is(j.target.value),style:E.input,placeholder:$n!=null&&$n.sambapos_db_password_set?"********":"Enter password"}),($n==null?void 0:$n.sambapos_db_password_set)&&!Kn&&s.jsx("span",{style:E.keyStatus,children:"Password is configured"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>gE.mutate(),style:E.testBtn,disabled:gE.isPending||!ze||!Ht||!Er,children:gE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:bX,style:E.saveBtn,disabled:pE.isPending,children:pE.isPending?"Saving...":"Save Connection"})]}),On&&s.jsx("div",{style:{...E.statusMessage,background:On.startsWith("Error")?"#fee":"#efe"},children:On})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Kitchen Courses for Top Sellers"}),s.jsx("p",{style:E.hint,children:"Select and order kitchen courses for the Top Sellers report. Use arrows to change the display order in reports."}),FE?$K?s.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"#666"},children:"Loading courses..."}):x8?s.jsxs("div",{style:{padding:"1rem",background:"#fee",borderRadius:"6px",color:"#c00"},children:["Failed to load courses: ",x8.message,s.jsx("button",{onClick:()=>y8(),style:{...E.actionBtn,marginLeft:"1rem"},children:"Retry"})]}):Zg&&Zg.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("strong",{style:{display:"block",marginBottom:"0.5rem"},children:"Selected Courses (in report order):"}),Tn.length===0?s.jsx("div",{style:{padding:"1rem",background:"#f8f9fa",borderRadius:"6px",color:"#666",fontStyle:"italic"},children:"No courses selected. Add courses from the list below."}):s.jsx("div",{style:E.sortableList,children:Tn.map((j,V)=>s.jsxs("div",{style:E.sortableItem,children:[s.jsx("span",{style:E.sortableOrder,children:V+1}),s.jsx("span",{style:E.sortableName,children:j}),s.jsxs("div",{style:E.sortableButtons,children:[s.jsx("button",{onClick:()=>vX(V),disabled:V===0,style:E.arrowBtn,title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>wX(V),disabled:V===Tn.length-1,style:E.arrowBtn,title:"Move down",children:"▼"}),s.jsx("button",{onClick:()=>T8(j),style:E.removeBtn,title:"Remove",children:"✕"})]})]},j))})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("strong",{style:{display:"block",marginBottom:"0.5rem"},children:"Available Courses:"}),s.jsxs("div",{style:E.sambaCategoryGrid,children:[Zg.filter(j=>!Tn.includes(j.name)).map(j=>s.jsxs("button",{onClick:()=>T8(j.name),style:E.addCourseBtn,children:["+ ",j.name]},j.id)),Zg.filter(j=>!Tn.includes(j.name)).length===0&&s.jsx("span",{style:{color:"#666",fontStyle:"italic"},children:"All courses selected"})]})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{Zg&&Dt(Zg.map(j=>j.name))},style:E.actionBtn,children:"Select All"}),s.jsx("button",{onClick:()=>Dt([]),style:E.actionBtn,children:"Clear All"}),s.jsx("button",{onClick:SX,style:E.saveBtn,disabled:mE.isPending,children:mE.isPending?"Saving...":"Save Courses"})]}),s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:"#e8f4fd",borderRadius:"6px",textAlign:"center",fontWeight:500},children:[Tn.length," of ",Zg.length," courses selected"]})]}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:'No courses found. Please verify your SambaPOS menu items have the "Kitchen Course" product tag configured.'}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:"Configure and test your database connection above to load courses."})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Excluded Menu Categories"}),s.jsx("p",{style:E.hint,children:'Select menu categories (GroupCode) to exclude from the Top Sellers report (e.g., "Drinks", "Extras").'}),FE?JK?s.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"#666"},children:"Loading menu categories..."}):UD&&UD.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>Fi(new Set),style:E.actionBtn,children:"Clear Exclusions"}),s.jsx("button",{onClick:kX,style:E.saveBtn,disabled:yE.isPending,children:yE.isPending?"Saving...":"Save Exclusions"})]}),s.jsx("div",{style:E.excludedItemsGrid,children:UD.map(j=>s.jsxs("label",{style:E.excludedItem,children:[s.jsx("input",{type:"checkbox",checked:Ln.has(j.name),onChange:()=>jX(j.name)}),s.jsx("span",{style:{flex:1},children:j.name})]},j.name))}),s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:Ln.size>0?"#fef3c7":"#e8f4fd",borderRadius:"6px",textAlign:"center",fontWeight:500},children:[Ln.size," categories excluded from reports"]})]}):s.jsxs("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:["No menu categories found.",s.jsx("button",{onClick:()=>ZK(),style:{...E.actionBtn,marginLeft:"1rem"},children:"Retry"})]}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:"Configure your database connection above first."})]}),ps&&s.jsx("div",{style:{...E.statusMessage,background:ps.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:ps}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"GL Code Classification for Spend Analysis"}),s.jsx("p",{style:E.hint,children:'Fetch unique GL codes from "NewBook GLA" custom tags and classify them as food or beverage. Used to calculate average spend per cover and food/beverage split in the Bookings Stats Report.'}),FE?tX?s.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"#666"},children:"Loading GL codes..."}):WC&&WC.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{ll(new Set),Mc(new Set)},style:E.actionBtn,children:"Clear Selections"}),s.jsx("button",{onClick:AX,style:E.saveBtn,disabled:xE.isPending,children:xE.isPending?"Saving...":"Save GL Codes"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2rem",marginTop:"1.5rem"},children:[s.jsxs("div",{children:[s.jsxs("h4",{style:{marginBottom:"1rem",color:"#374151",fontSize:"1rem"},children:["Food GL Codes (",Zr.size," selected)"]}),s.jsx("div",{style:{...E.excludedItemsGrid,maxHeight:"400px",overflowY:"auto",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"0.75rem"},children:WC.map(j=>s.jsxs("label",{style:E.excludedItem,children:[s.jsx("input",{type:"checkbox",checked:Zr.has(j.code),onChange:()=>_X(j.code),disabled:Wo.has(j.code)}),s.jsx("span",{style:{flex:1,color:Wo.has(j.code)?"#999":"#000"},children:j.code})]},j.code))})]}),s.jsxs("div",{children:[s.jsxs("h4",{style:{marginBottom:"1rem",color:"#374151",fontSize:"1rem"},children:["Beverage GL Codes (",Wo.size," selected)"]}),s.jsx("div",{style:{...E.excludedItemsGrid,maxHeight:"400px",overflowY:"auto",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"0.75rem"},children:WC.map(j=>s.jsxs("label",{style:E.excludedItem,children:[s.jsx("input",{type:"checkbox",checked:Wo.has(j.code),onChange:()=>CX(j.code),disabled:Zr.has(j.code)}),s.jsx("span",{style:{flex:1,color:Zr.has(j.code)?"#999":"#000"},children:j.code})]},j.code))})]})]}),s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:Zr.size>0||Wo.size>0?"#dcfce7":"#e8f4fd",borderRadius:"6px",textAlign:"center",fontWeight:500},children:[Zr.size," food codes, ",Wo.size," beverage codes selected"]})]}):s.jsxs("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:["No GL codes found in ProductTag custom tags.",s.jsx("button",{onClick:()=>eX(),style:{...E.actionBtn,marginLeft:"1rem"},children:"Retry"})]}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:"Configure your database connection above first."})]}),H0&&s.jsx("div",{style:{...E.statusMessage,background:H0.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:H0})]}),o==="kds"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Kitchen Display System Settings"}),s.jsx("p",{style:E.hint,children:"Configure the KDS to display orders from SambaPOS GraphQL API for kitchen staff."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"SambaPOS GraphQL Connection"}),s.jsx("p",{style:E.blockHint,children:"Connect to SambaPOS Message Server to fetch kitchen orders in real-time."}),s.jsxs("label",{style:E.label,children:["GraphQL URL",s.jsx("input",{type:"text",value:q0,onChange:j=>A1(j.target.value),style:E.input,placeholder:"http://localhost:9000"})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:V0,onChange:j=>_e(j.target.value),style:E.input,placeholder:"Admin"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:T1,onChange:j=>G0(j.target.value),style:E.input,placeholder:td!=null&&td.kds_graphql_password_set?"••••••••":"Enter password"})]}),s.jsxs("label",{style:E.label,children:["Client ID (Application Key)",s.jsx("input",{type:"text",value:Mf,onChange:j=>Yt(j.target.value),style:E.input,placeholder:"graphiql"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>bE.mutate(),style:E.testBtn,disabled:bE.isPending||!q0,children:bE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:TX,style:E.saveBtn,disabled:ax.isPending,children:ax.isPending?"Saving...":"Save Connection"})]}),E1&&s.jsx("div",{style:{...E.statusMessage,background:E1.startsWith("Error")?"#fee":"#efe"},children:E1})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Display Settings"}),s.jsx("p",{style:E.blockHint,children:"Configure how tickets and timers are displayed on the KDS screen."}),s.jsxs("label",{style:E.label,children:["Poll Interval (seconds)",s.jsx("input",{type:"number",value:zc,onChange:j=>Vu(parseInt(j.target.value)||5),style:E.input,min:"1",max:"60"})]}),s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem"},children:"Courses & Timer Thresholds"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},children:"Define courses in order. Each course has its own prep (time since called away) and away (time since food sent) timer thresholds in minutes."}),Li.map((j,V)=>s.jsxs("div",{style:{border:"1px solid #ddd",borderRadius:"6px",padding:"0.75rem",marginBottom:"0.5rem",background:"#fafafa"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem"},children:[s.jsx("button",{onClick:()=>F8(V,-1),disabled:V===0,style:{...E.smallBtn,opacity:V===0?.3:1},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>F8(V,1),disabled:V===Li.length-1,style:{...E.smallBtn,opacity:V===Li.length-1?.3:1},title:"Move down",children:"▼"}),s.jsx("input",{type:"text",value:j.name,onChange:Pe=>em(V,"name",Pe.target.value),style:{...E.input,flex:1,marginBottom:0},placeholder:"Course name"}),s.jsx("button",{onClick:()=>PX(V),style:{...E.smallBtn,color:"#e94560",borderColor:"#e94560"},title:"Remove course",children:"✕"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"60px 1fr 1fr 1fr",gap:"0.4rem",alignItems:"center",fontSize:"0.85rem"},children:[s.jsx("span",{style:{fontWeight:"bold"},children:"Prep"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#27ae60",fontSize:"0.8rem"},children:"Green"}),s.jsx("input",{type:"number",value:j.prep_green,onChange:Pe=>em(V,"prep_green",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#f39c12",fontSize:"0.8rem"},children:"Amber"}),s.jsx("input",{type:"number",value:j.prep_amber,onChange:Pe=>em(V,"prep_amber",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#e94560",fontSize:"0.8rem"},children:"Red"}),s.jsx("input",{type:"number",value:j.prep_red,onChange:Pe=>em(V,"prep_red",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"60px 1fr 1fr 1fr",gap:"0.4rem",alignItems:"center",fontSize:"0.85rem",marginTop:"0.3rem"},children:[s.jsx("span",{style:{fontWeight:"bold"},children:"Away"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#27ae60",fontSize:"0.8rem"},children:"Green"}),s.jsx("input",{type:"number",value:j.away_green,onChange:Pe=>em(V,"away_green",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#f39c12",fontSize:"0.8rem"},children:"Amber"}),s.jsx("input",{type:"number",value:j.away_amber,onChange:Pe=>em(V,"away_amber",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#e94560",fontSize:"0.8rem"},children:"Red"}),s.jsx("input",{type:"number",value:j.away_red,onChange:Pe=>em(V,"away_red",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]})]})]},V)),s.jsx("button",{onClick:RX,style:{...E.saveBtn,background:"#3498db",marginBottom:"1rem"},children:"+ Add Course"}),s.jsxs("label",{style:E.label,children:["Show Completed Tickets For (seconds)",s.jsx("input",{type:"number",value:ui,onChange:j=>la(parseInt(j.target.value)||30),style:E.input,min:"0",max:"300"})]}),s.jsxs("label",{style:E.label,children:["Bookings Refresh Interval (seconds)",s.jsx("input",{type:"number",value:F1,onChange:j=>D1(parseInt(j.target.value)||60),style:E.input,min:"10",max:"600"})]}),s.jsx("div",{style:E.buttonRow,children:s.jsx("button",{onClick:FX,style:E.saveBtn,disabled:ax.isPending,children:ax.isPending?"Saving...":"Save Display Settings"})}),Oc&&s.jsx("div",{style:{...E.statusMessage,background:Oc.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:Oc})]})]}),o==="budget"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Spend Budget Settings"}),s.jsx("p",{style:E.hint,children:"Configure integration with the forecasting app to calculate spending budgets based on forecast revenue and GP targets."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Forecast API Connection"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Forecast API URL",s.jsx("input",{type:"text",value:I1,onChange:j=>vC(j.target.value),style:E.input,placeholder:"http://forecast-app:8000"})]}),s.jsxs("label",{style:E.label,children:["API Key",s.jsx("input",{type:"password",value:M1,onChange:j=>z1(j.target.value),style:E.input,placeholder:Jd!=null&&Jd.forecast_api_configured?"••••••••":"Enter API key"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>SE.mutate(),style:E.testBtn,disabled:SE.isPending||!(Jd!=null&&Jd.forecast_api_configured),children:SE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:EX,style:E.saveBtn,disabled:wE.isPending,children:wE.isPending?"Saving...":"Save Settings"})]}),Q0&&s.jsx("div",{style:{...E.statusMessage,background:Q0.startsWith("Error")?"#fee":"#efe"},children:Q0})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Budget Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["GP Target (%)",s.jsx("input",{type:"number",min:"0",max:"100",step:"0.5",value:wC,onChange:j=>SC(j.target.value),style:{...E.input,width:"120px"}}),s.jsx("span",{style:E.fieldHint,children:"Budget = Forecast Revenue × (100 - GP%)"})]}),s.jsxs("label",{style:E.label,children:["Lookback Period (weeks)",s.jsxs("select",{value:jC,onChange:j=>O1(parseInt(j.target.value)),style:{...E.input,width:"120px"},children:[s.jsx("option",{value:2,children:"2 weeks"}),s.jsx("option",{value:4,children:"4 weeks"}),s.jsx("option",{value:6,children:"6 weeks"}),s.jsx("option",{value:8,children:"8 weeks"})]}),s.jsx("span",{style:E.fieldHint,children:"Used to calculate historical supplier spend percentages"})]})]})]}),N1&&s.jsx("div",{style:{...E.statusMessage,background:N1.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:N1}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Cost Distribution"}),s.jsx("p",{style:{marginBottom:"1rem",color:"#666"},children:"Configure how far into the future invoice costs can be spread when using the cost distribution feature on the Budget page."}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Maximum Days Into Future",s.jsx("input",{type:"number",min:"7",max:"365",value:S,onChange:j=>_(parseInt(j.target.value)||90),style:{...E.input,width:"120px"}}),s.jsx("span",{style:E.fieldHint,children:"Distributions cannot target dates beyond this many days from today (default: 90)"})]}),s.jsx("button",{onClick:()=>Jg.mutate({cost_distribution_max_days:S}),style:E.saveBtn,disabled:Jg.isPending,children:Jg.isPending?"Saving...":"Save"})]})]})]}),o==="kitchen"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Kitchen Details"}),s.jsx("p",{style:E.hint,children:"Your kitchen address and contact details appear on Purchase Order letterheads and emails sent to suppliers."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Business Details"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Display Name",s.jsx("input",{type:"text",value:fC,onChange:j=>Yd(j.target.value),style:E.input,placeholder:"e.g., Number Four at Stow"}),s.jsx("span",{style:E.fieldHint,children:"Name shown on PO letterhead (defaults to kitchen name if blank)"})]}),s.jsxs("label",{style:E.label,children:["Address Line 1",s.jsx("input",{type:"text",value:Ni,onChange:j=>K0(j.target.value),style:E.input,placeholder:"e.g., 4 The Square"})]}),s.jsxs("label",{style:E.label,children:["Address Line 2",s.jsx("input",{type:"text",value:Gu,onChange:j=>pC(j.target.value),style:E.input,placeholder:"e.g., Stow-on-the-Wold"})]}),s.jsxs("div",{style:{display:"flex",gap:"1rem"},children:[s.jsxs("label",{style:{...E.label,flex:2},children:["City / Town",s.jsx("input",{type:"text",value:Jl,onChange:j=>gC(j.target.value),style:E.input,placeholder:"e.g., Cheltenham"})]}),s.jsxs("label",{style:{...E.label,flex:1},children:["Postcode",s.jsx("input",{type:"text",value:mC,onChange:j=>yC(j.target.value),style:E.input,placeholder:"e.g., GL54 1BQ"})]})]}),s.jsxs("label",{style:E.label,children:["Phone",s.jsx("input",{type:"tel",value:X0,onChange:j=>Y0(j.target.value),style:E.input,placeholder:"e.g., 01451 830297"})]}),s.jsxs("label",{style:E.label,children:["Email",s.jsx("input",{type:"email",value:xC,onChange:j=>bC(j.target.value),style:E.input,placeholder:"e.g., kitchen@example.com"})]}),s.jsx("div",{style:E.buttonRow,children:s.jsx("button",{onClick:DX,style:E.saveBtn,disabled:vE.isPending,children:vE.isPending?"Saving...":"Save Details"})}),R1&&s.jsx("div",{style:{...E.statusMessage,background:R1.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:R1})]})]})]}),o==="suppliers"&&s.jsx("div",{style:E.section,children:s.jsx(DJ,{})}),o==="nextcloud"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Nextcloud File Storage"}),s.jsx("p",{style:E.hint,children:"Archive confirmed invoices to Nextcloud to reduce local storage. Files are organized by supplier, year, and month."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Nextcloud Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:H1,onChange:j=>TC(j.target.checked)}),"Enable Nextcloud archival"]}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:Z0,onChange:j=>J0(j.target.checked),disabled:!H1}),"Delete local files after successful archive"]}),s.jsx("p",{style:{...E.hint,marginLeft:"1.5rem",marginTop:"-0.5rem",marginBottom:"1rem"},children:"Frees up Docker storage after files are safely archived to Nextcloud"}),s.jsxs("label",{style:E.label,children:["Nextcloud Host URL",s.jsx("input",{type:"text",value:kC,onChange:j=>U1(j.target.value),placeholder:"https://cloud.example.com",style:E.input})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:_C,onChange:j=>CC(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:$0,onChange:j=>pD(j.target.value),placeholder:ul!=null&&ul.nextcloud_password_set?"••••••••":"Enter password",style:E.input}),(ul==null?void 0:ul.nextcloud_password_set)&&s.jsx("span",{style:E.keyStatus,children:"Password is set"})]}),s.jsxs("label",{style:E.label,children:["Base Directory",s.jsx("input",{type:"text",value:ed,onChange:j=>AC(j.target.value),placeholder:"/Kitchen Invoices",style:E.input})]}),s.jsxs("p",{style:{...E.hint,marginTop:"0.5rem"},children:["Files organized as: ",ed||"/Kitchen Invoices","/Supplier/Year/Month/"]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{const j={nextcloud_host:kC,nextcloud_username:_C,nextcloud_base_path:ed,nextcloud_enabled:H1,nextcloud_delete_local:Z0};$0&&(j.nextcloud_password=$0),jE.mutate(j)},style:E.saveBtn,disabled:jE.isPending,children:jE.isPending?"Saving...":"Save Settings"}),s.jsx("button",{onClick:()=>kE.mutate(),style:E.testBtn,disabled:kE.isPending,children:kE.isPending?"Testing...":"Test Connection"})]}),V1&&s.jsx("div",{style:{...E.statusMessage,background:V1.startsWith("Error")?"#fee":"#efe"},children:V1}),ex&&s.jsx("div",{style:{...E.statusMessage,background:ex.startsWith("Error")?"#fee":"#efe"},children:ex})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Manual Archive"}),s.jsx("p",{style:E.hint,children:"Manually archive completed invoices that haven't been transferred to Nextcloud yet."}),qo&&s.jsxs("div",{style:E.dataActions,children:[s.jsx("div",{style:E.dataAction,children:s.jsxs("div",{children:[s.jsx("strong",{children:"Total local files:"})," ",qo.local_count," invoices",s.jsx("p",{style:E.actionDesc,children:"All invoices stored in Docker container"})]})}),s.jsx("div",{style:E.dataAction,children:s.jsxs("div",{children:[s.jsx("strong",{children:"Ready for archival:"})," ",qo.pending_count,s.jsx("p",{style:E.actionDesc,children:"Confirmed invoices that can be archived"})]})}),s.jsx("div",{style:E.dataAction,children:s.jsxs("div",{children:[s.jsx("strong",{children:"Already archived:"})," ",qo.archived_count," invoices"]})}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Archive All Pending"}),s.jsx("p",{style:E.actionDesc,children:"Transfer all eligible invoices to Nextcloud now"})]}),s.jsx("button",{onClick:()=>{confirm(`Archive ${qo.pending_count} invoices to Nextcloud?`)&&_E.mutate()},style:E.actionBtn,disabled:_E.isPending||qo.pending_count===0||!qo.nextcloud_configured,children:_E.isPending?"Archiving...":"Archive All"})]})]})]}),K1&&s.jsx("div",{style:{...E.statusMessage,background:K1.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:K1})]}),o==="search"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Search & Pricing"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Price Change Detection"}),s.jsx("p",{style:{marginBottom:"1rem",color:"#666"},children:"Configure how price changes are detected and flagged on invoices. When a line item's price differs from historical prices, it will be marked with a warning indicator."}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Lookback Period (days)",s.jsx("input",{type:"number",value:en,onChange:j=>rn(parseInt(j.target.value)||30),min:"1",max:"365",style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"How far back to check for price history (default: 30 days)"})]}),s.jsxs("label",{style:E.label,children:["Amber Warning Threshold (%)",s.jsx("input",{type:"number",value:Nn,onChange:j=>Qn(parseInt(j.target.value)||10),min:"1",max:"100",style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"Price changes above this % show amber warning (default: 10%)"})]}),s.jsxs("label",{style:E.label,children:["Red Warning Threshold (%)",s.jsx("input",{type:"number",value:gr,onChange:j=>br(parseInt(j.target.value)||20),min:"1",max:"100",style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"Price changes above this % show red warning (default: 20%)"})]}),s.jsx("button",{onClick:()=>{TE.mutate({price_change_lookback_days:en,price_change_amber_threshold:Nn,price_change_red_threshold:gr})},style:E.btn,disabled:TE.isPending,children:TE.isPending?"Saving...":"Save Settings"}),mr&&s.jsx("div",{style:{...E.statusMessage,background:mr.startsWith("Error")?"#fee":"#efe"},children:mr})]})]}),s.jsx("h3",{style:{...E.subsectionTitle,marginTop:"2rem"},children:"Price Status Legend"}),s.jsxs("div",{style:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{color:"#22c55e",fontWeight:"bold",fontSize:"1.2rem"},children:"✓"}),s.jsx("span",{children:"Price consistent (no significant change)"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{color:"#f59e0b",fontWeight:"bold",fontSize:"1.2rem"},children:"?"}),s.jsx("span",{children:"Small price change (amber threshold)"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{color:"#ef4444",fontWeight:"bold",fontSize:"1.2rem"},children:"!"}),s.jsx("span",{children:"Large price change (red threshold)"})]})]}),s.jsx("p",{style:{color:"#666",fontSize:"0.9rem"},children:"Click on a price status icon to view the full price history and acknowledge the change."})]}),o==="backup"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Backup & Restore"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Backup Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Frequency",s.jsxs("select",{value:Y1,onChange:j=>Q1(j.target.value),style:E.input,children:[s.jsx("option",{value:"manual",children:"Manual Only"}),s.jsx("option",{value:"daily",children:"Daily"}),s.jsx("option",{value:"weekly",children:"Weekly (Sundays)"})]})]}),s.jsxs("label",{style:E.label,children:["Time (for scheduled backups)",s.jsx("input",{type:"time",value:tx,onChange:j=>qn(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Retention (number of backups to keep)",s.jsx("input",{type:"number",min:"1",max:"100",value:Ku,onChange:j=>FC(parseInt(j.target.value)||7),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Destination",s.jsxs("select",{value:dl,onChange:j=>DC(j.target.value),style:E.input,children:[s.jsx("option",{value:"local",children:"Local Storage"}),s.jsx("option",{value:"nextcloud",children:"Nextcloud"}),s.jsx("option",{value:"smb",children:"SMB Network Share"})]})]}),dl==="nextcloud"&&s.jsxs(s.Fragment,{children:[!(qo!=null&&qo.nextcloud_configured)&&s.jsx("div",{style:{...E.statusMessage,background:"#fee",marginTop:"0.5rem"},children:"⚠️ Nextcloud is not configured. Please set up Nextcloud credentials in the Nextcloud Storage settings first."}),s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem"},children:"Nextcloud Backup Settings"}),s.jsxs("label",{style:E.label,children:["Backup Directory Path",s.jsx("input",{type:"text",value:Qd,onChange:j=>Nc(j.target.value),placeholder:"/Backups",style:E.input,disabled:!(qo!=null&&qo.nextcloud_configured)})]}),s.jsx("p",{style:E.hint,children:"Path on Nextcloud where backups will be stored (separate from invoice archives)"})]}),dl==="smb"&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem"},children:"SMB Network Share Settings"}),s.jsxs("label",{style:E.label,children:["SMB Host",s.jsx("input",{type:"text",value:Xu,onChange:j=>$1(j.target.value),placeholder:"192.168.1.100",style:E.input})]}),s.jsxs("label",{style:E.label,children:["Share Name",s.jsx("input",{type:"text",value:Yu,onChange:j=>Z1(j.target.value),placeholder:"backups",style:E.input})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:J1,onChange:j=>ew(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:nx,onChange:j=>EC(j.target.value),placeholder:Nr!=null&&Nr.backup_smb_password_set?"••••••••":"Enter password",style:E.input}),(Nr==null?void 0:Nr.backup_smb_password_set)&&s.jsx("span",{style:E.keyStatus,children:"Password is set"})]}),s.jsxs("label",{style:E.label,children:["Path on Share",s.jsx("input",{type:"text",value:tw,onChange:j=>B(j.target.value),placeholder:"/kitchen-backups",style:E.input})]})]}),s.jsx("div",{style:E.buttonRow,children:s.jsx("button",{onClick:()=>{const j={backup_frequency:Y1,backup_retention_count:Ku,backup_destination:dl,backup_time:tx};dl==="nextcloud"&&(j.backup_nextcloud_path=Qd),dl==="smb"&&(j.backup_smb_host=Xu,j.backup_smb_share=Yu,j.backup_smb_username=J1,j.backup_smb_path=tw,nx&&(j.backup_smb_password=nx)),CE.mutate(j)},style:E.saveBtn,disabled:CE.isPending||dl==="nextcloud"&&!(qo!=null&&qo.nextcloud_configured),children:CE.isPending?"Saving...":"Save Backup Settings"})}),oe&&s.jsx("div",{style:{...E.statusMessage,background:oe.startsWith("Error")?"#fee":"#efe"},children:oe})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Manual Backup"}),s.jsx("div",{style:E.dataActions,children:s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Last Backup:"})," ",Nr!=null&&Nr.backup_last_run_at?new Date(Nr.backup_last_run_at).toLocaleString():"Never",(Nr==null?void 0:Nr.backup_last_status)&&s.jsx("span",{style:{marginLeft:"1rem",color:Nr.backup_last_status==="success"?"#28a745":"#dc3545"},children:Nr.backup_last_status==="success"?"Success":"Failed"}),(Nr==null?void 0:Nr.backup_last_error)&&s.jsx("p",{style:{...E.actionDesc,color:"#dc3545"},children:Nr.backup_last_error})]}),s.jsx("button",{onClick:()=>AE.mutate(),style:E.saveBtn,disabled:AE.isPending,children:AE.isPending?"Creating...":"Create Backup Now"})]})})]}),Ae&&s.jsx("div",{style:{...E.statusMessage,background:Ae.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:Ae}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Restore from File"}),s.jsx("div",{style:E.dataActions,children:s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Upload Backup File"}),s.jsx("p",{style:E.actionDesc,children:"Restore invoice files from a previously downloaded backup ZIP file. Only missing files will be restored (existing files are not overwritten)."})]}),s.jsx("input",{type:"file",accept:".zip",onChange:j=>{var Pe;const V=(Pe=j.target.files)==null?void 0:Pe[0];V&&(confirm("Restore from this backup file? Only missing files will be restored.")&&YC.mutate(V),j.target.value="")},style:{display:"none"},id:"backup-upload-input"}),s.jsx("label",{htmlFor:"backup-upload-input",style:{...E.saveBtn,cursor:YC.isPending?"not-allowed":"pointer",opacity:YC.isPending?.6:1,display:"inline-block"},children:YC.isPending?"Uploading...":"Upload & Restore"})]})})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Backup History"}),HD&&HD.length>0?s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:E.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:E.th,children:"Date"}),s.jsx("th",{style:E.th,children:"Type"}),s.jsx("th",{style:E.th,children:"Destination"}),s.jsx("th",{style:E.th,children:"Status"}),s.jsx("th",{style:E.th,children:"Size"}),s.jsx("th",{style:E.th,children:"Actions"})]})}),s.jsx("tbody",{children:HD.map(j=>s.jsxs("tr",{children:[s.jsx("td",{style:E.td,children:new Date(j.started_at).toLocaleString()}),s.jsx("td",{style:E.td,children:j.backup_type}),s.jsx("td",{style:E.td,children:j.destination}),s.jsx("td",{style:E.td,children:s.jsx("span",{style:{color:j.status==="success"?"#28a745":j.status==="running"?"#ffc107":"#dc3545"},children:j.status})}),s.jsx("td",{style:E.td,children:j.file_size_bytes?`${(j.file_size_bytes/1024/1024).toFixed(1)} MB`:"-"}),s.jsx("td",{style:E.td,children:s.jsxs("div",{style:E.actionButtons,children:[s.jsx("button",{onClick:()=>{window.open(`/api/backup/${j.id}/download?token=${e}`,"_blank")},style:E.actionBtn,disabled:j.status!=="success",title:"Download",children:"Download"}),s.jsx("button",{onClick:()=>{confirm("Restore from this backup? This will restore files that are missing locally.")&&_8.mutate(j.id)},style:E.actionBtn,disabled:j.status!=="success"||_8.isPending,title:"Restore",children:"Restore"}),s.jsx("button",{onClick:()=>{confirm("Delete this backup?")&&C8.mutate(j.id)},style:E.deleteBtn,disabled:C8.isPending,title:"Delete",children:"Delete"})]})})]},j.id))})]})}):s.jsx("p",{style:E.hint,children:"No backups yet. Create your first backup above."})]})]}),o==="food_flags"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Food Flags"}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[s.jsx("p",{style:{...E.hint,marginBottom:0},children:"Manage allergen and dietary flag categories and their individual flags."}),s.jsx("button",{onClick:async()=>{t8(!0),Hi(null);try{const j=await fetch("/api/food-flags/seed-defaults",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(V.created_flags===0&&V.created_categories===0?Hi("All default flags already exist."):Hi(`Loaded ${V.created_flags} flags in ${V.created_categories} categories + ${V.seeded_keywords} keywords.`),i.invalidateQueries({queryKey:["food-flag-categories"]}),i.invalidateQueries({queryKey:["allergen-keywords"]})):Hi(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{Hi("Error: Network error")}t8(!1)},disabled:BC,style:{padding:"0.4rem 0.75rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:BC?"wait":"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap",opacity:BC?.6:1},children:BC?"Loading...":"Load UK 14 Defaults"})]}),vD&&s.jsx("div",{style:{...E.statusMessage,background:vD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:vD}),b8&&b8.map(j=>s.jsxs("div",{style:E.settingsBlock,children:[dw===j.id?s.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap",marginBottom:"1rem"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"200px"},children:["Category Name",s.jsx("input",{type:"text",value:cw,onChange:V=>uw(V.target.value),style:E.input})]}),s.jsxs("label",{style:{...E.label,minWidth:"160px"},children:["Propagation Type",s.jsxs("select",{value:Yg,onChange:V=>ix(V.target.value),style:E.input,children:[s.jsx("option",{value:"contains",children:"Contains (allergens)"}),s.jsx("option",{value:"suitable_for",children:"Suitable For (dietary)"})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>XD.mutate({id:j.id,data:{name:cw,propagation_type:Yg}}),style:E.saveBtn,disabled:XD.isPending,children:"Save"}),s.jsx("button",{onClick:()=>Xg(null),style:E.actionBtn,children:"Cancel"})]})]}):s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[s.jsxs("div",{children:[s.jsx("h3",{style:{...E.blockTitle,marginBottom:"0.25rem"},children:j.name}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:"0.8rem",color:"#666",background:j.propagation_type==="contains"?"#fff3cd":"#d4edda",padding:"0.15rem 0.5rem",borderRadius:"4px"},children:j.propagation_type==="contains"?"Contains (allergen)":"Suitable For (dietary)"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"0.8rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:j.required,onChange:()=>XD.mutate({id:j.id,data:{required:!j.required}}),style:{margin:0}}),"Required"]})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>{Xg(j.id),uw(j.name),ix(j.propagation_type)},style:E.smallBtn,title:"Edit category",children:"✎"}),s.jsx("button",{onClick:()=>{confirm(`Delete category "${j.name}" and all its flags?`)&&nX.mutate(j.id)},style:{...E.smallBtn,color:"#dc3545"},title:"Delete category",children:"✕"})]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[j.flags.map(V=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:gD===V.id?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:pw,onChange:Pe=>X3(Pe.target.value),style:{...E.input,flex:2},placeholder:"Name"}),s.jsx("input",{type:"text",value:Y3,onChange:Pe=>Q3(Pe.target.value),style:{...E.input,flex:1},placeholder:"Code"}),s.jsx("input",{type:"text",value:$3,onChange:Pe=>Z3(Pe.target.value),style:{...E.input,flex:1},placeholder:"Icon"}),s.jsx("button",{onClick:()=>w8.mutate({id:V.id,data:{name:pw,code:Y3||void 0,icon:$3||void 0}}),style:E.saveBtn,disabled:w8.isPending,children:"Save"}),s.jsx("button",{onClick:()=>Nf(null),style:E.actionBtn,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[V.icon&&s.jsx("span",{style:{fontSize:"1.2rem"},children:V.icon}),s.jsx("span",{style:{flex:2,fontWeight:"500"},children:V.name}),s.jsx("span",{style:{flex:1,color:"#666",fontSize:"0.85rem"},children:V.code||"-"}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[s.jsx("button",{onClick:()=>{Nf(V.id),X3(V.name),Q3(V.code||""),Z3(V.icon||"")},style:E.smallBtn,title:"Edit flag",children:"✎"}),s.jsx("button",{onClick:()=>{confirm(`Delete flag "${V.name}"?`)&&rX.mutate(V.id)},style:{...E.smallBtn,color:"#dc3545"},title:"Delete flag",children:"✕"})]})]})},V.id)),HK===j.id?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"6px",border:"1px dashed #ccc"},children:[s.jsx("input",{type:"text",value:RC,onChange:V=>yD(V.target.value),style:{...E.input,flex:2},placeholder:"Flag name"}),s.jsx("input",{type:"text",value:J3,onChange:V=>xD(V.target.value),style:{...E.input,flex:1},placeholder:"Code (e.g. GF)"}),s.jsx("input",{type:"text",value:e8,onChange:V=>bD(V.target.value),style:{...E.input,flex:1},placeholder:"Icon (emoji)"}),s.jsx("button",{onClick:()=>{RC.trim()&&v8.mutate({category_id:j.id,name:RC.trim(),code:J3.trim()||void 0,icon:e8.trim()||void 0})},style:E.saveBtn,disabled:v8.isPending||!RC.trim(),children:"Add"}),s.jsx("button",{onClick:()=>{mD(null),yD(""),xD(""),bD("")},style:E.actionBtn,children:"Cancel"})]}):s.jsx("button",{onClick:()=>mD(j.id),style:{...E.secondaryButton,alignSelf:"flex-start",marginTop:"0.25rem"},children:"+ Add Flag"})]})]},j.id)),Qg?s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"New Category"}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"200px"},children:["Category Name",s.jsx("input",{type:"text",value:Lf,onChange:j=>hw(j.target.value),style:E.input,placeholder:"e.g., Allergens, Dietary Preferences"})]}),s.jsxs("label",{style:{...E.label,minWidth:"160px"},children:["Propagation Type",s.jsxs("select",{value:PC,onChange:j=>Zu(j.target.value),style:E.input,children:[s.jsx("option",{value:"contains",children:"Contains (allergens)"}),s.jsx("option",{value:"suitable_for",children:"Suitable For (dietary)"})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>{Lf.trim()&&KD.mutate({name:Lf.trim(),propagation_type:PC})},style:E.saveBtn,disabled:KD.isPending||!Lf.trim(),children:KD.isPending?"Creating...":"Create Category"}),s.jsx("button",{onClick:()=>{fw(!1),hw(""),Zu("contains")},style:E.actionBtn,children:"Cancel"})]})]}),s.jsxs("p",{style:{...E.hint,marginTop:"0.5rem",marginBottom:0},children:[s.jsx("strong",{children:"Contains"}),': Flag propagates if ANY ingredient has it (e.g., "Contains Nuts").',s.jsx("br",{}),s.jsx("strong",{children:"Suitable For"}),': Flag propagates only if ALL ingredients have it (e.g., "Vegan").']})]}):s.jsx("button",{onClick:()=>fw(!0),style:{...E.button,marginTop:"0.5rem"},children:"+ Add Category"})]}),o==="allergen_keywords"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Allergen Keywords"}),s.jsx("p",{style:E.hint,children:"Manage ingredient name keywords that trigger allergen flag suggestions. When creating or editing ingredients, names and product ingredient lists are matched against these keywords to suggest relevant flags."}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"1rem"},children:s.jsx("button",{onClick:()=>{confirm("Reset all default keywords to their original values? Your custom-added keywords will be preserved.")&&ZD.mutate()},style:E.actionBtn,disabled:ZD.isPending,children:ZD.isPending?"Resetting...":"Reset to Defaults"})}),jD&&s.jsx("div",{style:{...E.statusMessage,background:jD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:jD}),YD&&YD.length>0?YD.map(j=>s.jsxs("div",{style:E.settingsBlock,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[s.jsxs("h3",{style:{...E.blockTitle,marginBottom:0},children:[j.flag_name,j.flag_code&&s.jsxs("span",{style:{color:"#888",fontWeight:400,marginLeft:"0.5rem"},children:["(",j.flag_code,")"]}),s.jsx("span",{style:{color:"#aaa",fontWeight:400,fontSize:"0.8rem",marginLeft:"0.5rem"},children:j.category_name})]}),qK===j.flag_id?s.jsxs("div",{style:{display:"flex",gap:"0.35rem",alignItems:"center"},children:[s.jsx("input",{type:"text",value:sx,onChange:V=>wD(V.target.value),style:{...E.input,width:"150px",padding:"0.3rem 0.5rem",fontSize:"0.8rem"},placeholder:"New keyword...",onKeyDown:V=>{V.key==="Enter"&&sx.trim()&&$D.mutate({food_flag_id:j.flag_id,keyword:sx.trim().toLowerCase()})},autoFocus:!0}),s.jsx("button",{onClick:()=>{sx.trim()&&$D.mutate({food_flag_id:j.flag_id,keyword:sx.trim().toLowerCase()})},style:E.saveBtn,disabled:!sx.trim()||$D.isPending,children:"Add"}),s.jsx("button",{onClick:()=>{SD(null),wD("")},style:E.actionBtn,children:"Cancel"})]}):s.jsx("button",{onClick:()=>SD(j.flag_id),style:E.secondaryButton,children:"+ Add"})]}),s.jsxs("div",{style:{display:"flex",gap:"0.3rem",flexWrap:"wrap"},children:[j.keywords.map(V=>s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.25rem",padding:"0.2rem 0.5rem",background:V.is_default?"#f0f0f0":"#e8f0fe",border:`1px solid ${V.is_default?"#ddd":"#90caf9"}`,borderRadius:"12px",fontSize:"0.78rem",color:"#555"},children:[V.keyword,s.jsx("button",{onClick:()=>iX.mutate(V.id),style:{background:"none",border:"none",cursor:"pointer",color:"#999",fontSize:"0.7rem",padding:"0 0.15rem",lineHeight:1},title:"Remove keyword",children:"✕"})]},V.id)),j.keywords.length===0&&s.jsx("span",{style:{fontSize:"0.8rem",color:"#aaa",fontStyle:"italic"},children:"No keywords"})]})]},j.flag_id)):s.jsx("p",{style:E.hint,children:"No allergen keywords configured. Keywords are seeded automatically when food flags are created."})]}),o==="ingredient_categories"&&s.jsxs("div",{style:E.section,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("h2",{style:E.sectionTitle,children:"Ingredient Categories"}),s.jsx("button",{onClick:async()=>{yo(null);try{const j=await fetch("/api/ingredients/categories/seed-defaults",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(V.created===0?yo("All default categories already exist."):yo(`Loaded ${V.created} default categories.`),qC()):yo(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{yo("Error: Network error")}},style:{padding:"0.4rem 0.75rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap"},children:"Load Defaults"})]}),s.jsx("p",{style:E.hint,children:"Manage ingredient groupings (e.g. Dairy, Meat, Produce). Categories help organise your ingredient library and can be used to filter the ingredients list."}),TD&&s.jsx("div",{style:{...E.statusMessage,background:TD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:TD}),Ps&&Ps.length>0?s.jsx("div",{style:E.settingsBlock,children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Order"}),s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Name"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Ingredients"}),s.jsx("th",{style:{textAlign:"right",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Actions"})]})}),s.jsx("tbody",{children:Ps.map((j,V)=>s.jsx("tr",{style:{borderBottom:"1px solid #eee"},children:VK===j.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem"},children:s.jsx("input",{type:"number",value:i8,onChange:Pe=>s8(parseInt(Pe.target.value)||0),style:{...E.input,width:"60px",marginBottom:0}})}),s.jsx("td",{style:{padding:"0.5rem 0.75rem"},children:s.jsx("input",{type:"text",value:n8,onChange:Pe=>r8(Pe.target.value),style:{...E.input,marginBottom:0}})}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.ingredient_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>VC.mutate({id:j.id,data:{name:n8,sort_order:i8}}),style:E.saveBtn,disabled:VC.isPending,children:"Save"}),s.jsx("button",{onClick:()=>kD(null),style:E.actionBtn,children:"Cancel"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem"},children:s.jsxs("div",{style:{display:"flex",gap:"0.25rem",alignItems:"center"},children:[s.jsx("button",{onClick:()=>S8(j.id,"up"),disabled:V===0,style:{background:"none",border:"none",cursor:V===0?"default":"pointer",opacity:V===0?.3:1,fontSize:"1rem",padding:"0 2px"},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>S8(j.id,"down"),disabled:V===Ps.length-1,style:{background:"none",border:"none",cursor:V===Ps.length-1?"default":"pointer",opacity:V===Ps.length-1?.3:1,fontSize:"1rem",padding:"0 2px"},title:"Move down",children:"▼"})]})}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",fontWeight:500},children:j.name}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.ingredient_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>{kD(j.id),r8(j.name),s8(j.sort_order)},style:E.smallBtn,title:"Edit",children:"✎"}),s.jsx("button",{onClick:()=>{confirm(`Delete "${j.name}"?${j.ingredient_count>0?` ${j.ingredient_count} ingredient(s) will become uncategorised.`:""}`)&&sX.mutate(j.id)},style:{...E.smallBtn,color:"#dc3545"},title:"Delete",children:"✕"})]})})]})},j.id))})]})}):s.jsx("p",{style:E.hint,children:"No ingredient categories yet. Create your first category below."}),GK?s.jsxs("div",{style:{...E.settingsBlock,marginTop:"1rem"},children:[s.jsx("h3",{style:E.blockTitle,children:"New Category"}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"200px"},children:["Name",s.jsx("input",{type:"text",value:_D,onChange:j=>CD(j.target.value),placeholder:"e.g. Dairy, Produce, Proteins...",style:E.input})]}),s.jsxs("label",{style:{...E.label,minWidth:"80px"},children:["Sort Order",s.jsx("input",{type:"number",value:o8,onChange:j=>IC(parseInt(j.target.value)||0),style:{...E.input,width:"80px"}})]}),s.jsx("button",{onClick:()=>JD.mutate({name:_D.trim(),sort_order:o8}),style:E.saveBtn,disabled:!_D.trim()||JD.isPending,children:JD.isPending?"Creating...":"Create"}),s.jsx("button",{onClick:()=>{AD(!1),CD(""),IC(0)},style:E.actionBtn,children:"Cancel"})]})]}):s.jsx("button",{onClick:()=>{AD(!0),IC((Ps==null?void 0:Ps.length)||0)},style:{...E.button,marginTop:"0.5rem"},children:"+ Add Category"})]}),o==="recipe_sections"&&s.jsxs("div",{style:E.section,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("h2",{style:E.sectionTitle,children:"Recipe Sections"}),s.jsx("button",{onClick:async()=>{MC(null);try{const j=await fetch("/api/recipes/menu-sections/seed-defaults?section_type=recipe",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(MC(V.created===0?"All default sections already exist.":`Loaded ${V.created} default sections.`),GC()):MC(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{MC("Error: Network error")}},style:{padding:"0.4rem 0.75rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap"},children:"Load Defaults"})]}),s.jsx("p",{style:E.hint,children:"Recipe sections group component recipes (e.g. Sauces & Jus, Meats & Protein). Used to organise recipes in the recipe list."}),FD&&s.jsx("div",{style:{...E.statusMessage,background:FD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:FD}),th&&th.length>0?s.jsx("div",{style:E.settingsBlock,children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Name"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Recipes"}),s.jsx("th",{style:{textAlign:"right",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Actions"})]})}),s.jsx("tbody",{children:th.map(j=>s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem",fontWeight:500},children:j.name}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.recipe_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsx("button",{onClick:async()=>{confirm(`Delete "${j.name}"?${j.recipe_count>0?` ${j.recipe_count} recipe(s) will become unsectioned.`:""}`)&&(await fetch(`/api/recipes/menu-sections/${j.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})).ok&&GC()},style:{...E.smallBtn,color:"#dc3545"},title:"Delete",children:"✕"})})]},j.id))})]})}):s.jsx("p",{style:E.hint,children:'No recipe sections yet. Click "Load Defaults" or add one below.'}),s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"0.5rem",alignItems:"flex-end"},children:[s.jsx("input",{type:"text",placeholder:"New section name...",id:"newRecipeSectionName",style:{...E.input,marginBottom:0,flex:1,maxWidth:"300px"},onKeyDown:async j=>{if(j.key==="Enter"){const V=j.currentTarget,Pe=V.value.trim();if(!Pe)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:Pe,section_type:"recipe",sort_order:(th==null?void 0:th.length)||0})})).ok&&(V.value="",GC())}}}),s.jsx("button",{onClick:async()=>{const j=document.getElementById("newRecipeSectionName"),V=j==null?void 0:j.value.trim();if(!V)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:V,section_type:"recipe",sort_order:(th==null?void 0:th.length)||0})})).ok&&(j.value="",GC())},style:E.saveBtn,children:"Add"})]})]}),o==="dish_courses"&&s.jsxs("div",{style:E.section,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("h2",{style:E.sectionTitle,children:"Dish Courses"}),s.jsx("button",{onClick:async()=>{zC(null);try{const j=await fetch("/api/recipes/menu-sections/seed-defaults?section_type=dish",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(zC(V.created===0?"All default courses already exist.":`Loaded ${V.created} default courses.`),KC()):zC(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{zC("Error: Network error")}},style:{padding:"0.4rem 0.75rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap"},children:"Load Defaults"})]}),s.jsx("p",{style:E.hint,children:"Dish courses categorise menu items (e.g. Starter, Main, Dessert). Used to organise dishes in the dish list."}),DD&&s.jsx("div",{style:{...E.statusMessage,background:DD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:DD}),nh&&nh.length>0?s.jsx("div",{style:E.settingsBlock,children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Name"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Dishes"}),s.jsx("th",{style:{textAlign:"right",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Actions"})]})}),s.jsx("tbody",{children:nh.map(j=>s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem",fontWeight:500},children:j.name}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.recipe_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsx("button",{onClick:async()=>{confirm(`Delete "${j.name}"?${j.recipe_count>0?` ${j.recipe_count} dish(es) will become uncategorised.`:""}`)&&(await fetch(`/api/recipes/menu-sections/${j.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})).ok&&KC()},style:{...E.smallBtn,color:"#dc3545"},title:"Delete",children:"✕"})})]},j.id))})]})}):s.jsx("p",{style:E.hint,children:'No dish courses yet. Click "Load Defaults" or add one below.'}),s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"0.5rem",alignItems:"flex-end"},children:[s.jsx("input",{type:"text",placeholder:"New course name...",id:"newDishCourseName",style:{...E.input,marginBottom:0,flex:1,maxWidth:"300px"},onKeyDown:async j=>{if(j.key==="Enter"){const V=j.currentTarget,Pe=V.value.trim();if(!Pe)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:Pe,section_type:"dish",sort_order:(nh==null?void 0:nh.length)||0})})).ok&&(V.value="",KC())}}}),s.jsx("button",{onClick:async()=>{const j=document.getElementById("newDishCourseName"),V=j==null?void 0:j.value.trim();if(!V)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:V,section_type:"dish",sort_order:(nh==null?void 0:nh.length)||0})})).ok&&(j.value="",KC())},style:E.saveBtn,children:"Add"})]})]}),o==="api_access"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"API Access"}),s.jsxs("p",{style:E.hint,children:["Manage API key access for external applications such as menu display plugins. External apps authenticate using the ",s.jsx("code",{children:"X-API-Key"})," header."]}),RD&&s.jsx("div",{style:{...E.statusMessage,background:RD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:RD}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Key Settings"}),s.jsxs("label",{style:{...E.checkboxLabel,marginTop:0,marginBottom:"1.5rem"},children:[s.jsx("input",{type:"checkbox",checked:a8,onChange:j=>{ED(j.target.checked),oX.mutate({api_key_enabled:j.target.checked})}}),s.jsx("span",{children:"Enable API Access"})]}),s.jsxs("label",{style:E.label,children:["Current API Key",s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("input",{type:"text",readOnly:!0,value:$d?OC?$d:$d.substring(0,8)+"..."+$d.substring($d.length-4):"No API key generated",style:{...E.input,flex:1,fontFamily:"monospace",background:"#f8f9fa",color:$d?"#333":"#999"}}),$d&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>l8(!OC),style:E.smallBtn,title:OC?"Hide key":"Reveal key",children:OC?"👁":"🔒"}),s.jsx("button",{onClick:()=>{$d&&(navigator.clipboard.writeText($d),Wf("API key copied to clipboard"),setTimeout(()=>Wf(null),3e3))},style:E.smallBtn,title:"Copy to clipboard",children:"📋"})]})]}),s.jsx("span",{style:E.fieldHint,children:a8?"API access is enabled. External apps can use this key to access recipe and food flag data.":"API access is disabled. Enable it above to allow external apps to connect."})]}),s.jsx("div",{style:{...E.buttonRow,marginTop:"1rem"},children:s.jsx("button",{onClick:()=>{$d?confirm("Regenerate API key? The old key will stop working immediately.")&&XC.mutate():XC.mutate()},style:E.saveBtn,disabled:XC.isPending,children:XC.isPending?"Generating...":$d?"Regenerate API Key":"Generate API Key"})})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Usage"}),s.jsx("p",{style:{...E.hint,marginBottom:"0.5rem"},children:"External applications can access the following endpoints using the API key:"}),s.jsxs("div",{style:{fontFamily:"monospace",fontSize:"0.85rem",background:"white",padding:"0.75rem",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{marginBottom:"0.25rem"},children:[s.jsx("strong",{children:"GET"})," /api/external/recipes/dishes"]}),s.jsxs("div",{style:{marginBottom:"0.25rem"},children:[s.jsx("strong",{children:"GET"})," /api/external/recipes/:id"]}),s.jsxs("div",{children:[s.jsx("strong",{children:"GET"})," /api/external/food-flags"]})]}),s.jsxs("p",{style:{...E.hint,marginTop:"0.75rem",marginBottom:0},children:["Include the header ",s.jsx("code",{style:{background:"#f0f0f5",padding:"0.1rem 0.3rem",borderRadius:"3px"},children:"X-API-Key: your-key-here"})," with every request."]})]})]}),o==="llm"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"AI Features (Claude)"}),s.jsx("p",{style:E.hint,children:"Configure Anthropic Claude integration for allergen detection, ingredient matching, and more."}),zD&&s.jsx("div",{style:{...E.statusMessage,background:zD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:zD}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Master Switch"}),s.jsxs("label",{style:{...E.checkboxLabel,marginTop:0},children:[s.jsx("input",{type:"checkbox",checked:mw,onChange:j=>d8(j.target.checked)}),s.jsx("span",{children:"Enable AI Features"})]}),s.jsx("p",{style:{...E.hint,marginTop:"0.5rem",marginBottom:0},children:mw?"AI features are active. Allergen analysis, smart matching, and other AI tools will appear throughout the app.":"All AI features are hidden. No API calls are made, and no AI elements are shown anywhere in the app."})]}),mw&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Anthropic API Key",s.jsx("input",{type:"password",value:LC,onChange:j=>c8(j.target.value),style:E.input,placeholder:Lt!=null&&Lt.anthropic_api_key_set?"••••••••••••••••":"Enter your Anthropic API key"}),(Lt==null?void 0:Lt.anthropic_api_key_set)&&!LC&&s.jsx("span",{style:E.keyStatus,children:"Key is configured"}),s.jsx("span",{style:E.fieldHint,children:"Get your key from console.anthropic.com. Stored securely in your database."})]}),s.jsxs("div",{style:E.label,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{children:"Model"}),s.jsx("button",{type:"button",onClick:()=>dX(),disabled:j8,style:{background:"none",border:"1px solid #ccc",borderRadius:"4px",padding:"0.15rem 0.5rem",fontSize:"0.75rem",cursor:"pointer",color:"#666"},children:j8?"Fetching...":"Refresh Models"})]}),Uf&&Uf.models.length>0?s.jsx("select",{value:BD,onChange:j=>ID(j.target.value),style:E.input,children:Uf.models.map(j=>s.jsxs("option",{value:j.id,children:[j.display_name,j.id===Uf.default?" (default)":""]},j.id))}):s.jsx("input",{type:"text",value:BD,onChange:j=>ID(j.target.value),style:E.input,placeholder:lX?"Loading models...":"e.g. claude-haiku-4-5-20251001"}),s.jsxs("span",{style:E.fieldHint,children:[Uf!=null&&Uf.models.length?`${Uf.models.length} models available.`:"Save your API key first to see available models."," ","Haiku is recommended — Sonnet costs ~10x more."]})]}),s.jsxs("label",{style:E.label,children:["Confidence Threshold",s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("input",{type:"range",min:"0.50",max:"0.99",step:"0.01",value:MD,onChange:j=>u8(parseFloat(j.target.value)),style:{flex:1}}),s.jsxs("span",{style:{fontFamily:"monospace",minWidth:"3.5rem"},children:[(MD*100).toFixed(0),"%"]})]}),s.jsx("span",{style:E.fieldHint,children:"Minimum confidence for AI suggestions to be shown. Lower = more suggestions, higher = more precise."})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Cost Controls"}),s.jsx("div",{style:E.form,children:s.jsxs("label",{style:E.label,children:["Monthly Token Budget",s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("input",{type:"number",value:$g,onChange:j=>h8(parseInt(j.target.value)||0),style:{...E.input,flex:1},min:"0",step:"50000"}),s.jsxs("span",{style:{fontFamily:"monospace",minWidth:"5rem",color:"#666",fontSize:"0.85rem"},children:["~$",($g/1e6*1.25).toFixed(2),"/mo"]})]}),s.jsx("span",{style:E.fieldHint,children:"Set to 0 to pause all AI features without removing the API key. 500,000 tokens ~= $0.63/month on Haiku."})]})}),ec&&(ec.total_calls>0||(Lt==null?void 0:Lt.anthropic_api_key_set))&&s.jsxs("div",{style:{marginTop:"1rem",background:"white",padding:"1rem",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[s.jsx("strong",{style:{fontSize:"0.9rem"},children:"This Month's Usage"}),s.jsx("button",{onClick:()=>aX(),style:{...E.smallBtn,width:"auto",padding:"0.2rem 0.5rem",fontSize:"0.75rem"},children:"Refresh"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"0.75rem"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:"API Calls"}),s.jsxs("div",{style:{fontWeight:"600"},children:[ec.successful_calls," / ",ec.total_calls]})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:"Tokens Used"}),s.jsx("div",{style:{fontWeight:"600"},children:ec.total_tokens.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:"Est. Cost"}),s.jsxs("div",{style:{fontWeight:"600"},children:["$",ec.estimated_cost_usd.toFixed(4)]})]})]}),$g>0&&s.jsxs("div",{style:{marginTop:"0.75rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"0.75rem",color:"#888",marginBottom:"0.25rem"},children:[s.jsx("span",{children:"Budget"}),s.jsxs("span",{children:[(ec.total_tokens/$g*100).toFixed(1),"%"]})]}),s.jsx("div",{style:{height:"6px",background:"#e9ecef",borderRadius:"3px",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${Math.min(100,ec.total_tokens/$g*100)}%`,background:ec.total_tokens/$g>.8?"#e94560":"#28a745",borderRadius:"3px",transition:"width 0.3s"}})})]}),ec.cache_entries_this_month>0&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#888",marginTop:"0.5rem"},children:[ec.cache_entries_this_month," cached results this month"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Feature Toggles"}),s.jsx("p",{style:{...E.hint,marginBottom:"0.75rem"},children:"Enable or disable individual AI features. Disabled features fall back to existing keyword/trigram matching."}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.25rem"},children:[{key:"label_parsing",label:"Label Allergen Parsing",desc:"Auto-analyse product ingredient labels"},{key:"recipe_scanning",label:"Recipe Text Scanning",desc:"Detect allergens in recipe text"},{key:"invoice_assist",label:"Invoice AI Assist",desc:"Smart OCR correction suggestions"},{key:"ingredient_match",label:"Ingredient Matching",desc:"AI-powered ingredient suggestions"},{key:"line_item_reconciliation",label:"Line Item Reconciliation",desc:"Match items from supplier history"},{key:"duplicate_detection",label:"Duplicate Detection",desc:"Find semantic duplicates"},{key:"menu_description",label:"Menu Descriptions",desc:"Generate dish descriptions"},{key:"dispute_email",label:"Dispute Email Drafting",desc:"Draft supplier dispute emails"},{key:"supplier_alias",label:"Supplier Alias Resolution",desc:"Match unknown vendor names"},{key:"yield_estimation",label:"Yield Estimation",desc:"Suggest ingredient yields"}].map(({key:j,label:V,desc:Pe})=>s.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem",cursor:"pointer",borderRadius:"4px"},children:[s.jsx("input",{type:"checkbox",checked:f8[j]??!0,onChange:St=>p8(yr=>({...yr,[j]:St.target.checked})),style:{marginTop:"0.15rem"}}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.9rem",fontWeight:500},children:V}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:Pe})]})]},j))})]})]}),s.jsxs("div",{style:E.buttonRow,children:[mw&&(Lt==null?void 0:Lt.anthropic_api_key_set)&&s.jsx("button",{onClick:()=>tE.mutate(),style:E.testBtn,disabled:tE.isPending,children:tE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:cX,style:E.saveBtn,disabled:eE.isPending,children:eE.isPending?"Saving...":"Save AI Settings"})]}),LD&&s.jsx("div",{style:{...E.statusMessage,background:LD.startsWith("Error")?"#fee":"#efe"},children:LD})]}),o==="data"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Data Management"}),s.jsx("p",{style:E.hint,children:"Tools for reprocessing invoices and fixing supplier matching issues."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Data Actions"}),s.jsxs("div",{style:E.dataActions,children:[s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Reprocess All Invoices"}),s.jsx("p",{style:E.actionDesc,children:"Re-run OCR processing on all non-confirmed invoices."})]}),s.jsx("button",{onClick:()=>{confirm("Reprocess all non-confirmed invoices?")&&iE.mutate()},style:E.actionBtn,disabled:iE.isPending,children:iE.isPending?"Reprocessing...":"Reprocess"})]}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Clear Fuzzy Matches"}),s.jsx("p",{style:E.actionDesc,children:"Clear all fuzzy supplier matches and re-run matching."})]}),s.jsx("button",{onClick:()=>{confirm("Clear all fuzzy supplier matches?")&&aE.mutate()},style:E.actionBtn,disabled:aE.isPending,children:aE.isPending?"Clearing...":"Clear Matches"})]}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Clear Cache & Reload"}),s.jsx("p",{style:E.actionDesc,children:"Clear all cached files, service worker data, and reload with fresh assets."})]}),s.jsx("button",{onClick:async()=>{var j;try{const V=await caches.keys();await Promise.all(V.map(St=>caches.delete(St)));const Pe=await((j=navigator.serviceWorker)==null?void 0:j.getRegistrations());Pe&&await Promise.all(Pe.map(St=>St.unregister())),i.clear(),window.location.reload()}catch{window.location.reload()}},style:E.actionBtn,children:"Clear & Reload"})]}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Cleanup False Price Changes"}),s.jsx("p",{style:E.actionDesc,children:"Remove recipe change log entries where old and new price are identical (e.g. £0.0086/g → £0.0086/g)."})]}),s.jsx("button",{onClick:()=>{confirm("Remove all false price change entries from recipe change logs?")&&sE.mutate()},style:E.actionBtn,disabled:sE.isPending,children:sE.isPending?"Cleaning...":"Cleanup"})]}),s.jsxs("div",{style:E.actionRow,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Backfill Invoice References"}),s.jsx("p",{style:E.actionDesc,children:"Link existing price change entries to their triggering invoice (for entries created before this feature was added)."})]}),s.jsx("button",{onClick:()=>{confirm("Scan price change entries and link them to triggering invoices?")&&oE.mutate()},style:E.actionBtn,disabled:oE.isPending,children:oE.isPending?"Backfilling...":"Backfill"})]})]})]}),ct&&s.jsx("div",{style:{...E.statusMessage,background:ct.startsWith("Error")?"#fee":"#efe"},children:ct})]})]}),Dr&&Zd&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Select GL Accounts for Revenue Tracking"}),s.jsx("div",{style:E.glList,children:(()=>{const j={};return Zd.forEach(Pe=>{const St=Pe.gl_group_name||"Ungrouped";j[St]||(j[St]=[]),j[St].push(Pe)}),Object.keys(j).sort().map(Pe=>{const St=j[Pe],yr=St.every(Vi=>Vi.is_tracked),dr=St.some(Vi=>Vi.is_tracked),xo=()=>{const Vi=!yr;mX.mutate(St.map(DE=>({id:DE.id,is_tracked:Vi})))};return s.jsxs("div",{style:E.glGroup,children:[s.jsxs("label",{style:E.glGroupHeader,children:[s.jsx("input",{type:"checkbox",checked:yr,ref:Vi=>{Vi&&(Vi.indeterminate=dr&&!yr)},onChange:xo,style:{marginRight:"0.5rem"}}),Pe,s.jsxs("span",{style:E.glGroupCount,children:["(",St.filter(Vi=>Vi.is_tracked).length,"/",St.length,")"]})]}),s.jsx("div",{style:E.glGroupItems,children:St.map(Vi=>s.jsxs("label",{style:E.glItem,children:[s.jsx("input",{type:"checkbox",checked:Vi.is_tracked,onChange:DE=>gX.mutate({id:Vi.id,is_tracked:DE.target.checked})}),s.jsx("span",{children:Vi.gl_name}),Vi.gl_code&&s.jsxs("span",{style:E.glCode,children:["(",Vi.gl_code,")"]})]},Vi.id))})]},Pe)})})()}),s.jsx("button",{onClick:()=>xr(!1),style:E.btn,children:"Close"})]})}),Ss&&cl&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Select Room Categories for Occupancy"}),s.jsx("p",{style:{color:"#666",fontSize:"0.9rem",marginBottom:"1rem"},children:"Select which room types to include in occupancy and guest calculations."}),s.jsx("div",{style:E.glList,children:cl.map(j=>s.jsxs("label",{style:E.glItem,children:[s.jsx("input",{type:"checkbox",checked:j.is_included,onChange:V=>{fE.mutate([{id:j.id,is_included:V.target.checked}])}}),s.jsx("span",{children:j.site_name}),s.jsxs("span",{style:E.glCode,children:["(",j.room_count," rooms)"]})]},j.id))}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{fE.mutate(cl.map(j=>({id:j.id,is_included:!0})))},style:E.actionBtn,children:"Select All"}),s.jsx("button",{onClick:()=>{fE.mutate(cl.map(j=>({id:j.id,is_included:!1})))},style:E.actionBtn,children:"Deselect All"}),s.jsx("button",{onClick:()=>rs(!1),style:E.btn,children:"Close"})]})]})}),Xs&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Fetch Historical Data"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["From Date",s.jsx("input",{type:"date",value:Ea,onChange:j=>zn(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["To Date",s.jsx("input",{type:"date",value:gi,onChange:j=>je(j.target.value),style:E.input})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>uE.mutate({date_from:Ea,date_to:gi}),style:E.saveBtn,disabled:!Ea||!gi||uE.isPending,children:uE.isPending?"Syncing...":"Sync"}),s.jsx("button",{onClick:()=>Jt(!1),style:E.btn,children:"Cancel"})]})]})]})})]})}const E={layout:{display:"flex",gap:"2rem",maxWidth:"1200px",margin:"0 auto"},sidebar:{width:"200px",flexShrink:0,background:"white",borderRadius:"12px",padding:"1rem",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",height:"fit-content",position:"sticky",top:"1rem"},sidebarTitle:{margin:"0 0 1rem 0",fontSize:"1.1rem",color:"#1a1a2e"},nav:{display:"flex",flexDirection:"column",gap:"0.25rem"},navItem:{padding:"0.75rem 1rem",border:"none",background:"transparent",textAlign:"left",cursor:"pointer",borderRadius:"6px",fontSize:"0.95rem",color:"#333"},navItemActive:{background:"#e94560",color:"white"},content:{flex:1,minWidth:0},section:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},sectionTitle:{color:"#1a1a2e",marginTop:0,marginBottom:"1rem"},subsectionTitle:{color:"#1a1a2e",marginTop:"1.5rem",marginBottom:"0.75rem",fontSize:"1rem"},hint:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},fieldHint:{color:"#888",fontSize:"0.8rem",fontWeight:"normal"},form:{display:"flex",flexDirection:"column",gap:"1rem",maxWidth:"500px"},infoGrid:{display:"grid",gap:"0.5rem"},label:{display:"flex",flexDirection:"column",gap:"0.5rem",color:"#333",fontWeight:"500"},input:{padding:"0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"1rem"},keyStatus:{fontSize:"0.8rem",color:"#5cb85c"},buttonRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap"},btn:{padding:"0.5rem 1rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},testBtn:{padding:"0.5rem 1rem",background:"#5bc0de",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},saveBtn:{padding:"0.5rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"500"},smallBtn:{width:"28px",height:"28px",background:"white",border:"1px solid #ccc",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.75rem",flexShrink:0},actionBtn:{padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},secondaryButton:{padding:"0.5rem 1rem",background:"#5bc0de",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},button:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"500",fontSize:"1rem"},statusMessage:{padding:"0.75rem",borderRadius:"6px",marginTop:"0.5rem"},checkboxLabel:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"1rem",cursor:"pointer"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"0.75rem",borderBottom:"2px solid #eee",color:"#666",fontSize:"0.85rem"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},disabledRow:{opacity:.6,background:"#f9f9f9"},activeStatus:{color:"#28a745",fontWeight:"500"},inactiveStatus:{color:"#dc3545",fontWeight:"500"},actionButtons:{display:"flex",gap:"0.5rem"},disableBtn:{padding:"0.35rem 0.75rem",background:"#ffc107",color:"#212529",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},enableBtn:{padding:"0.35rem 0.75rem",background:"#28a745",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},deleteBtn:{padding:"0.35rem 0.75rem",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},promoteBtn:{padding:"0.35rem 0.75rem",background:"#6f42c1",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},demoteBtn:{padding:"0.35rem 0.75rem",background:"#6c757d",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},checkboxGroup:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},youLabel:{color:"#666",fontSize:"0.85rem",fontStyle:"italic"},dataActions:{display:"flex",flexDirection:"column",gap:"1rem"},dataAction:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},actionDesc:{margin:"0.25rem 0 0 0",fontSize:"0.85rem",color:"#666"},loading:{padding:"2rem",textAlign:"center",color:"#666"},modal:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modalContent:{background:"white",padding:"1.5rem",borderRadius:"12px",maxWidth:"500px",width:"90%",maxHeight:"80vh",overflow:"auto"},glList:{display:"flex",flexDirection:"column",gap:"0.5rem",margin:"1rem 0",maxHeight:"300px",overflow:"auto"},glItem:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"#f8f9fa",borderRadius:"4px",cursor:"pointer"},glCode:{color:"#666",fontSize:"0.85rem"},glGroup:{marginBottom:"1.25rem"},glGroupHeader:{display:"flex",alignItems:"center",fontWeight:"bold",fontSize:"0.95rem",color:"#1a1a2e",padding:"0.5rem 0.75rem",background:"#f0f0f5",borderLeft:"3px solid #e94560",marginBottom:"0.5rem",cursor:"pointer"},glGroupItems:{paddingLeft:"1.25rem",borderLeft:"1px solid #e0e0e0",marginLeft:"0.5rem"},glGroupCount:{marginLeft:"auto",fontSize:"0.8rem",color:"#666",fontWeight:"normal"},mealMappingList:{display:"flex",flexDirection:"column",gap:"0.25rem",maxHeight:"150px",overflow:"auto",padding:"0.5rem",background:"#f8f9fa",borderRadius:"6px",marginTop:"0.5rem"},mealMappingItem:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem",cursor:"pointer"},mealMappingEmpty:{color:"#999",fontSize:"0.85rem",fontStyle:"italic"},sambaCategoryGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(180px, 1fr))",gap:"0.5rem",marginTop:"1rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",maxHeight:"300px",overflowY:"auto"},sortableList:{display:"flex",flexDirection:"column",gap:"0.25rem",background:"#f8f9fa",borderRadius:"8px",padding:"0.5rem"},sortableItem:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"6px",boxShadow:"0 1px 3px rgba(0,0,0,0.08)"},sortableOrder:{width:"24px",height:"24px",display:"flex",alignItems:"center",justifyContent:"center",background:"#e94560",color:"white",borderRadius:"50%",fontSize:"0.8rem",fontWeight:"bold"},sortableName:{flex:1,fontWeight:500},sortableButtons:{display:"flex",gap:"0.25rem"},arrowBtn:{width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid #ddd",background:"white",borderRadius:"4px",cursor:"pointer",fontSize:"0.75rem"},removeBtn:{width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"#fee",color:"#c00",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},addCourseBtn:{padding:"0.5rem 0.75rem",background:"#e8f4fd",border:"1px dashed #0077cc",borderRadius:"6px",color:"#0077cc",cursor:"pointer",fontSize:"0.9rem"},excludedItemsGrid:{display:"flex",flexDirection:"column",gap:"0.25rem",marginTop:"1rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",maxHeight:"300px",overflowY:"auto"},excludedItem:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"4px",cursor:"pointer",fontSize:"0.9rem"},settingsBlock:{background:"#f8f9fa",padding:"1.5rem",borderRadius:"8px",marginBottom:"1.5rem",border:"1px solid #e0e0e0"},blockTitle:{color:"#1a1a2e",marginTop:0,marginBottom:"0.75rem",fontSize:"1.1rem",fontWeight:"600",borderBottom:"2px solid #e94560",paddingBottom:"0.5rem"}},PJ=["January","February","March","April","May","June","July","August","September","October","November","December"],RJ=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function BJ(){const{token:n}=gn(),e=new Date,[t,r]=k.useState(e.getFullYear()),[i,o]=k.useState(e.getMonth()+1),[a,l]=k.useState(null),{data:d}=Oe({queryKey:["settings"],queryFn:async()=>{const _=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${n}`}});if(!_.ok)throw new Error("Failed to fetch settings");return _.json()},enabled:!!n}),c=(d==null?void 0:d.currency_symbol)||"£",{data:u,isLoading:f}=Oe({queryKey:["newbook-calendar",t,i],queryFn:async()=>{const _=await fetch(`/api/newbook/calendar/${t}/${i}`,{headers:{Authorization:`Bearer ${n}`}});if(!_.ok)throw new Error("Failed to fetch calendar data");return _.json()},enabled:!!n}),p=()=>{i===1?(o(12),r(t-1)):o(i-1)},g=()=>{i===12?(o(1),r(t+1)):o(i+1)},m=()=>{r(e.getFullYear()),o(e.getMonth()+1)},y=new Date(t,i-1,1).getDay(),v=new Date(t,i,0).getDate(),x=[];for(let _=0;_{if(_===null)return"-";const b=new Intl.NumberFormat("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2}).format(_);return`${c}${b}`},S=_=>new Date(_).toLocaleDateString("en-AU",{weekday:"long",day:"numeric",month:"long",year:"numeric"});return s.jsxs("div",{style:Nt.container,children:[s.jsxs("div",{style:Nt.titleRow,children:[s.jsx("a",{href:"/settings",style:Nt.backLink,children:"← Back to Settings"}),s.jsx("h1",{style:Nt.title,children:"Newbook Data"})]}),s.jsxs("div",{style:Nt.calendarHeader,children:[s.jsx("button",{onClick:p,style:Nt.navBtn,children:"< Prev"}),s.jsxs("div",{style:Nt.monthTitle,children:[s.jsxs("h2",{style:Nt.monthName,children:[PJ[i-1]," ",t]}),s.jsx("button",{onClick:m,style:Nt.todayBtn,children:"Today"})]}),s.jsx("button",{onClick:g,style:Nt.navBtn,children:"Next >"})]}),s.jsxs("div",{style:Nt.legend,children:[s.jsxs("div",{style:Nt.legendItem,children:[s.jsx("span",{style:{...Nt.legendDot,background:"#4ade80"}}),s.jsx("span",{children:"Historical (locked)"})]}),s.jsxs("div",{style:Nt.legendItem,children:[s.jsx("span",{style:{...Nt.legendDot,background:"#fbbf24"}}),s.jsx("span",{children:"Forecast (updates on sync)"})]}),s.jsxs("div",{style:Nt.legendItem,children:[s.jsx("span",{style:{...Nt.legendDot,background:"#e5e7eb"}}),s.jsx("span",{children:"No data"})]})]}),f?s.jsx("div",{style:Nt.loading,children:"Loading calendar data..."}):s.jsx(s.Fragment,{children:s.jsxs("div",{style:Nt.calendar,children:[RJ.map(_=>s.jsx("div",{style:Nt.dayHeader,children:_},_)),x.map((_,b)=>{if(_===null)return s.jsx("div",{style:Nt.emptyCell},`empty-${b}`);const C=new Date(_.date).getDate(),T=_.date===e.toISOString().split("T")[0];let F={...Nt.dayCell};return _.has_data&&(_.is_forecast?F={...F,...Nt.forecastCell}:F={...F,...Nt.historicalCell}),T&&(F={...F,...Nt.todayCell}),s.jsxs("div",{style:F,onClick:()=>_.has_data&&l(_),children:[s.jsx("div",{style:Nt.dayNumber,children:C}),_.has_data&&s.jsxs("div",{style:Nt.dayData,children:[_.total_revenue!==null&&s.jsxs("div",{style:Nt.revenueTag,children:[c,Math.round(_.total_revenue)," net"]}),_.occupied_rooms!==null&&s.jsxs("div",{style:Nt.occupancyTag,children:[_.occupied_rooms,"/",_.total_rooms," (",_.total_guests??"-",") ",Math.round(_.occupancy_percentage??0),"%"]})]})]},_.date)})]})}),a&&s.jsx("div",{style:Nt.modalOverlay,onClick:()=>l(null),children:s.jsxs("div",{style:Nt.modal,onClick:_=>_.stopPropagation(),children:[s.jsxs("div",{style:Nt.modalHeader,children:[s.jsx("h3",{style:Nt.modalTitle,children:S(a.date)}),s.jsx("span",{style:{...Nt.badge,background:a.is_forecast?"#fbbf24":"#4ade80",color:a.is_forecast?"#78350f":"#14532d"},children:a.is_forecast?"Forecast":"Historical"})]}),s.jsxs("div",{style:Nt.modalContent,children:[s.jsxs("div",{style:Nt.section,children:[s.jsx("h4",{style:Nt.sectionTitle,children:"Occupancy"}),s.jsxs("div",{style:Nt.dataGrid,children:[s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Occupancy Rate"}),s.jsx("span",{style:Nt.dataValue,children:a.occupancy_percentage!==null?`${a.occupancy_percentage}%`:"-"})]}),s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Rooms"}),s.jsx("span",{style:Nt.dataValue,children:a.occupied_rooms!==null&&a.total_rooms!==null?`${a.occupied_rooms} / ${a.total_rooms}`:"-"})]}),s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Total Guests"}),s.jsx("span",{style:Nt.dataValue,children:a.total_guests??"-"})]})]})]}),s.jsxs("div",{style:Nt.section,children:[s.jsx("h4",{style:Nt.sectionTitle,children:"Meal Allocations"}),s.jsxs("div",{style:Nt.dataGrid,children:[s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Breakfast"}),s.jsx("span",{style:Nt.dataValue,children:a.breakfast_allocation_qty!==null?`${a.breakfast_allocation_qty} pax`:"-"}),a.is_forecast&&a.breakfast_allocation_netvalue!==null&&s.jsxs("span",{style:Nt.dataSubValue,children:[w(a.breakfast_allocation_netvalue)," net (est)"]})]}),s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Dinner"}),s.jsx("span",{style:Nt.dataValue,children:a.dinner_allocation_qty!==null?`${a.dinner_allocation_qty} pax`:"-"}),a.is_forecast&&a.dinner_allocation_netvalue!==null&&s.jsxs("span",{style:Nt.dataSubValue,children:[w(a.dinner_allocation_netvalue)," net (est)"]})]})]})]}),s.jsxs("div",{style:Nt.section,children:[s.jsx("h4",{style:Nt.sectionTitle,children:"Revenue (net)"}),s.jsxs("div",{style:Nt.revenueTotal,children:[s.jsx("span",{children:"Total"}),s.jsx("span",{style:Nt.revenueTotalValue,children:w(a.total_revenue)})]}),a.revenue_by_account&&a.revenue_by_account.length>0&&s.jsx("div",{style:Nt.revenueBreakdown,children:a.revenue_by_account.map((_,b)=>s.jsxs("div",{style:Nt.revenueItem,children:[s.jsx("span",{style:Nt.revenueGLName,children:_.gl_name}),s.jsx("span",{style:Nt.revenueAmount,children:w(_.amount)})]},b))})]})]}),s.jsx("button",{onClick:()=>l(null),style:Nt.closeBtn,children:"Close"})]})})]})}const Nt={container:{padding:"1rem"},titleRow:{marginBottom:"1rem"},backLink:{display:"inline-block",color:"#6b7280",textDecoration:"none",fontSize:"0.875rem",marginBottom:"0.5rem"},title:{fontSize:"1.75rem",fontWeight:"bold",marginBottom:"0.5rem",color:"#1a1a2e",margin:0},calendarHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},monthTitle:{display:"flex",alignItems:"center",gap:"1rem"},monthName:{fontSize:"1.5rem",fontWeight:"600",color:"#1a1a2e",margin:0},navBtn:{padding:"0.5rem 1rem",background:"#f3f4f6",border:"1px solid #d1d5db",borderRadius:"6px",cursor:"pointer",fontWeight:"500"},todayBtn:{padding:"0.25rem 0.75rem",background:"#e94560",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.875rem"},legend:{display:"flex",gap:"1.5rem",marginBottom:"1rem",padding:"0.75rem 1rem",background:"#f9fafb",borderRadius:"8px"},legendItem:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.875rem",color:"#4b5563"},legendDot:{width:"16px",height:"16px",borderRadius:"4px"},loading:{textAlign:"center",padding:"3rem",color:"#6b7280"},calendar:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:"4px",background:"#e5e7eb",borderRadius:"12px",padding:"4px"},dayHeader:{padding:"0.75rem",textAlign:"center",fontWeight:"600",color:"#374151",background:"#f9fafb"},emptyCell:{background:"#f9fafb",minHeight:"100px"},dayCell:{background:"white",minHeight:"100px",padding:"0.5rem",cursor:"default",position:"relative",borderRadius:"4px"},historicalCell:{background:"#dcfce7",cursor:"pointer"},forecastCell:{background:"#fef3c7",cursor:"pointer"},todayCell:{boxShadow:"inset 0 0 0 2px #e94560"},dayNumber:{fontWeight:"600",fontSize:"0.875rem",color:"#374151"},dayData:{marginTop:"0.5rem",display:"flex",flexDirection:"column",gap:"0.25rem"},revenueTag:{fontSize:"0.75rem",color:"#047857",fontWeight:"500"},occupancyTag:{fontSize:"0.75rem",color:"#6366f1",fontWeight:"500"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0, 0, 0, 0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",padding:"1.5rem",width:"90%",maxWidth:"500px",maxHeight:"80vh",overflow:"auto",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",paddingBottom:"1rem",borderBottom:"1px solid #e5e7eb"},modalTitle:{margin:0,fontSize:"1.25rem",fontWeight:"600",color:"#1a1a2e"},badge:{padding:"0.25rem 0.75rem",borderRadius:"9999px",fontSize:"0.75rem",fontWeight:"600"},modalContent:{display:"flex",flexDirection:"column",gap:"1.5rem"},section:{background:"#f9fafb",borderRadius:"8px",padding:"1rem"},sectionTitle:{margin:"0 0 0.75rem 0",fontSize:"0.875rem",fontWeight:"600",color:"#6b7280",textTransform:"uppercase",letterSpacing:"0.05em"},dataGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(120px, 1fr))",gap:"1rem"},dataItem:{display:"flex",flexDirection:"column",gap:"0.25rem"},dataLabel:{fontSize:"0.75rem",color:"#6b7280"},dataValue:{fontSize:"1.125rem",fontWeight:"600",color:"#1a1a2e"},dataSubValue:{fontSize:"0.875rem",color:"#6b7280"},revenueTotal:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem",background:"white",borderRadius:"6px",marginBottom:"0.75rem"},revenueTotalValue:{fontSize:"1.25rem",fontWeight:"700",color:"#047857"},revenueBreakdown:{display:"flex",flexDirection:"column",gap:"0.5rem"},revenueItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0.75rem",background:"white",borderRadius:"4px",fontSize:"0.875rem"},revenueGLName:{color:"#4b5563"},revenueAmount:{fontWeight:"500",color:"#1a1a2e"},closeBtn:{width:"100%",padding:"0.75rem",marginTop:"1.5rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"500"}},IJ=["January","February","March","April","May","June","July","August","September","October","November","December"],MJ=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];function zJ(){const{token:n}=gn(),[e,t]=K_(),r=new Date,[i,o]=k.useState(r.getFullYear()),[a,l]=k.useState(r.getMonth()+1),[d,c]=k.useState(null),[u,f]=k.useState(new Set),[p,g]=k.useState("all");k.useEffect(()=>{const ee=e.get("date");if(ee&&/^\d{4}-\d{2}-\d{2}$/.test(ee)){const Z=new Date(ee);o(Z.getFullYear()),l(Z.getMonth()+1),c(ee),t({},{replace:!0})}},[]);const[m,y]=k.useState(!1),[v,x]=k.useState(null),[w,S]=k.useState({event_date:"",event_type:"reminder",title:"",description:""});k.useEffect(()=>{f(new Set)},[d]);const{data:_}=Oe({queryKey:["resos-settings"],queryFn:async()=>{const ee=await fetch("/api/resos/settings",{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch settings");return ee.json()},enabled:!!n}),{data:b,isLoading:C}=Oe({queryKey:["resos-daily-stats",i,a],queryFn:async()=>{const ee=`${i}-${String(a).padStart(2,"0")}-01`,Z=new Date(i,a,0),ge=`${i}-${String(a).padStart(2,"0")}-${String(Z.getDate()).padStart(2,"0")}`,Te=await fetch(`/api/resos/daily-stats?from_date=${ee}&to_date=${ge}`,{headers:{Authorization:`Bearer ${n}`}});if(!Te.ok)throw new Error("Failed to fetch daily stats");return Te.json()},enabled:!!n}),{data:T}=Oe({queryKey:["resos-stats-prev",i,a],queryFn:async()=>{const ee=a===1?12:a-1,Z=a===1?i-1:i,ge=`${Z}-${String(ee).padStart(2,"0")}-01`,Te=new Date(Z,ee,0),Be=`${Z}-${String(ee).padStart(2,"0")}-${String(Te.getDate()).padStart(2,"0")}`,he=await fetch(`/api/resos/daily-stats?from_date=${ge}&to_date=${Be}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch previous month stats");return he.json()},enabled:!!n}),{data:F,refetch:A}=Oe({queryKey:["calendar-events",i,a],queryFn:async()=>{const ee=`${i}-${String(a).padStart(2,"0")}-01`,Z=new Date(i,a,0),ge=`${i}-${String(a).padStart(2,"0")}-${String(Z.getDate()).padStart(2,"0")}`,Te=await fetch(`/api/calendar-events/?from_date=${ee}&to_date=${ge}`,{headers:{Authorization:`Bearer ${n}`}});if(!Te.ok)throw new Error("Failed to fetch calendar events");return Te.json()},enabled:!!n}),{data:D}=Oe({queryKey:["resos-bookings",d],queryFn:async()=>{if(!d)return[];const ee=await fetch(`/api/resos/bookings/${d}`,{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch bookings");return ee.json()},enabled:!!n&&!!d}),{data:P}=Oe({queryKey:["resos-all-opening-hours"],queryFn:async()=>{const ee=await fetch("/api/resos/opening-hours",{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch opening hours");return ee.json()},enabled:!!n}),L=P!=null&&P.opening_hours?(()=>{const ee=P.opening_hours.filter(he=>!he.special);if(ee.length===0)return null;let Z=2400,ge=0;ee.forEach(he=>{const He=he.open||0,Ge=he.close||0;Hege&&(ge=Ge)});const Te=Math.floor(Z/100);let Be=Math.floor(ge/100);return ge%100>0&&Be++,{startHour:Te,endHour:Be}})():null,{data:W}=Oe({queryKey:["resos-opening-hours",d],queryFn:async()=>{if(!d)return[];const ee=await fetch(`/api/resos/opening-hours/${d}`,{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch opening hours");return ee.json()},enabled:!!d&&!!n}),O=()=>{a===1?(l(12),o(i-1)):l(a-1)},U=()=>{a===12?(l(1),o(i+1)):l(a+1)},M=()=>{o(r.getFullYear()),l(r.getMonth()+1)},I=ee=>{if(!(_!=null&&_.resos_opening_hours_mapping))return ee;const Z=_.resos_opening_hours_mapping.find(ge=>{var Te;return((Te=ge.display_name)==null?void 0:Te.toLowerCase())===ee.toLowerCase()});return Z!=null&&Z.service_type?Z.service_type.charAt(0).toUpperCase()+Z.service_type.slice(1):ee},H=ee=>{const Z=(_==null?void 0:_.resos_flag_icon_mapping)||{},ge={allergies:"🦀",large_group:"👥",note_keyword_birthday:"🎂",note_keyword_anniversary:"💍"};if(Z[ee])return Z[ee];if(ee.startsWith("note_keyword_")){const Te=ee.replace("note_keyword_","");if(Z[Te])return Z[Te]}return ge[ee]?ge[ee]:"⚠️"},z=ee=>{if(!ee)return"⚠️";const Z=ee.split(",").map(ge=>ge.trim());return H(Z[0])},G=ee=>ee?ee.split(",").map(ge=>ge.trim().toLowerCase()).includes("notes"):!1,te=ee=>{if(!ee||!(_!=null&&_.resos_note_keywords))return{hasKeywords:!1,matchedKeyword:null};const Z=_.resos_note_keywords.split(",").map(Te=>Te.trim().toLowerCase()),ge=ee.toLowerCase();for(const Te of Z)if(ge.includes(Te))return{hasKeywords:!0,matchedKeyword:Te};return{hasKeywords:!1,matchedKeyword:null}},re=ee=>{const Z=(_==null?void 0:_.resos_large_group_threshold)||8;return ee>=Z},me=()=>H("large_group"),J=ee=>{f(Z=>{const ge=new Set(Z);return ge.has(ee)?ge.delete(ee):ge.add(ee),ge})},ne=ee=>{if(!ee||ee.length===0)return[];const Z=new Set;for(const ge of ee){const Te=H(ge);Z.add(Te)}return Array.from(Z)},ye=new Map;b==null||b.forEach(ee=>{ye.set(ee.date,ee)});const ke=new Date(i,a-1,1),Ye=new Date(i,a,0),De=(ke.getDay()+6)%7,qe=Ye.getDate(),ue=[];for(let ee=0;ee{const Z=ee.event_date;Ze.has(Z)||Ze.set(Z,[]),Ze.get(Z).push(ee)}),s.jsxs("div",{style:ht.container,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h1",{style:ht.title,children:"Restaurant Calendar"}),s.jsx("p",{style:ht.subtitle,children:"View synced booking data, covers, and flagged reservations from Resos"})]}),s.jsx("button",{onClick:()=>{x(null),S({event_date:new Date().toISOString().split("T")[0],event_type:"reminder",title:"",description:""}),y(!0)},style:{...ht.todayButton,padding:"0.75rem 1.5rem",fontSize:"0.95rem"},children:"+ Create Event"})]}),s.jsxs("div",{style:ht.navBar,children:[s.jsx("button",{onClick:O,style:ht.navButton,children:"← Previous"}),s.jsxs("div",{style:ht.monthYearDisplay,children:[IJ[a-1]," ",i]}),s.jsx("button",{onClick:M,style:ht.todayButton,children:"Today"}),s.jsx("button",{onClick:U,style:ht.navButton,children:"Next →"})]}),C?s.jsx("div",{style:ht.loading,children:"Loading calendar data..."}):s.jsxs("div",{style:ht.calendar,children:[s.jsx("div",{style:ht.calendarHeader,children:MJ.map(ee=>s.jsx("div",{style:ht.dayHeader,children:ee},ee))}),s.jsx("div",{style:ht.calendarGrid,children:ue.map((ee,Z)=>{if(!ee)return s.jsx("div",{style:ht.emptyCell},`empty-${Z}`);const ge=`${i}-${String(a).padStart(2,"0")}-${String(ee.getDate()).padStart(2,"0")}`,Te=ye.get(ge),Be=ge===r.toISOString().split("T")[0],he=((Te==null?void 0:Te.flagged_booking_count)||0)>0,He=Ze.has(ge);return s.jsxs("div",{style:{...ht.dayCell,...Te?ht.dayCellWithData:{},...Be?ht.dayCellToday:{},...he?ht.dayCellFlagged:{},...Te!=null&&Te.is_forecast?ht.dayCellForecast:{}},onClick:()=>Te&&c(ge),children:[s.jsxs("div",{style:ht.dayNumber,children:[ee.getDate(),He&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.9rem"},children:"⭐"}),he&&s.jsx("span",{style:ht.flagIcon,children:ne((Te==null?void 0:Te.unique_flag_types)||null).map((Ge,ae)=>s.jsx("span",{children:Ge},ae))})]}),Te&&s.jsxs("div",{style:ht.dayStats,children:[s.jsxs("div",{style:ht.statLine,children:[s.jsx("strong",{children:Te.total_bookings})," bookings"]}),s.jsxs("div",{style:ht.statLine,children:[s.jsx("strong",{children:Te.total_covers})," covers"]}),Te.service_breakdown.length>0&&s.jsx("div",{style:ht.serviceBreakdown,children:Te.service_breakdown.map(Ge=>s.jsxs("div",{style:ht.serviceLine,children:[I(Ge.period),": ",Ge.bookings," : ",Ge.covers]},Ge.period))})]})]},ge)})}),b&&T&&s.jsxs("div",{style:ht.chartContainer,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsx("h3",{style:ht.chartTitle,children:"Current vs Previous Month"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("label",{htmlFor:"serviceTypeFilter",style:{fontSize:"0.9rem",fontWeight:"600"},children:"Service Type:"}),s.jsxs("select",{id:"serviceTypeFilter",value:p,onChange:ee=>g(ee.target.value),style:{padding:"0.5rem",borderRadius:"4px",border:"1px solid #ccc",fontSize:"0.9rem",cursor:"pointer"},children:[s.jsx("option",{value:"all",children:"All Services"}),s.jsx("option",{value:"breakfast",children:"Breakfast"}),s.jsx("option",{value:"lunch",children:"Lunch"}),s.jsx("option",{value:"dinner",children:"Dinner"}),s.jsx("option",{value:"other",children:"Other"})]})]})]}),(()=>{const ee=new Date(i,a,0).getDate(),Z=a===1?12:a-1,ge=a===1?i-1:i,Te=Le=>{if(p==="all")return{bookings:Le.total_bookings,covers:Le.total_covers};const rt=Le.service_breakdown.find($e=>$e.period.toLowerCase()===p);return rt?{bookings:rt.bookings,covers:rt.covers}:{bookings:0,covers:0}},Be=new Array(ee).fill(0),he=new Array(ee).fill(0),He=new Array(ee).fill(0),Ge=new Array(ee).fill(0);b.forEach(Le=>{const rt=new Date(Le.date).getDate(),{bookings:$e,covers:ce}=Te(Le);Be[rt-1]=$e,he[rt-1]=ce});const ae=new Map;T.forEach(Le=>{const{bookings:rt,covers:$e}=Te(Le);ae.set(Le.date,{bookings:rt,covers:$e})});const de=new Date(i,a-1,1).getDay();let Y=new Date(ge,Z-1,1);for(;Y.getDay()!==de;)Y.setDate(Y.getDate()+1);for(let Le=1;Le<=ee;Le++){const rt=Le-1,$e=new Date(Y);$e.setDate(Y.getDate()+rt);const ce=$e.toISOString().split("T")[0],Je=ae.get(ce);Je&&(He[Le-1]=Je.bookings,Ge[Le-1]=Je.covers)}const Q={};for(let Le=0;Le<7;Le++)Q[Le]={bookings:[],covers:[]};T.forEach(Le=>{const $e=new Date(Le.date).getDay(),{bookings:ce,covers:Je}=Te(Le);Q[$e].bookings.push(ce),Q[$e].covers.push(Je)});const X={};for(let Le=0;Le<7;Le++){const rt=Q[Le].bookings,$e=Q[Le].covers;X[Le]={bookings:rt.length>0?rt.reduce((ce,Je)=>ce+Je,0)/rt.length:0,covers:$e.length>0?$e.reduce((ce,Je)=>ce+Je,0)/$e.length:0}}const pe=new Array(ee).fill(0);for(let Le=1;Le<=ee;Le++){const $e=new Date(i,a-1,Le).getDay();pe[Le-1]=X[$e].covers}const we=Math.max(...Be,...He,...he,...Ge,...pe,10),Ne=300,st="100%",Ve=50,Re=1200;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:st,height:Ne,viewBox:`0 0 ${Re} ${Ne}`,preserveAspectRatio:"xMidYMid meet",style:ht.chart,children:[[0,.25,.5,.75,1].map(Le=>s.jsx("line",{x1:Ve,y1:Ve+(Ne-2*Ve)*Le,x2:Re-Ve,y2:Ve+(Ne-2*Ve)*Le,stroke:"#e0e0e0",strokeWidth:"1"},Le)),Array.from({length:ee},(Le,rt)=>{const $e=rt+1;if(new Date(i,a-1,$e).getDay()===0){const jt=Ve+(Re-2*Ve)/(ee-1)*rt;return s.jsx("line",{x1:jt,y1:Ve,x2:jt,y2:Ne-Ve,stroke:"#999",strokeWidth:"1",strokeDasharray:"3,3"},`sunday-${$e}`)}return null}),s.jsx("polyline",{points:Be.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-He[rt]/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#93c5fd",strokeWidth:"2",strokeDasharray:"5,5"}),s.jsx("polyline",{points:Be.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#3b82f6",strokeWidth:"3"}),Be.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return s.jsx("circle",{cx:$e,cy:ce,r:"3",fill:"#3b82f6",stroke:"white",strokeWidth:"1"},`booking-point-${rt}`)}),s.jsx("polyline",{points:he.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Ge[rt]/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#86efac",strokeWidth:"2",strokeDasharray:"5,5"}),s.jsx("polyline",{points:he.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#10b981",strokeWidth:"3"}),he.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return s.jsx("circle",{cx:$e,cy:ce,r:"3",fill:"#10b981",stroke:"white",strokeWidth:"1"},`cover-point-${rt}`)}),s.jsx("polyline",{points:pe.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#f97316",strokeWidth:"2",strokeDasharray:"3,3"}),s.jsx("text",{x:Ve-10,y:Ve,textAnchor:"end",fontSize:"12",fill:"#666",children:we}),s.jsx("text",{x:Ve-10,y:Ve+(Ne-2*Ve)*.5,textAnchor:"end",fontSize:"12",fill:"#666",children:Math.round(we/2)}),s.jsx("text",{x:Ve-10,y:Ne-Ve,textAnchor:"end",fontSize:"12",fill:"#666",children:"0"}),Array.from({length:Math.ceil(ee/5)},(Le,rt)=>{const $e=rt*5+1;if($e>ee)return null;const ce=Ve+(Re-2*Ve)/(ee-1)*($e-1);return s.jsx("text",{x:ce,y:Ne-Ve+20,textAnchor:"middle",fontSize:"11",fill:"#666",children:$e},$e)})]}),s.jsxs("div",{style:ht.chartLegend,children:[s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,background:"#3b82f6"}}),"Current Bookings"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,height:"2px",borderTop:"2px dashed #93c5fd",background:"transparent"}}),"Previous Bookings"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,background:"#10b981"}}),"Current Covers"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,height:"2px",borderTop:"2px dashed #86efac",background:"transparent"}}),"Previous Covers"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,height:"2px",borderTop:"2px dashed #f97316",background:"transparent"}}),"Avg Day-of-Week Covers"]})]})]})})()]})]}),d&&D&&s.jsx("div",{style:ht.modalOverlay,onClick:()=>c(null),children:s.jsxs("div",{style:ht.modal,onClick:ee=>ee.stopPropagation(),children:[s.jsxs("div",{style:ht.modalHeader,children:[s.jsxs("h2",{children:["Bookings for ",d]}),s.jsx("button",{onClick:()=>c(null),style:ht.closeBtn,children:"×"})]}),s.jsxs("div",{style:ht.modalContent,children:[(()=>{const ee=Ze.get(d)||[];return ee.length>0?s.jsxs("div",{style:{marginBottom:"2rem"},children:[s.jsx("h3",{style:{marginBottom:"1rem"},children:"Events & Reminders"}),ee.map(Z=>s.jsxs("div",{style:{padding:"1rem",background:Z.event_type==="reminder"?"#fff3cd":Z.event_type==="event"?"#d1ecf1":"#f8f9fa",borderLeft:`4px solid ${Z.event_type==="reminder"?"#ffc107":Z.event_type==="event"?"#0dcaf0":"#6c757d"}`,borderRadius:"4px",marginBottom:"0.5rem",display:"flex",justifyContent:"space-between",alignItems:"start"},children:[s.jsxs("div",{children:[s.jsxs("div",{style:{fontWeight:"bold",marginBottom:"0.25rem"},children:[Z.event_type.toUpperCase(),": ",Z.title]}),Z.description&&s.jsx("div",{style:{fontSize:"0.9rem",color:"#666"},children:Z.description})]}),s.jsx("button",{onClick:()=>{x(Z),S({event_date:Z.event_date,event_type:Z.event_type,title:Z.title,description:Z.description||""}),y(!0)},style:{padding:"0.5rem 1rem",background:"#667eea",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"Edit"})]},Z.id))]}):null})(),(()=>{let ee=18,Z=22;if(L)ee=L.startHour,Z=L.endHour;else if(D.length>0){const K=D.map(Q=>{const[X,pe]=Q.booking_time.split(":").map(Number);return X*60+pe}),de=Math.min(...K),Y=Math.max(...K)+120;ee=Math.floor(de/60),Z=Math.ceil(Y/60)}const ge=(Z-ee)*60,Te=[...D].sort((K,de)=>{const Y=parseInt(K.booking_time.replace(/:/g,"")),Q=parseInt(de.booking_time.replace(/:/g,""));return Y-Q}),Be=[],he=Te.map(K=>{const[de,Y]=K.booking_time.split(":").map(Number),Q=(de-ee)*60+Y,X=Q+120,pe=K.people,we=Math.max(1,Math.floor(pe/4)+1);let Ne=0,st=!1;for(;!st;){for(;Be.length=Le.end+5)){Ve=!1;break}if(!Ve)break}if(Ve){for(let Re=Ne;Re{const K=[];if(!W||W.length===0)return K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:"0%",width:"100%",height:Ge}},"full-closed")),K;const de=[...W].sort((st,Ve)=>st.open-Ve.open),Y=de[0].open,X=Math.floor(Y/100)*60+Y%100-ee*60;if(X>0){const st=X/ge*100;K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:"0%",width:`${st}%`,height:Ge}},"before-open"))}for(let st=0;st0){const jt=$e/ge*100,ct=Je/ge*100;K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:`${jt}%`,width:`${ct}%`,height:Ge}},`gap-${st}`))}}const pe=de[de.length-1].close,we=Math.floor(pe/100)*60+pe%100,Ne=Z*60-we;if(Ne>0){const st=(we-ee*60)/ge*100,Ve=Ne/ge*100;K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:`${st}%`,width:`${Ve}%`,height:Ge}},"after-close"))}return K};return s.jsxs("div",{style:ht.ganttContainer,children:[s.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem"},children:"Timeline"}),s.jsx("div",{style:ht.ganttTimeAxis,children:Array.from({length:Z-ee},(K,de)=>ee+de).flatMap(K=>[s.jsxs("div",{style:{...ht.ganttTimeLabel,left:`${(K-ee)*60/ge*100}%`},children:[K,":00"]},`${K}-00`),s.jsxs("div",{style:{...ht.ganttTimeLabel,left:`${((K-ee)*60+30)/ge*100}%`},children:[K,":30"]},`${K}-30`)])}),s.jsxs("div",{style:{...ht.ganttBookings,height:Ge},children:[ae(),Array.from({length:Math.floor(ge/15)},(K,de)=>(de+1)*15).map(K=>s.jsx("div",{style:{...ht.ganttIntervalLine,left:`${K/ge*100}%`,height:Ge}},K)),he.map(K=>{const de=K.bookingStart/ge*100,Y=(Math.min(K.bookingEnd,ge)-K.bookingStart)/ge*100,Q=10+K.gridRow*He,X=K.rowSpan*He-4,pe=K.table_name||"",we=re(K.people),Ne=K.is_flagged?z(K.flag_reasons):we?me():"";return s.jsxs("div",{style:{...ht.ganttBookingBar,left:`${de}%`,width:`${Y}%`,top:Q,height:X},title:`${K.booking_time} - ${I(K.opening_hour_name||"")} - ${K.people} covers${K.table_name?` - Table ${K.table_name}`:""}${K.allergies?` 🦀 ${K.allergies}`:""}${K.notes?` 📝 ${K.notes}`:""}`,children:[s.jsx("span",{style:ht.ganttPartySize,children:K.people}),Ne&&s.jsx("span",{children:Ne}),pe&&s.jsx("span",{style:ht.ganttBarText,children:pe})]},K.id)})]})]})})(),s.jsxs("h3",{children:["All Bookings (",D.length,")"]}),s.jsx("div",{style:ht.tableContainer,children:(()=>{const ee=D.reduce((ge,Te)=>{const Be=I(Te.opening_hour_name||"Unknown");return ge[Be]||(ge[Be]=[]),ge[Be].push(Te),ge},{});return Object.entries(ee).map(([ge,Te])=>{var Be;return{period:ge,bookings:Te.sort((he,He)=>he.booking_time.localeCompare(He.booking_time)),firstTime:((Be=Te[0])==null?void 0:Be.booking_time)||""}}).sort((ge,Te)=>ge.firstTime.localeCompare(Te.firstTime)).map(({period:ge,bookings:Te})=>s.jsxs("div",{style:ht.serviceGroup,children:[s.jsx("h4",{style:ht.serviceGroupTitle,children:ge}),s.jsxs("table",{style:ht.bookingsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:ht.th,children:"Time"}),s.jsx("th",{style:ht.th,children:"Area"}),s.jsx("th",{style:ht.th,children:"Table"}),s.jsx("th",{style:ht.th,children:"Covers"}),s.jsx("th",{style:ht.th,children:"Hotel Guest"}),s.jsx("th",{style:ht.th,children:"DBB/Package"}),s.jsx("th",{style:ht.th,children:"Allergies"}),s.jsx("th",{style:ht.th,children:"Notes"})]})}),s.jsx("tbody",{children:Te.map(Be=>{var we;const he=Be.allergies&&((we=Be.flag_reasons)!=null&&we.includes("allergies"))?z("allergies"):"",He=Be.notes?"📝":"",Ge=G(Be.flag_reasons),ae=u.has(Be.id),K=Be.notes&&(ae||Ge),de=re(Be.people),Y=de?me():"",{hasKeywords:Q,matchedKeyword:X}=te(Be.notes),pe=Q&&X?H(`note_keyword_${X}`):"";return s.jsxs(nF.Fragment,{children:[s.jsxs("tr",{children:[s.jsx("td",{style:ht.td,children:Be.booking_time}),s.jsx("td",{style:ht.td,children:Be.seating_area||"-"}),s.jsx("td",{style:ht.td,children:Be.table_name||"-"}),s.jsxs("td",{style:de?ht.highlightCell:ht.td,children:[Be.people,Y&&s.jsx("span",{style:{marginLeft:"0.25rem"},children:Y})]}),s.jsx("td",{style:ht.td,children:Be.is_hotel_guest?"✓":"-"}),s.jsx("td",{style:ht.td,children:Be.is_dbb&&Be.is_package?"DBB + Pkg":Be.is_dbb?"DBB":Be.is_package?"Package":"-"}),s.jsxs("td",{style:Be.allergies?ht.highlightCell:ht.td,children:[he&&s.jsx("span",{style:{marginRight:"0.25rem"},children:he}),Be.allergies||"-"]}),s.jsxs("td",{style:Ge||Q?ht.highlightCell:ht.td,onClick:()=>Be.notes&&J(Be.id),children:[He&&s.jsx("span",{style:ht.clickableIcon,children:He}),pe&&s.jsx("span",{style:{...ht.clickableIcon,marginLeft:"0.25rem"},children:pe}),!Be.notes&&"-"]})]}),K&&s.jsxs("tr",{children:[s.jsx("td",{colSpan:4,style:ht.emptyIndentCell}),s.jsxs("td",{colSpan:4,style:ht.notesRow,children:[s.jsx("strong",{children:"Notes:"})," ",Be.notes]})]},`${Be.id}-notes`),Be.allergies&&s.jsxs("tr",{children:[s.jsx("td",{colSpan:4,style:ht.emptyIndentCell}),s.jsxs("td",{colSpan:4,style:ht.allergiesRow,children:[s.jsx("strong",{children:"Allergies:"})," ",Be.allergies]})]},`${Be.id}-allergies`)]},Be.id)})})]})]},ge))})()})]})]})}),m&&s.jsx("div",{style:ht.modalOverlay,onClick:()=>y(!1),children:s.jsxs("div",{style:{...ht.modal,maxWidth:"600px"},onClick:ee=>ee.stopPropagation(),children:[s.jsxs("div",{style:ht.modalHeader,children:[s.jsx("h2",{children:v?"Edit Event":"Create Event"}),s.jsx("button",{onClick:()=>y(!1),style:ht.closeBtn,children:"×"})]}),s.jsx("div",{style:ht.modalContent,children:s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Date"}),s.jsx("input",{type:"date",value:w.event_date,onChange:ee=>S({...w,event_date:ee.target.value}),style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Type"}),s.jsxs("select",{value:w.event_type,onChange:ee=>S({...w,event_type:ee.target.value}),style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd"},children:[s.jsx("option",{value:"reminder",children:"Reminder"}),s.jsx("option",{value:"event",children:"Event"}),s.jsx("option",{value:"note",children:"Note"})]})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Title"}),s.jsx("input",{type:"text",value:w.title,onChange:ee=>S({...w,title:ee.target.value}),placeholder:"Event title...",style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Description"}),s.jsx("textarea",{value:w.description,onChange:ee=>S({...w,description:ee.target.value}),placeholder:"Optional description...",rows:4,style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd",resize:"vertical"}})]}),s.jsxs("div",{style:{display:"flex",gap:"1rem",justifyContent:"flex-end"},children:[v&&s.jsx("button",{onClick:async()=>{confirm("Delete this event?")&&(await fetch(`/api/calendar-events/${v.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}}),y(!1),A())},style:{padding:"0.75rem 1.5rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},children:"Delete"}),s.jsx("button",{onClick:()=>y(!1),style:{padding:"0.75rem 1.5rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},children:"Cancel"}),s.jsx("button",{onClick:async()=>{const ee=v?`/api/calendar-events/${v.id}`:"/api/calendar-events/";await fetch(ee,{method:v?"PUT":"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(w)}),y(!1),A()},disabled:!w.title||!w.event_date,style:{padding:"0.75rem 1.5rem",background:!w.title||!w.event_date?"#ccc":"#667eea",color:"white",border:"none",borderRadius:"6px",cursor:!w.title||!w.event_date?"not-allowed":"pointer",fontWeight:"bold"},children:v?"Update":"Create"})]})]})})]})})]})}const ht={container:{padding:"2rem",maxWidth:"1400px",margin:"0 auto"},title:{fontSize:"2rem",fontWeight:"bold",marginBottom:"0.5rem"},subtitle:{color:"#666",marginBottom:"2rem"},navBar:{display:"flex",alignItems:"center",gap:"1rem",marginBottom:"2rem",padding:"1rem",background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},navButton:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:500},todayButton:{padding:"0.5rem 1rem",background:"#0066cc",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:500},monthYearDisplay:{fontSize:"1.5rem",fontWeight:"bold",flex:1,textAlign:"center"},loading:{padding:"2rem",textAlign:"center",background:"white",borderRadius:"8px"},calendar:{background:"white",borderRadius:"8px",padding:"1rem",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},calendarHeader:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:"0.5rem",marginBottom:"0.5rem"},dayHeader:{padding:"0.5rem",textAlign:"center",fontWeight:"bold",color:"#666"},calendarGrid:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:"0.5rem"},emptyCell:{minHeight:"100px"},dayCell:{minHeight:"100px",padding:"0.5rem",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"default",background:"#fafafa"},dayCellWithData:{background:"white",cursor:"pointer",transition:"transform 0.2s, box-shadow 0.2s"},dayCellToday:{borderColor:"#0066cc",borderWidth:"2px"},dayCellFlagged:{borderLeftColor:"#e94560",borderLeftWidth:"4px"},dayCellForecast:{background:"#f0f8ff"},dayNumber:{fontSize:"1.1rem",fontWeight:"bold",marginBottom:"0.5rem",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.25rem"},flagIcon:{fontSize:"1rem"},dayStats:{fontSize:"0.85rem",color:"#333"},statLine:{marginBottom:"0.25rem"},serviceBreakdown:{marginTop:"0.5rem",fontSize:"0.75rem",color:"#666"},serviceLine:{marginBottom:"0.2rem"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",width:"90%",maxWidth:"1000px",maxHeight:"90vh",overflow:"hidden",display:"flex",flexDirection:"column",padding:"2rem"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",paddingBottom:"1rem",borderBottom:"2px solid #e0e0e0",flexShrink:0},closeBtn:{background:"none",border:"none",fontSize:"2rem",cursor:"pointer",color:"#666",lineHeight:1},modalContent:{marginTop:"1rem",flex:1,overflowY:"scroll",scrollbarGutter:"stable",paddingRight:"0.5rem"},tableContainer:{overflowX:"auto",marginTop:"1rem"},bookingsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",fontWeight:"bold",background:"#f8f9fa"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},serviceGroup:{marginBottom:"1.5rem"},serviceGroupTitle:{fontSize:"1.1rem",fontWeight:"bold",marginBottom:"0.5rem",padding:"0.5rem",background:"#f0f0f0",borderRadius:"4px"},highlightCell:{padding:"0.75rem",borderBottom:"1px solid #eee",background:"#fffbcc"},clickableIcon:{cursor:"pointer",userSelect:"none",fontSize:"1.2rem"},emptyIndentCell:{padding:0,borderTop:"none",borderBottom:"2px solid #ddd",background:"transparent"},notesRow:{padding:"0.75rem",background:"#f8f9fa",borderTop:"none",borderBottom:"2px solid #ddd",fontSize:"0.9rem",fontStyle:"italic",color:"#555"},allergiesRow:{padding:"0.75rem",background:"#fff3cd",borderTop:"none",borderBottom:"2px solid #ddd",fontSize:"0.9rem",color:"#856404"},ganttContainer:{marginBottom:"1.5rem",border:"1px solid #e5e7eb",borderRadius:"6px",overflow:"hidden",padding:"0.75rem",background:"#f9fafb"},ganttTimeAxis:{position:"relative",height:"30px",borderBottom:"1px solid #ddd",background:"#f9f9f9",marginBottom:"0.5rem"},ganttTimeLabel:{position:"absolute",top:"8px",transform:"translateX(-50%)",fontSize:"11px",color:"#666",whiteSpace:"nowrap"},ganttBookings:{position:"relative",background:"white"},ganttBookingBar:{position:"absolute",background:"linear-gradient(135deg, #667eea 0%, #764ba2 100%)",borderRadius:"4px",border:"2px solid #5568d3",padding:"4px 8px",color:"white",fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",cursor:"pointer",transition:"transform 0.2s",zIndex:2},ganttPartySize:{background:"rgba(255,255,255,0.3)",borderRadius:"3px",padding:"2px 6px",fontSize:"11px",fontWeight:"bold",flexShrink:0},ganttBarText:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:"11px"},ganttIntervalLine:{position:"absolute",width:"1px",background:"#e5e5e5",top:0,pointerEvents:"none",zIndex:1},ganttClosedBlock:{position:"absolute",background:"rgba(100, 100, 100, 0.1)",top:0,pointerEvents:"none",zIndex:0},chartContainer:{background:"white",borderRadius:"8px",padding:"1.5rem",marginTop:"2rem",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},chartTitle:{fontSize:"1.5rem",fontWeight:"bold",marginBottom:"1rem"},chart:{border:"1px solid #e5e7eb",borderRadius:"4px"},chartLegend:{display:"flex",gap:"2rem",justifyContent:"center",marginTop:"1rem"},legendItem:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem"},legendLine:{width:"30px",height:"3px",display:"inline-block"}},lO={normal:{bg:"#e8e5f5",border:"#667eea"},groupMember:{bg:"#e8e5f5",border:"#0ea5e9"}};function OJ(){const{token:n}=gn(),[e,t]=k.useState(()=>new Date().toISOString().split("T")[0]),[r,i]=k.useState(null),[o,a]=k.useState(null),{data:l,isLoading:d}=Oe({queryKey:["residents-table-chart","v2",e],queryFn:async()=>{const p=await fetch(`/api/residents-table-chart?start_date=${e}`,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok)throw new Error("Failed to fetch chart data");return p.json()},staleTime:2*60*1e3}),c=()=>{const p=new Date(e);p.setDate(p.getDate()-7),t(p.toISOString().split("T")[0])},u=()=>{const p=new Date(e);p.setDate(p.getDate()+7),t(p.toISOString().split("T")[0])},f=p=>{const g=new Date(p);return`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][g.getDay()]} ${g.getDate()}`};return d?s.jsxs("div",{style:Vn.container,children:[s.jsx("h1",{children:"Residents Table Chart"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"Loading..."})]}):!l||!l.rooms?s.jsxs("div",{style:Vn.container,children:[s.jsx("h1",{children:"Residents Table Chart"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:l?"Loading new data structure...":"No data available"})]}):s.jsxs("div",{style:Vn.container,children:[s.jsx("h1",{children:"Residents Table Chart"}),s.jsxs("div",{style:Vn.header,children:[s.jsx("button",{onClick:c,style:Vn.navButton,children:"◀ Prev Week"}),s.jsx("input",{type:"date",value:e,onChange:p=>t(p.target.value),style:Vn.dateInput}),s.jsx("button",{onClick:u,style:Vn.navButton,children:"Next Week ▶"})]}),s.jsxs("div",{style:Vn.summary,children:[s.jsx("strong",{children:l.summary.total_rooms})," Rooms",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsx("strong",{children:l.summary.total_bookings})," Bookings",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsx("strong",{children:l.summary.total_room_nights})," Room Nights",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsx("strong",{children:l.summary.nights_with_restaurant})," with Restaurant Table",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsxs("strong",{children:[l.summary.coverage_percentage,"%"]})," Coverage"]}),s.jsx("div",{style:Vn.chartContainer,children:s.jsxs("div",{style:Vn.grid,children:[s.jsx("div",{style:{...Vn.headerCell,borderLeft:"none"},children:"Room"}),l.date_range.dates.map(p=>s.jsx("div",{style:Vn.headerCell,children:f(p)},p)),l.rooms.map((p,g)=>s.jsxs("div",{style:Vn.row,children:[s.jsx("div",{style:Vn.roomCell,children:s.jsx("div",{style:Vn.roomNumber,children:p.room_number||"Unknown Room"})}),l.date_range.dates.map(m=>{const v=p.bookings.filter(T=>T.nights.includes(m))[0];if(!v)return s.jsx("div",{style:Vn.dayCell},m);const x=v.check_in===m,w=v.nights[v.nights.length-1]===m,S=v.restaurant_bookings[m],_=v.bookings_group_id&&v.bookings_group_id.trim()!=="",b=_&&o===v.bookings_group_id,C=_?lO.groupMember:lO.normal;return s.jsxs("div",{style:Vn.dayCell,children:[s.jsx("div",{style:{position:"absolute",top:"12px",height:"36px",background:C.bg,cursor:"pointer",transition:"all 0.2s ease",zIndex:b?15:10,left:x?"0.5rem":"calc(-0.5rem + 1px)",right:w?"0.5rem":"calc(-0.5rem + 1px)",borderRadius:x&&w?"8px":x?"8px 0 0 8px":w?"0 8px 8px 0":"0",borderTop:`2px solid ${C.border}`,borderBottom:`2px solid ${C.border}`,borderLeft:x?`2px solid ${C.border}`:"none",borderRight:w?`2px solid ${C.border}`:"none",boxShadow:b?x&&w?`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}, inset 3px 0 0 ${C.border}, inset -3px 0 0 ${C.border}`:x?`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}, inset 3px 0 0 ${C.border}`:w?`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}, inset -3px 0 0 ${C.border}`:`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}`:x||w?"0 1px 3px rgba(0,0,0,0.05)":"none"},onMouseEnter:()=>_&&a(v.bookings_group_id),onMouseLeave:()=>a(null),onClick:()=>i({room:p,booking:v}),title:`Room ${p.room_number} - Booking ${v.booking_id} ${v.check_in} to ${v.check_out}${_?` Group: ${v.bookings_group_id}`:""}`}),(S==null?void 0:S.has_booking)&&s.jsx("div",{style:{position:"absolute",top:"12px",left:"50%",transform:"translateX(-50%)",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.3rem",cursor:"pointer",filter:"drop-shadow(0 1px 2px rgba(0,0,0,0.3))",zIndex:20,pointerEvents:"none",opacity:S.is_group_match?.5:1},title:`${S.opening_hour_name||"Dining"} - ${S.time||""} ${S.people} people${S.table_name?` ${S.table_name}`:""}${S.is_group_match?` (Group booking - via another room)`:""}`,children:"🍽️"})]},m)})]},p.room_number||`room-${g}`))]})}),r&&s.jsx("div",{style:Vn.modalOverlay,onClick:()=>i(null),children:s.jsxs("div",{style:Vn.modal,onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{style:Vn.modalHeader,children:[s.jsxs("h2",{children:["Room ",r.room.room_number||"Unknown"]}),s.jsx("button",{onClick:()=>i(null),style:Vn.closeBtn,children:"×"})]}),s.jsxs("div",{style:Vn.modalContent,children:[s.jsxs("div",{style:Vn.modalRow,children:[s.jsx("strong",{children:"Booking ID:"})," ",r.booking.booking_id||"Not specified"]}),s.jsxs("div",{style:Vn.modalRow,children:[s.jsx("strong",{children:"Stay:"})," ",r.booking.check_in," to ",r.booking.check_out," (",r.booking.nights.length," nights)"]}),r.booking.is_dbb&&s.jsx("div",{style:Vn.modalRow,children:s.jsx("span",{style:Vn.badge,children:"Dinner, Bed & Breakfast"})}),r.booking.is_package&&s.jsx("div",{style:Vn.modalRow,children:s.jsx("span",{style:Vn.badge,children:"Package Deal"})}),s.jsx("h3",{style:{marginTop:"1.5rem",marginBottom:"0.75rem"},children:"Restaurant Bookings"}),s.jsxs("table",{style:Vn.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Vn.th,children:"Date"}),s.jsx("th",{style:Vn.th,children:"Time"}),s.jsx("th",{style:Vn.th,children:"Service"}),s.jsx("th",{style:Vn.th,children:"Covers"}),s.jsx("th",{style:Vn.th,children:"Table"})]})}),s.jsx("tbody",{children:r.booking.nights.map(p=>{const g=r.booking.restaurant_bookings[p];return s.jsxs("tr",{style:g!=null&&g.has_booking?{}:Vn.noBookingRow,children:[s.jsx("td",{style:Vn.td,children:p}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.time:"-"}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.opening_hour_name:"-"}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.people:"-"}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.table_name:"-"})]},p)})})]})]})]})})]})}const Vn={container:{padding:"2rem",background:"#f5f5f5",minHeight:"100vh"},header:{background:"white",padding:"1.5rem",borderRadius:"12px",marginBottom:"1rem",display:"flex",gap:"1rem",alignItems:"center",justifyContent:"center"},navButton:{padding:"0.75rem 1.5rem",background:"#667eea",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"1rem",fontWeight:"500"},dateInput:{padding:"0.75rem",border:"1px solid #ddd",borderRadius:"8px",fontSize:"1rem"},summary:{background:"white",padding:"1rem 1.5rem",borderRadius:"8px",marginBottom:"1rem",fontSize:"0.95rem",color:"#666",textAlign:"center"},chartContainer:{background:"white",borderRadius:"12px",overflow:"auto",scrollbarGutter:"stable",padding:"1rem",paddingRight:"0.5rem"},grid:{display:"grid",gridTemplateColumns:"150px repeat(7, 1fr)",gap:"0",minWidth:"1000px"},headerCell:{padding:"0.75rem",borderBottom:"2px solid #333",borderLeft:"1px solid #eee",fontWeight:"bold",textAlign:"center",background:"#f8f8f8",fontSize:"0.9rem"},row:{display:"contents"},roomCell:{padding:"0.75rem",borderRight:"1px solid #ddd",borderBottom:"1px solid #eee",fontWeight:"500",background:"#fafafa",display:"flex",flexDirection:"column",gap:"0.25rem"},roomNumber:{fontSize:"1rem",fontWeight:"bold",color:"#333"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#e0e7ff",color:"#4338ca",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"600",marginTop:"0.25rem"},dayCell:{position:"relative",padding:"0.5rem",borderLeft:"1px solid #eee",borderBottom:"1px solid #eee",minHeight:"70px",background:"white"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",width:"90%",maxWidth:"700px",maxHeight:"90vh",overflow:"auto",padding:"24px"},modalHeader:{display:"flex",justifyContent:"space-between",marginBottom:"1rem",paddingBottom:"1rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"2rem",cursor:"pointer",color:"#999"},modalContent:{fontSize:"0.95rem"},modalRow:{marginBottom:"0.75rem",lineHeight:"1.6"},table:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",fontWeight:"600",fontSize:"0.9rem"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},noBookingRow:{background:"#f9f9f9",color:"#999"}};/*! * @kurkle/color v0.3.4 * https://github.com/kurkle/color#readme * (c) 2024 Jukka Kurkela * Released under the MIT License */function X_(n){return n+.5|0}const hg=(n,e,t)=>Math.max(Math.min(n,t),e);function Jw(n){return hg(X_(n*2.55),0,255)}function Tg(n){return hg(X_(n*255),0,255)}function vh(n){return hg(X_(n/2.55)/100,0,1)}function dO(n){return hg(X_(n*100),0,100)}const nd={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},uB=[..."0123456789ABCDEF"],LJ=n=>uB[n&15],NJ=n=>uB[(n&240)>>4]+uB[n&15],p2=n=>(n&240)>>4===(n&15),WJ=n=>p2(n.r)&&p2(n.g)&&p2(n.b)&&p2(n.a);function UJ(n){var e=n.length,t;return n[0]==="#"&&(e===4||e===5?t={r:255&nd[n[1]]*17,g:255&nd[n[2]]*17,b:255&nd[n[3]]*17,a:e===5?nd[n[4]]*17:255}:(e===7||e===9)&&(t={r:nd[n[1]]<<4|nd[n[2]],g:nd[n[3]]<<4|nd[n[4]],b:nd[n[5]]<<4|nd[n[6]],a:e===9?nd[n[7]]<<4|nd[n[8]]:255})),t}const HJ=(n,e)=>n<255?e(n):"";function qJ(n){var e=WJ(n)?LJ:NJ;return n?"#"+e(n.r)+e(n.g)+e(n.b)+HJ(n.a,e):void 0}const VJ=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function V9(n,e,t){const r=e*Math.min(t,1-t),i=(o,a=(o+n/30)%12)=>t-r*Math.max(Math.min(a-3,9-a,1),-1);return[i(0),i(8),i(4)]}function GJ(n,e,t){const r=(i,o=(i+n/60)%6)=>t-t*e*Math.max(Math.min(o,4-o,1),0);return[r(5),r(3),r(1)]}function KJ(n,e,t){const r=V9(n,1,.5);let i;for(e+t>1&&(i=1/(e+t),e*=i,t*=i),i=0;i<3;i++)r[i]*=1-e-t,r[i]+=e;return r}function XJ(n,e,t,r,i){return n===i?(e-t)/r+(e.5?u/(2-o-a):u/(o+a),d=XJ(t,r,i,u,o),d=d*60+.5),[d|0,c||0,l]}function C6(n,e,t,r){return(Array.isArray(e)?n(e[0],e[1],e[2]):n(e,t,r)).map(Tg)}function A6(n,e,t){return C6(V9,n,e,t)}function YJ(n,e,t){return C6(KJ,n,e,t)}function QJ(n,e,t){return C6(GJ,n,e,t)}function G9(n){return(n%360+360)%360}function $J(n){const e=VJ.exec(n);let t=255,r;if(!e)return;e[5]!==r&&(t=e[6]?Jw(+e[5]):Tg(+e[5]));const i=G9(+e[2]),o=+e[3]/100,a=+e[4]/100;return e[1]==="hwb"?r=YJ(i,o,a):e[1]==="hsv"?r=QJ(i,o,a):r=A6(i,o,a),{r:r[0],g:r[1],b:r[2],a:t}}function ZJ(n,e){var t=_6(n);t[0]=G9(t[0]+e),t=A6(t),n.r=t[0],n.g=t[1],n.b=t[2]}function JJ(n){if(!n)return;const e=_6(n),t=e[0],r=dO(e[1]),i=dO(e[2]);return n.a<255?`hsla(${t}, ${r}%, ${i}%, ${vh(n.a)})`:`hsl(${t}, ${r}%, ${i}%)`}const cO={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},uO={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};function eee(){const n={},e=Object.keys(uO),t=Object.keys(cO);let r,i,o,a,l;for(r=0;r>16&255,o>>8&255,o&255]}return n}let g2;function tee(n){g2||(g2=eee(),g2.transparent=[0,0,0,0]);const e=g2[n.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:e.length===4?e[3]:255}}const nee=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;function ree(n){const e=nee.exec(n);let t=255,r,i,o;if(e){if(e[7]!==r){const a=+e[7];t=e[8]?Jw(a):hg(a*255,0,255)}return r=+e[1],i=+e[3],o=+e[5],r=255&(e[2]?Jw(r):hg(r,0,255)),i=255&(e[4]?Jw(i):hg(i,0,255)),o=255&(e[6]?Jw(o):hg(o,0,255)),{r,g:i,b:o,a:t}}}function iee(n){return n&&(n.a<255?`rgba(${n.r}, ${n.g}, ${n.b}, ${vh(n.a)})`:`rgb(${n.r}, ${n.g}, ${n.b})`)}const oP=n=>n<=.0031308?n*12.92:Math.pow(n,1/2.4)*1.055-.055,cx=n=>n<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4);function see(n,e,t){const r=cx(vh(n.r)),i=cx(vh(n.g)),o=cx(vh(n.b));return{r:Tg(oP(r+t*(cx(vh(e.r))-r))),g:Tg(oP(i+t*(cx(vh(e.g))-i))),b:Tg(oP(o+t*(cx(vh(e.b))-o))),a:n.a+t*(e.a-n.a)}}function m2(n,e,t){if(n){let r=_6(n);r[e]=Math.max(0,Math.min(r[e]+r[e]*t,e===0?360:1)),r=A6(r),n.r=r[0],n.g=r[1],n.b=r[2]}}function K9(n,e){return n&&Object.assign(e||{},n)}function hO(n){var e={r:0,g:0,b:0,a:255};return Array.isArray(n)?n.length>=3&&(e={r:n[0],g:n[1],b:n[2],a:255},n.length>3&&(e.a=Tg(n[3]))):(e=K9(n,{r:0,g:0,b:0,a:1}),e.a=Tg(e.a)),e}function oee(n){return n.charAt(0)==="r"?ree(n):$J(n)}class Tj{constructor(e){if(e instanceof Tj)return e;const t=typeof e;let r;t==="object"?r=hO(e):t==="string"&&(r=UJ(e)||tee(e)||oee(e)),this._rgb=r,this._valid=!!r}get valid(){return this._valid}get rgb(){var e=K9(this._rgb);return e&&(e.a=vh(e.a)),e}set rgb(e){this._rgb=hO(e)}rgbString(){return this._valid?iee(this._rgb):void 0}hexString(){return this._valid?qJ(this._rgb):void 0}hslString(){return this._valid?JJ(this._rgb):void 0}mix(e,t){if(e){const r=this.rgb,i=e.rgb;let o;const a=t===o?.5:t,l=2*a-1,d=r.a-i.a,c=((l*d===-1?l:(l+d)/(1+l*d))+1)/2;o=1-c,r.r=255&c*r.r+o*i.r+.5,r.g=255&c*r.g+o*i.g+.5,r.b=255&c*r.b+o*i.b+.5,r.a=a*r.a+(1-a)*i.a,this.rgb=r}return this}interpolate(e,t){return e&&(this._rgb=see(this._rgb,e._rgb,t)),this}clone(){return new Tj(this.rgb)}alpha(e){return this._rgb.a=Tg(e),this}clearer(e){const t=this._rgb;return t.a*=1-e,this}greyscale(){const e=this._rgb,t=X_(e.r*.3+e.g*.59+e.b*.11);return e.r=e.g=e.b=t,this}opaquer(e){const t=this._rgb;return t.a*=1+e,this}negate(){const e=this._rgb;return e.r=255-e.r,e.g=255-e.g,e.b=255-e.b,this}lighten(e){return m2(this._rgb,2,e),this}darken(e){return m2(this._rgb,2,-e),this}saturate(e){return m2(this._rgb,1,e),this}desaturate(e){return m2(this._rgb,1,-e),this}rotate(e){return ZJ(this._rgb,e),this}}/*! * Chart.js v4.5.1 * https://www.chartjs.org * (c) 2025 Chart.js Contributors * Released under the MIT License */function ih(){}const aee=(()=>{let n=0;return()=>n++})();function Ur(n){return n==null}function ki(n){if(Array.isArray&&Array.isArray(n))return!0;const e=Object.prototype.toString.call(n);return e.slice(0,7)==="[object"&&e.slice(-6)==="Array]"}function Yn(n){return n!==null&&Object.prototype.toString.call(n)==="[object Object]"}function sl(n){return(typeof n=="number"||n instanceof Number)&&isFinite(+n)}function Hc(n,e){return sl(n)?n:e}function In(n,e){return typeof n>"u"?e:n}const lee=(n,e)=>typeof n=="string"&&n.endsWith("%")?parseFloat(n)/100:+n/e,X9=(n,e)=>typeof n=="string"&&n.endsWith("%")?parseFloat(n)/100*e:+n;function li(n,e,t){if(n&&typeof n.call=="function")return n.apply(t,e)}function Yr(n,e,t,r){let i,o,a;if(ki(n))for(o=n.length,i=0;in,x:n=>n.x,y:n=>n.y};function uee(n){const e=n.split("."),t=[];let r="";for(const i of e)r+=i,r.endsWith("\\")?r=r.slice(0,-1)+".":(t.push(r),r="");return t}function hee(n){const e=uee(n);return t=>{for(const r of e){if(r==="")break;t=t&&t[r]}return t}}function g0(n,e){return(fO[e]||(fO[e]=hee(e)))(n)}function T6(n){return n.charAt(0).toUpperCase()+n.slice(1)}const ol=n=>typeof n<"u",il=n=>typeof n=="function",pO=(n,e)=>{if(n.size!==e.size)return!1;for(const t of n)if(!e.has(t))return!1;return!0};function fee(n){return n.type==="mouseup"||n.type==="click"||n.type==="contextmenu"}const Or=Math.PI,Eo=2*Or,pee=Eo+Or,VA=Number.POSITIVE_INFINITY,F6=Or/180,Po=Or/2,jd=Or/4,GA=Or*2/3,Q9=Math.log10,zu=Math.sign;function HS(n,e,t){return Math.abs(n-e)i-o).pop(),e}function mee(n){return typeof n=="symbol"||typeof n=="object"&&n!==null&&!(Symbol.toPrimitive in n||"toString"in n||"valueOf"in n)}function m0(n){return!mee(n)&&!isNaN(parseFloat(n))&&isFinite(n)}function yee(n,e){const t=Math.round(n);return t-e<=n&&t+e>=n}function xee(n,e,t){let r,i,o;for(r=0,i=n.length;rd&&c=Math.min(e,t)-r&&n<=Math.max(e,t)+r}function D6(n,e,t){t=t||(a=>n[a]1;)o=i+r>>1,t(o)?i=o:r=o;return{lo:i,hi:r}}const vm=(n,e,t,r)=>D6(n,t,r?i=>{const o=n[i][e];return on[i][e]D6(n,t,r=>n[r][e]>=t);function See(n,e,t){let r=0,i=n.length;for(;rr&&n[i-1]>t;)i--;return r>0||i{const r="_onData"+T6(t),i=n[t];Object.defineProperty(n,t,{configurable:!0,enumerable:!1,value(...o){const a=i.apply(this,o);return n._chartjs.listeners.forEach(l=>{typeof l[r]=="function"&&l[r](...o)}),a}})})}function yO(n,e){const t=n._chartjs;if(!t)return;const r=t.listeners,i=r.indexOf(e);i!==-1&&r.splice(i,1),!(r.length>0)&&(Z9.forEach(o=>{delete n[o]}),delete n._chartjs)}function J9(n){const e=new Set(n);return e.size===n.length?n:Array.from(e)}const eU=function(){return typeof window>"u"?function(n){return n()}:window.requestAnimationFrame}();function tU(n,e){let t=[],r=!1;return function(...i){t=i,r||(r=!0,eU.call(window,()=>{r=!1,n.apply(e,t)}))}}function kee(n,e){let t;return function(...r){return e?(clearTimeout(t),t=setTimeout(n,e,r)):n.apply(this,r),e}}const E6=n=>n==="start"?"left":n==="end"?"right":"center",ta=(n,e,t)=>n==="start"?e:n==="end"?t:(e+t)/2,_ee=(n,e,t,r)=>n===(r?"left":"right")?t:n==="center"?(e+t)/2:e;function Cee(n,e,t){const r=e.length;let i=0,o=r;if(n._sorted){const{iScale:a,vScale:l,_parsed:d}=n,c=n.dataset&&n.dataset.options?n.dataset.options.spanGaps:null,u=a.axis,{min:f,max:p,minDefined:g,maxDefined:m}=a.getUserBounds();if(g){if(i=Math.min(vm(d,u,f).lo,t?r:vm(e,u,a.getPixelForValue(f)).lo),c){const y=d.slice(0,i+1).reverse().findIndex(v=>!Ur(v[l.axis]));i-=Math.max(0,y)}i=Wl(i,0,r-1)}if(m){let y=Math.max(vm(d,a.axis,p,!0).hi+1,t?0:vm(e,u,a.getPixelForValue(p),!0).hi+1);if(c){const v=d.slice(y-1).findIndex(x=>!Ur(x[l.axis]));y+=Math.max(0,v)}o=Wl(y,i,r)-i}else o=r-i}return{start:i,count:o}}function Aee(n){const{xScale:e,yScale:t,_scaleRanges:r}=n,i={xmin:e.min,xmax:e.max,ymin:t.min,ymax:t.max};if(!r)return n._scaleRanges=i,!0;const o=r.xmin!==e.min||r.xmax!==e.max||r.ymin!==t.min||r.ymax!==t.max;return Object.assign(r,i),o}const y2=n=>n===0||n===1,xO=(n,e,t)=>-(Math.pow(2,10*(n-=1))*Math.sin((n-e)*Eo/t)),bO=(n,e,t)=>Math.pow(2,-10*n)*Math.sin((n-e)*Eo/t)+1,qS={linear:n=>n,easeInQuad:n=>n*n,easeOutQuad:n=>-n*(n-2),easeInOutQuad:n=>(n/=.5)<1?.5*n*n:-.5*(--n*(n-2)-1),easeInCubic:n=>n*n*n,easeOutCubic:n=>(n-=1)*n*n+1,easeInOutCubic:n=>(n/=.5)<1?.5*n*n*n:.5*((n-=2)*n*n+2),easeInQuart:n=>n*n*n*n,easeOutQuart:n=>-((n-=1)*n*n*n-1),easeInOutQuart:n=>(n/=.5)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2),easeInQuint:n=>n*n*n*n*n,easeOutQuint:n=>(n-=1)*n*n*n*n+1,easeInOutQuint:n=>(n/=.5)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2),easeInSine:n=>-Math.cos(n*Po)+1,easeOutSine:n=>Math.sin(n*Po),easeInOutSine:n=>-.5*(Math.cos(Or*n)-1),easeInExpo:n=>n===0?0:Math.pow(2,10*(n-1)),easeOutExpo:n=>n===1?1:-Math.pow(2,-10*n)+1,easeInOutExpo:n=>y2(n)?n:n<.5?.5*Math.pow(2,10*(n*2-1)):.5*(-Math.pow(2,-10*(n*2-1))+2),easeInCirc:n=>n>=1?n:-(Math.sqrt(1-n*n)-1),easeOutCirc:n=>Math.sqrt(1-(n-=1)*n),easeInOutCirc:n=>(n/=.5)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1),easeInElastic:n=>y2(n)?n:xO(n,.075,.3),easeOutElastic:n=>y2(n)?n:bO(n,.075,.3),easeInOutElastic(n){return y2(n)?n:n<.5?.5*xO(n*2,.1125,.45):.5+.5*bO(n*2-1,.1125,.45)},easeInBack(n){return n*n*((1.70158+1)*n-1.70158)},easeOutBack(n){return(n-=1)*n*((1.70158+1)*n+1.70158)+1},easeInOutBack(n){let e=1.70158;return(n/=.5)<1?.5*(n*n*(((e*=1.525)+1)*n-e)):.5*((n-=2)*n*(((e*=1.525)+1)*n+e)+2)},easeInBounce:n=>1-qS.easeOutBounce(1-n),easeOutBounce(n){return n<1/2.75?7.5625*n*n:n<2/2.75?7.5625*(n-=1.5/2.75)*n+.75:n<2.5/2.75?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375},easeInOutBounce:n=>n<.5?qS.easeInBounce(n*2)*.5:qS.easeOutBounce(n*2-1)*.5+.5};function P6(n){if(n&&typeof n=="object"){const e=n.toString();return e==="[object CanvasPattern]"||e==="[object CanvasGradient]"}return!1}function vO(n){return P6(n)?n:new Tj(n)}function aP(n){return P6(n)?n:new Tj(n).saturate(.5).darken(.1).hexString()}const Tee=["x","y","borderWidth","radius","tension"],Fee=["color","borderColor","backgroundColor"];function Dee(n){n.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),n.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:e=>e!=="onProgress"&&e!=="onComplete"&&e!=="fn"}),n.set("animations",{colors:{type:"color",properties:Fee},numbers:{type:"number",properties:Tee}}),n.describe("animations",{_fallback:"animation"}),n.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:e=>e|0}}}})}function Eee(n){n.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}const wO=new Map;function Pee(n,e){e=e||{};const t=n+JSON.stringify(e);let r=wO.get(t);return r||(r=new Intl.NumberFormat(n,e),wO.set(t,r)),r}function R6(n,e,t){return Pee(e,t).format(n)}const Ree={values(n){return ki(n)?n:""+n},numeric(n,e,t){if(n===0)return"0";const r=this.chart.options.locale;let i,o=n;if(t.length>1){const c=Math.max(Math.abs(t[0].value),Math.abs(t[t.length-1].value));(c<1e-4||c>1e15)&&(i="scientific"),o=Bee(n,t)}const a=Q9(Math.abs(o)),l=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),d={notation:i,minimumFractionDigits:l,maximumFractionDigits:l};return Object.assign(d,this.options.ticks.format),R6(n,r,d)}};function Bee(n,e){let t=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;return Math.abs(t)>=1&&n!==Math.floor(n)&&(t=n-Math.floor(n)),t}var nU={formatters:Ree};function Iee(n){n.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(e,t)=>t.lineWidth,tickColor:(e,t)=>t.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:nU.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),n.route("scale.ticks","color","","color"),n.route("scale.grid","color","","borderColor"),n.route("scale.border","color","","borderColor"),n.route("scale.title","color","","color"),n.describe("scale",{_fallback:!1,_scriptable:e=>!e.startsWith("before")&&!e.startsWith("after")&&e!=="callback"&&e!=="parser",_indexable:e=>e!=="borderDash"&&e!=="tickBorderDash"&&e!=="dash"}),n.describe("scales",{_fallback:"scale"}),n.describe("scale.ticks",{_scriptable:e=>e!=="backdropPadding"&&e!=="callback",_indexable:e=>e!=="backdropPadding"})}const y0=Object.create(null),fB=Object.create(null);function VS(n,e){if(!e)return n;const t=e.split(".");for(let r=0,i=t.length;rr.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(r,i)=>aP(i.backgroundColor),this.hoverBorderColor=(r,i)=>aP(i.borderColor),this.hoverColor=(r,i)=>aP(i.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(e),this.apply(t)}set(e,t){return lP(this,e,t)}get(e){return VS(this,e)}describe(e,t){return lP(fB,e,t)}override(e,t){return lP(y0,e,t)}route(e,t,r,i){const o=VS(this,e),a=VS(this,r),l="_"+t;Object.defineProperties(o,{[l]:{value:o[t],writable:!0},[t]:{enumerable:!0,get(){const d=this[l],c=a[i];return Yn(d)?Object.assign({},c,d):In(d,c)},set(d){this[l]=d}}})}apply(e){e.forEach(t=>t(this))}}var hs=new Mee({_scriptable:n=>!n.startsWith("on"),_indexable:n=>n!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[Dee,Eee,Iee]);function zee(n){return!n||Ur(n.size)||Ur(n.family)?null:(n.style?n.style+" ":"")+(n.weight?n.weight+" ":"")+n.size+"px "+n.family}function SO(n,e,t,r,i){let o=e[i];return o||(o=e[i]=n.measureText(i).width,t.push(i)),o>r&&(r=o),r}function tm(n,e,t){const r=n.currentDevicePixelRatio,i=t!==0?Math.max(t/2,.5):0;return Math.round((e-i)*r)/r+i}function jO(n,e){!e&&!n||(e=e||n.getContext("2d"),e.save(),e.resetTransform(),e.clearRect(0,0,n.width,n.height),e.restore())}function pB(n,e,t,r){rU(n,e,t,r,null)}function rU(n,e,t,r,i){let o,a,l,d,c,u,f,p;const g=e.pointStyle,m=e.rotation,y=e.radius;let v=(m||0)*F6;if(g&&typeof g=="object"&&(o=g.toString(),o==="[object HTMLImageElement]"||o==="[object HTMLCanvasElement]")){n.save(),n.translate(t,r),n.rotate(v),n.drawImage(g,-g.width/2,-g.height/2,g.width,g.height),n.restore();return}if(!(isNaN(y)||y<=0)){switch(n.beginPath(),g){default:i?n.ellipse(t,r,i/2,y,0,0,Eo):n.arc(t,r,y,0,Eo),n.closePath();break;case"triangle":u=i?i/2:y,n.moveTo(t+Math.sin(v)*u,r-Math.cos(v)*y),v+=GA,n.lineTo(t+Math.sin(v)*u,r-Math.cos(v)*y),v+=GA,n.lineTo(t+Math.sin(v)*u,r-Math.cos(v)*y),n.closePath();break;case"rectRounded":c=y*.516,d=y-c,a=Math.cos(v+jd)*d,f=Math.cos(v+jd)*(i?i/2-c:d),l=Math.sin(v+jd)*d,p=Math.sin(v+jd)*(i?i/2-c:d),n.arc(t-f,r-l,c,v-Or,v-Po),n.arc(t+p,r-a,c,v-Po,v),n.arc(t+f,r+l,c,v,v+Po),n.arc(t-p,r+a,c,v+Po,v+Or),n.closePath();break;case"rect":if(!m){d=Math.SQRT1_2*y,u=i?i/2:d,n.rect(t-u,r-d,2*u,2*d);break}v+=jd;case"rectRot":f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+p,r-a),n.lineTo(t+f,r+l),n.lineTo(t-p,r+a),n.closePath();break;case"crossRot":v+=jd;case"cross":f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+f,r+l),n.moveTo(t+p,r-a),n.lineTo(t-p,r+a);break;case"star":f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+f,r+l),n.moveTo(t+p,r-a),n.lineTo(t-p,r+a),v+=jd,f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+f,r+l),n.moveTo(t+p,r-a),n.lineTo(t-p,r+a);break;case"line":a=i?i/2:Math.cos(v)*y,l=Math.sin(v)*y,n.moveTo(t-a,r-l),n.lineTo(t+a,r+l);break;case"dash":n.moveTo(t,r),n.lineTo(t+Math.cos(v)*(i?i/2:y),r+Math.sin(v)*y);break;case!1:n.closePath();break}n.fill(),e.borderWidth>0&&n.stroke()}}function Dj(n,e,t){return t=t||.5,!e||n&&n.x>e.left-t&&n.xe.top-t&&n.y0&&o.strokeColor!=="";let d,c;for(n.save(),n.font=i.string,Nee(n,o),d=0;d+n||0;function iU(n,e){const t={},r=Yn(e),i=r?Object.keys(e):e,o=Yn(n)?r?a=>In(n[a],n[e[a]]):a=>n[a]:()=>n;for(const a of i)t[a]=Gee(o(a));return t}function sU(n){return iU(n,{top:"y",right:"x",bottom:"y",left:"x"})}function o0(n){return iU(n,["topLeft","topRight","bottomLeft","bottomRight"])}function sa(n){const e=sU(n);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Us(n,e){n=n||{},e=e||hs.font;let t=In(n.size,e.size);typeof t=="string"&&(t=parseInt(t,10));let r=In(n.style,e.style);r&&!(""+r).match(qee)&&(console.warn('Invalid font style specified: "'+r+'"'),r=void 0);const i={family:In(n.family,e.family),lineHeight:Vee(In(n.lineHeight,e.lineHeight),t),size:t,style:r,weight:In(n.weight,e.weight),string:""};return i.string=zee(i),i}function x2(n,e,t,r){let i,o,a;for(i=0,o=n.length;it&&l===0?0:l+d;return{min:a(r,-Math.abs(o)),max:a(i,o)}}function P0(n,e){return Object.assign(Object.create(n),e)}function B6(n,e=[""],t,r,i=()=>n[0]){const o=t||n;typeof r>"u"&&(r=dU("_fallback",n));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:n,_rootScopes:o,_fallback:r,_getTarget:i,override:l=>B6([l,...n],e,o,r)};return new Proxy(a,{deleteProperty(l,d){return delete l[d],delete l._keys,delete n[0][d],!0},get(l,d){return aU(l,d,()=>tte(d,e,n,l))},getOwnPropertyDescriptor(l,d){return Reflect.getOwnPropertyDescriptor(l._scopes[0],d)},getPrototypeOf(){return Reflect.getPrototypeOf(n[0])},has(l,d){return _O(l).includes(d)},ownKeys(l){return _O(l)},set(l,d,c){const u=l._storage||(l._storage=i());return l[d]=u[d]=c,delete l._keys,!0}})}function i1(n,e,t,r){const i={_cacheable:!1,_proxy:n,_context:e,_subProxy:t,_stack:new Set,_descriptors:oU(n,r),setContext:o=>i1(n,o,t,r),override:o=>i1(n.override(o),e,t,r)};return new Proxy(i,{deleteProperty(o,a){return delete o[a],delete n[a],!0},get(o,a,l){return aU(o,a,()=>Yee(o,a,l))},getOwnPropertyDescriptor(o,a){return o._descriptors.allKeys?Reflect.has(n,a)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(n,a)},getPrototypeOf(){return Reflect.getPrototypeOf(n)},has(o,a){return Reflect.has(n,a)},ownKeys(){return Reflect.ownKeys(n)},set(o,a,l){return n[a]=l,delete o[a],!0}})}function oU(n,e={scriptable:!0,indexable:!0}){const{_scriptable:t=e.scriptable,_indexable:r=e.indexable,_allKeys:i=e.allKeys}=n;return{allKeys:i,scriptable:t,indexable:r,isScriptable:il(t)?t:()=>t,isIndexable:il(r)?r:()=>r}}const Xee=(n,e)=>n?n+T6(e):e,I6=(n,e)=>Yn(e)&&n!=="adapters"&&(Object.getPrototypeOf(e)===null||e.constructor===Object);function aU(n,e,t){if(Object.prototype.hasOwnProperty.call(n,e)||e==="constructor")return n[e];const r=t();return n[e]=r,r}function Yee(n,e,t){const{_proxy:r,_context:i,_subProxy:o,_descriptors:a}=n;let l=r[e];return il(l)&&a.isScriptable(e)&&(l=Qee(e,l,n,t)),ki(l)&&l.length&&(l=$ee(e,l,n,a.isIndexable)),I6(e,l)&&(l=i1(l,i,o&&o[e],a)),l}function Qee(n,e,t,r){const{_proxy:i,_context:o,_subProxy:a,_stack:l}=t;if(l.has(n))throw new Error("Recursion detected: "+Array.from(l).join("->")+"->"+n);l.add(n);let d=e(o,a||r);return l.delete(n),I6(n,d)&&(d=M6(i._scopes,i,n,d)),d}function $ee(n,e,t,r){const{_proxy:i,_context:o,_subProxy:a,_descriptors:l}=t;if(typeof o.index<"u"&&r(n))return e[o.index%e.length];if(Yn(e[0])){const d=e,c=i._scopes.filter(u=>u!==d);e=[];for(const u of d){const f=M6(c,i,n,u);e.push(i1(f,o,a&&a[n],l))}}return e}function lU(n,e,t){return il(n)?n(e,t):n}const Zee=(n,e)=>n===!0?e:typeof n=="string"?g0(e,n):void 0;function Jee(n,e,t,r,i){for(const o of e){const a=Zee(t,o);if(a){n.add(a);const l=lU(a._fallback,t,i);if(typeof l<"u"&&l!==t&&l!==r)return l}else if(a===!1&&typeof r<"u"&&t!==r)return null}return!1}function M6(n,e,t,r){const i=e._rootScopes,o=lU(e._fallback,t,r),a=[...n,...i],l=new Set;l.add(r);let d=kO(l,a,t,o||t,r);return d===null||typeof o<"u"&&o!==t&&(d=kO(l,a,o,d,r),d===null)?!1:B6(Array.from(l),[""],i,o,()=>ete(e,t,r))}function kO(n,e,t,r,i){for(;t;)t=Jee(n,e,t,r,i);return t}function ete(n,e,t){const r=n._getTarget();e in r||(r[e]={});const i=r[e];return ki(i)&&Yn(t)?t:i||{}}function tte(n,e,t,r){let i;for(const o of e)if(i=dU(Xee(o,n),t),typeof i<"u")return I6(n,i)?M6(t,r,n,i):i}function dU(n,e){for(const t of e){if(!t)continue;const r=t[n];if(typeof r<"u")return r}}function _O(n){let e=n._keys;return e||(e=n._keys=nte(n._scopes)),e}function nte(n){const e=new Set;for(const t of n)for(const r of Object.keys(t).filter(i=>!i.startsWith("_")))e.add(r);return Array.from(e)}const rte=Number.EPSILON||1e-14,s1=(n,e)=>en==="x"?"y":"x";function ite(n,e,t,r){const i=n.skip?e:n,o=e,a=t.skip?e:t,l=r1(o,i),d=r1(a,o);let c=l/(l+d),u=d/(l+d);c=isNaN(c)?0:c,u=isNaN(u)?0:u;const f=r*c,p=r*u;return{previous:{x:o.x-f*(a.x-i.x),y:o.y-f*(a.y-i.y)},next:{x:o.x+p*(a.x-i.x),y:o.y+p*(a.y-i.y)}}}function ste(n,e,t){const r=n.length;let i,o,a,l,d,c=s1(n,0);for(let u=0;u!c.skip)),e.cubicInterpolationMode==="monotone")ate(n,i);else{let c=r?n[n.length-1]:n[0];for(o=0,a=n.length;on.ownerDocument.defaultView.getComputedStyle(n,null);function cte(n,e){return jF(n).getPropertyValue(e)}const ute=["top","right","bottom","left"];function a0(n,e,t){const r={};t=t?"-"+t:"";for(let i=0;i<4;i++){const o=ute[i];r[o]=parseFloat(n[e+"-"+o+t])||0}return r.width=r.left+r.right,r.height=r.top+r.bottom,r}const hte=(n,e,t)=>(n>0||e>0)&&(!t||!t.shadowRoot);function fte(n,e){const t=n.touches,r=t&&t.length?t[0]:n,{offsetX:i,offsetY:o}=r;let a=!1,l,d;if(hte(i,o,n.target))l=i,d=o;else{const c=e.getBoundingClientRect();l=r.clientX-c.left,d=r.clientY-c.top,a=!0}return{x:l,y:d,box:a}}function om(n,e){if("native"in n)return n;const{canvas:t,currentDevicePixelRatio:r}=e,i=jF(t),o=i.boxSizing==="border-box",a=a0(i,"padding"),l=a0(i,"border","width"),{x:d,y:c,box:u}=fte(n,t),f=a.left+(u&&l.left),p=a.top+(u&&l.top);let{width:g,height:m}=e;return o&&(g-=a.width+l.width,m-=a.height+l.height),{x:Math.round((d-f)/g*t.width/r),y:Math.round((c-p)/m*t.height/r)}}function pte(n,e,t){let r,i;if(e===void 0||t===void 0){const o=n&&O6(n);if(!o)e=n.clientWidth,t=n.clientHeight;else{const a=o.getBoundingClientRect(),l=jF(o),d=a0(l,"border","width"),c=a0(l,"padding");e=a.width-c.width-d.width,t=a.height-c.height-d.height,r=XA(l.maxWidth,o,"clientWidth"),i=XA(l.maxHeight,o,"clientHeight")}}return{width:e,height:t,maxWidth:r||VA,maxHeight:i||VA}}const fg=n=>Math.round(n*10)/10;function gte(n,e,t,r){const i=jF(n),o=a0(i,"margin"),a=XA(i.maxWidth,n,"clientWidth")||VA,l=XA(i.maxHeight,n,"clientHeight")||VA,d=pte(n,e,t);let{width:c,height:u}=d;if(i.boxSizing==="content-box"){const p=a0(i,"border","width"),g=a0(i,"padding");c-=g.width+p.width,u-=g.height+p.height}return c=Math.max(0,c-o.width),u=Math.max(0,r?c/r:u-o.height),c=fg(Math.min(c,a,d.maxWidth)),u=fg(Math.min(u,l,d.maxHeight)),c&&!u&&(u=fg(c/2)),(e!==void 0||t!==void 0)&&r&&d.height&&u>d.height&&(u=d.height,c=fg(Math.floor(u*r))),{width:c,height:u}}function CO(n,e,t){const r=e||1,i=fg(n.height*r),o=fg(n.width*r);n.height=fg(n.height),n.width=fg(n.width);const a=n.canvas;return a.style&&(t||!a.style.height&&!a.style.width)&&(a.style.height=`${n.height}px`,a.style.width=`${n.width}px`),n.currentDevicePixelRatio!==r||a.height!==i||a.width!==o?(n.currentDevicePixelRatio=r,a.height=i,a.width=o,n.ctx.setTransform(r,0,0,r,0,0),!0):!1}const mte=function(){let n=!1;try{const e={get passive(){return n=!0,!1}};z6()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch{}return n}();function AO(n,e){const t=cte(n,e),r=t&&t.match(/^(\d+)(\.\d+)?px$/);return r?+r[1]:void 0}function am(n,e,t,r){return{x:n.x+t*(e.x-n.x),y:n.y+t*(e.y-n.y)}}function yte(n,e,t,r){return{x:n.x+t*(e.x-n.x),y:r==="middle"?t<.5?n.y:e.y:r==="after"?t<1?n.y:e.y:t>0?e.y:n.y}}function xte(n,e,t,r){const i={x:n.cp2x,y:n.cp2y},o={x:e.cp1x,y:e.cp1y},a=am(n,i,t),l=am(i,o,t),d=am(o,e,t),c=am(a,l,t),u=am(l,d,t);return am(c,u,t)}const bte=function(n,e){return{x(t){return n+n+e-t},setWidth(t){e=t},textAlign(t){return t==="center"?t:t==="right"?"left":"right"},xPlus(t,r){return t-r},leftForLtr(t,r){return t-r}}},vte=function(){return{x(n){return n},setWidth(n){},textAlign(n){return n},xPlus(n,e){return n+e},leftForLtr(n,e){return n}}};function ib(n,e,t){return n?bte(e,t):vte()}function uU(n,e){let t,r;(e==="ltr"||e==="rtl")&&(t=n.canvas.style,r=[t.getPropertyValue("direction"),t.getPropertyPriority("direction")],t.setProperty("direction",e,"important"),n.prevTextDirection=r)}function hU(n,e){e!==void 0&&(delete n.prevTextDirection,n.canvas.style.setProperty("direction",e[0],e[1]))}function fU(n){return n==="angle"?{between:KA,compare:bee,normalize:Yf}:{between:bm,compare:(e,t)=>e-t,normalize:e=>e}}function TO({start:n,end:e,count:t,loop:r,style:i}){return{start:n%t,end:e%t,loop:r&&(e-n+1)%t===0,style:i}}function wte(n,e,t){const{property:r,start:i,end:o}=t,{between:a,normalize:l}=fU(r),d=e.length;let{start:c,end:u,loop:f}=n,p,g;if(f){for(c+=d,u+=d,p=0,g=d;pd(i,S,x)&&l(i,S)!==0,b=()=>l(o,x)===0||d(o,S,x),C=()=>y||_(),T=()=>!y||b();for(let F=u,A=u;F<=f;++F)w=e[F%a],!w.skip&&(x=c(w[r]),x!==S&&(y=d(x,i,o),v===null&&C()&&(v=l(x,i)===0?F:A),v!==null&&T()&&(m.push(TO({start:v,end:F,loop:p,count:a,style:g})),v=null),A=F,S=x));return v!==null&&m.push(TO({start:v,end:f,loop:p,count:a,style:g})),m}function jte(n,e){const t=[],r=n.segments;for(let i=0;ii&&n[o%e].skip;)o--;return o%=e,{start:i,end:o}}function _te(n,e,t,r){const i=n.length,o=[];let a=e,l=n[e],d;for(d=e+1;d<=t;++d){const c=n[d%i];c.skip||c.stop?l.skip||(r=!1,o.push({start:e%i,end:(d-1)%i,loop:r}),e=a=c.stop?d:null):(a=d,l.skip&&(e=d)),l=c}return a!==null&&o.push({start:e%i,end:a%i,loop:r}),o}function Cte(n,e){const t=n.points,r=n.options.spanGaps,i=t.length;if(!i)return[];const o=!!n._loop,{start:a,end:l}=kte(t,i,o,r);if(r===!0)return FO(n,[{start:a,end:l,loop:o}],t,e);const d=ll({chart:e,initial:t.initial,numSteps:a,currentStep:Math.min(r-t.start,a)}))}_refresh(){this._request||(this._running=!0,this._request=eU.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(e=Date.now()){let t=0;this._charts.forEach((r,i)=>{if(!r.running||!r.items.length)return;const o=r.items;let a=o.length-1,l=!1,d;for(;a>=0;--a)d=o[a],d._active?(d._total>r.duration&&(r.duration=d._total),d.tick(e),l=!0):(o[a]=o[o.length-1],o.pop());l&&(i.draw(),this._notify(i,r,e,"progress")),o.length||(r.running=!1,this._notify(i,r,e,"complete"),r.initial=!1),t+=o.length}),this._lastDate=e,t===0&&(this._running=!1)}_getAnims(e){const t=this._charts;let r=t.get(e);return r||(r={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},t.set(e,r)),r}listen(e,t,r){this._getAnims(e).listeners[t].push(r)}add(e,t){!t||!t.length||this._getAnims(e).items.push(...t)}has(e){return this._getAnims(e).items.length>0}start(e){const t=this._charts.get(e);t&&(t.running=!0,t.start=Date.now(),t.duration=t.items.reduce((r,i)=>Math.max(r,i._duration),0),this._refresh())}running(e){if(!this._running)return!1;const t=this._charts.get(e);return!(!t||!t.running||!t.items.length)}stop(e){const t=this._charts.get(e);if(!t||!t.items.length)return;const r=t.items;let i=r.length-1;for(;i>=0;--i)r[i].cancel();t.items=[],this._notify(e,t,Date.now(),"complete")}remove(e){return this._charts.delete(e)}}var ch=new Ete;const EO="transparent",Pte={boolean(n,e,t){return t>.5?e:n},color(n,e,t){const r=vO(n||EO),i=r.valid&&vO(e||EO);return i&&i.valid?i.mix(r,t).hexString():e},number(n,e,t){return n+(e-n)*t}};class Rte{constructor(e,t,r,i){const o=t[r];i=x2([e.to,i,o,e.from]);const a=x2([e.from,o,i]);this._active=!0,this._fn=e.fn||Pte[e.type||typeof a],this._easing=qS[e.easing]||qS.linear,this._start=Math.floor(Date.now()+(e.delay||0)),this._duration=this._total=Math.floor(e.duration),this._loop=!!e.loop,this._target=t,this._prop=r,this._from=a,this._to=i,this._promises=void 0}active(){return this._active}update(e,t,r){if(this._active){this._notify(!1);const i=this._target[this._prop],o=r-this._start,a=this._duration-o;this._start=r,this._duration=Math.floor(Math.max(a,e.duration)),this._total+=o,this._loop=!!e.loop,this._to=x2([e.to,t,i,e.from]),this._from=x2([e.from,i,t])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(e){const t=e-this._start,r=this._duration,i=this._prop,o=this._from,a=this._loop,l=this._to;let d;if(this._active=o!==l&&(a||t1?2-d:d,d=this._easing(Math.min(1,Math.max(0,d))),this._target[i]=this._fn(o,l,d)}wait(){const e=this._promises||(this._promises=[]);return new Promise((t,r)=>{e.push({res:t,rej:r})})}_notify(e){const t=e?"res":"rej",r=this._promises||[];for(let i=0;i{const o=e[i];if(!Yn(o))return;const a={};for(const l of t)a[l]=o[l];(ki(o.properties)&&o.properties||[i]).forEach(l=>{(l===i||!r.has(l))&&r.set(l,a)})})}_animateOptions(e,t){const r=t.options,i=Ite(e,r);if(!i)return[];const o=this._createAnimations(i,r);return r.$shared&&Bte(e.options.$animations,r).then(()=>{e.options=r},()=>{}),o}_createAnimations(e,t){const r=this._properties,i=[],o=e.$animations||(e.$animations={}),a=Object.keys(t),l=Date.now();let d;for(d=a.length-1;d>=0;--d){const c=a[d];if(c.charAt(0)==="$")continue;if(c==="options"){i.push(...this._animateOptions(e,t));continue}const u=t[c];let f=o[c];const p=r.get(c);if(f)if(p&&f.active()){f.update(p,u,l);continue}else f.cancel();if(!p||!p.duration){e[c]=u;continue}o[c]=f=new Rte(p,e,c,u),i.push(f)}return i}update(e,t){if(this._properties.size===0){Object.assign(e,t);return}const r=this._createAnimations(e,t);if(r.length)return ch.add(this._chart,r),!0}}function Bte(n,e){const t=[],r=Object.keys(e);for(let i=0;i0||!t&&o<0)return i.index}return null}function IO(n,e){const{chart:t,_cachedMeta:r}=n,i=t._stacks||(t._stacks={}),{iScale:o,vScale:a,index:l}=r,d=o.axis,c=a.axis,u=Lte(o,a,r),f=e.length;let p;for(let g=0;gt[r].axis===e).shift()}function Ute(n,e){return P0(n,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}function Hte(n,e,t){return P0(n,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:t,index:e,mode:"default",type:"data"})}function Tw(n,e){const t=n.controller.index,r=n.vScale&&n.vScale.axis;if(r){e=e||n._parsed;for(const i of e){const o=i._stacks;if(!o||o[r]===void 0||o[r][t]===void 0)return;delete o[r][t],o[r]._visualValues!==void 0&&o[r]._visualValues[t]!==void 0&&delete o[r]._visualValues[t]}}}const uP=n=>n==="reset"||n==="none",MO=(n,e)=>e?n:Object.assign({},n),qte=(n,e,t)=>n&&!e.hidden&&e._stacked&&{keys:pU(t,!0),values:null};class l0{constructor(e,t){this.chart=e,this._ctx=e.ctx,this.index=t,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const e=this._cachedMeta;this.configure(),this.linkScales(),e._stacked=dP(e.vScale,e),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(e){this.index!==e&&Tw(this._cachedMeta),this.index=e}linkScales(){const e=this.chart,t=this._cachedMeta,r=this.getDataset(),i=(f,p,g,m)=>f==="x"?p:f==="r"?m:g,o=t.xAxisID=In(r.xAxisID,cP(e,"x")),a=t.yAxisID=In(r.yAxisID,cP(e,"y")),l=t.rAxisID=In(r.rAxisID,cP(e,"r")),d=t.indexAxis,c=t.iAxisID=i(d,o,a,l),u=t.vAxisID=i(d,a,o,l);t.xScale=this.getScaleForId(o),t.yScale=this.getScaleForId(a),t.rScale=this.getScaleForId(l),t.iScale=this.getScaleForId(c),t.vScale=this.getScaleForId(u)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(e){return this.chart.scales[e]}_getOtherScale(e){const t=this._cachedMeta;return e===t.iScale?t.vScale:t.iScale}reset(){this._update("reset")}_destroy(){const e=this._cachedMeta;this._data&&yO(this._data,this),e._stacked&&Tw(e)}_dataCheck(){const e=this.getDataset(),t=e.data||(e.data=[]),r=this._data;if(Yn(t)){const i=this._cachedMeta;this._data=Ote(t,i)}else if(r!==t){if(r){yO(r,this);const i=this._cachedMeta;Tw(i),i._parsed=[]}t&&Object.isExtensible(t)&&jee(t,this),this._syncList=[],this._data=t}}addElements(){const e=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(e.dataset=new this.datasetElementType)}buildOrUpdateElements(e){const t=this._cachedMeta,r=this.getDataset();let i=!1;this._dataCheck();const o=t._stacked;t._stacked=dP(t.vScale,t),t.stack!==r.stack&&(i=!0,Tw(t),t.stack=r.stack),this._resyncElements(e),(i||o!==t._stacked)&&(IO(this,t._parsed),t._stacked=dP(t.vScale,t))}configure(){const e=this.chart.config,t=e.datasetScopeKeys(this._type),r=e.getOptionScopes(this.getDataset(),t,!0);this.options=e.createResolver(r,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(e,t){const{_cachedMeta:r,_data:i}=this,{iScale:o,_stacked:a}=r,l=o.axis;let d=e===0&&t===i.length?!0:r._sorted,c=e>0&&r._parsed[e-1],u,f,p;if(this._parsing===!1)r._parsed=i,r._sorted=!0,p=i;else{ki(i[e])?p=this.parseArrayData(r,i,e,t):Yn(i[e])?p=this.parseObjectData(r,i,e,t):p=this.parsePrimitiveData(r,i,e,t);const g=()=>f[l]===null||c&&f[l]y||f=0;--p)if(!m()){this.updateRangeFromParsed(c,e,g,d);break}}return c}getAllParsedValues(e){const t=this._cachedMeta._parsed,r=[];let i,o,a;for(i=0,o=t.length;i=0&&ethis.getContext(r,i,t),y=c.resolveNamedOptions(p,g,m,f);return y.$shared&&(y.$shared=d,o[a]=Object.freeze(MO(y,d))),y}_resolveAnimations(e,t,r){const i=this.chart,o=this._cachedDataOpts,a=`animation-${t}`,l=o[a];if(l)return l;let d;if(i.options.animation!==!1){const u=this.chart.config,f=u.datasetAnimationScopeKeys(this._type,t),p=u.getOptionScopes(this.getDataset(),f);d=u.createResolver(p,this.getContext(e,r,t))}const c=new L6(i,d&&d.animations);return d&&d._cacheable&&(o[a]=Object.freeze(c)),c}getSharedOptions(e){if(e.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},e))}includeOptions(e,t){return!t||uP(e)||this.chart._animationsDisabled}_getSharedOptions(e,t){const r=this.resolveDataElementOptions(e,t),i=this._sharedOptions,o=this.getSharedOptions(r),a=this.includeOptions(t,o)||o!==i;return this.updateSharedOptions(o,t,r),{sharedOptions:o,includeOptions:a}}updateElement(e,t,r,i){uP(i)?Object.assign(e,r):this._resolveAnimations(t,i).update(e,r)}updateSharedOptions(e,t,r){e&&!uP(t)&&this._resolveAnimations(void 0,t).update(e,r)}_setStyle(e,t,r,i){e.active=i;const o=this.getStyle(t,i);this._resolveAnimations(t,r,i).update(e,{options:!i&&this.getSharedOptions(o)||o})}removeHoverStyle(e,t,r){this._setStyle(e,r,"active",!1)}setHoverStyle(e,t,r){this._setStyle(e,r,"active",!0)}_removeDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!1)}_setDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!0)}_resyncElements(e){const t=this._data,r=this._cachedMeta.data;for(const[l,d,c]of this._syncList)this[l](d,c);this._syncList=[];const i=r.length,o=t.length,a=Math.min(o,i);a&&this.parse(0,a),o>i?this._insertElements(i,o-i,e):o{for(c.length+=t,l=c.length-1;l>=a;l--)c[l]=c[l-t]};for(d(o),l=e;li-o))}return n._cache.$bar}function Gte(n){const e=n.iScale,t=Vte(e,n.type);let r=e._length,i,o,a,l;const d=()=>{a===32767||a===-32768||(ol(l)&&(r=Math.min(r,Math.abs(a-l)||r)),l=a)};for(i=0,o=t.length;i0?i[n-1]:null,l=nMath.abs(l)&&(d=l,c=a),e[t.axis]=c,e._custom={barStart:d,barEnd:c,start:i,end:o,min:a,max:l}}function gU(n,e,t,r){return ki(n)?Yte(n,e,t,r):e[t.axis]=t.parse(n,r),e}function zO(n,e,t,r){const i=n.iScale,o=n.vScale,a=i.getLabels(),l=i===o,d=[];let c,u,f,p;for(c=t,u=t+r;c=t?1:-1)}function $te(n){let e,t,r,i,o;return n.horizontal?(e=n.base>n.x,t="left",r="right"):(e=n.baseu.controller.options.grouped),o=r.options.stacked,a=[],l=this._cachedMeta.controller.getParsed(t),d=l&&l[r.axis],c=u=>{const f=u._parsed.find(g=>g[r.axis]===d),p=f&&f[u.vScale.axis];if(Ur(p)||isNaN(p))return!0};for(const u of i)if(!(t!==void 0&&c(u))&&((o===!1||a.indexOf(u.stack)===-1||o===void 0&&u.stack===void 0)&&a.push(u.stack),u.index===e))break;return a.length||a.push(void 0),a}_getStackCount(e){return this._getStacks(void 0,e).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const e=this.chart.scales,t=this.chart.options.indexAxis;return Object.keys(e).filter(r=>e[r].axis===t).shift()}_getAxis(){const e={},t=this.getFirstScaleIdForIndexAxis();for(const r of this.chart.data.datasets)e[In(this.chart.options.indexAxis==="x"?r.xAxisID:r.yAxisID,t)]=!0;return Object.keys(e)}_getStackIndex(e,t,r){const i=this._getStacks(e,r),o=t!==void 0?i.indexOf(t):-1;return o===-1?i.length-1:o}_getRuler(){const e=this.options,t=this._cachedMeta,r=t.iScale,i=[];let o,a;for(o=0,a=t.data.length;oKA(S,l,d,!0)?1:Math.max(_,_*t,b,b*t),m=(S,_,b)=>KA(S,l,d,!0)?-1:Math.min(_,_*t,b,b*t),y=g(0,c,f),v=g(Po,u,p),x=m(Or,c,f),w=m(Or+Po,u,p);r=(y-x)/2,i=(v-w)/2,o=-(y+x)/2,a=-(v+w)/2}return{ratioX:r,ratioY:i,offsetX:o,offsetY:a}}class eS extends l0{constructor(e,t){super(e,t),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(e,t){const r=this.getDataset().data,i=this._cachedMeta;if(this._parsing===!1)i._parsed=r;else{let o=d=>+r[d];if(Yn(r[e])){const{key:d="value"}=this._parsing;o=c=>+g0(r[c],d)}let a,l;for(a=e,l=e+t;a0&&!isNaN(e)?Eo*(Math.abs(e)/t):0}getLabelAndValue(e){const t=this._cachedMeta,r=this.chart,i=r.data.labels||[],o=R6(t._parsed[e],r.options.locale);return{label:i[e]||"",value:o}}getMaxBorderWidth(e){let t=0;const r=this.chart;let i,o,a,l,d;if(!e){for(i=0,o=r.data.datasets.length;ie!=="spacing",_indexable:e=>e!=="spacing"&&!e.startsWith("borderDash")&&!e.startsWith("hoverBorderDash")}),ve(eS,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(e){const t=e.data,{labels:{pointStyle:r,textAlign:i,color:o,useBorderRadius:a,borderRadius:l}}=e.legend.options;return t.labels.length&&t.datasets.length?t.labels.map((d,c)=>{const f=e.getDatasetMeta(0).controller.getStyle(c);return{text:d,fillStyle:f.backgroundColor,fontColor:o,hidden:!e.getDataVisibility(c),lineDash:f.borderDash,lineDashOffset:f.borderDashOffset,lineJoin:f.borderJoinStyle,lineWidth:f.borderWidth,strokeStyle:f.borderColor,textAlign:i,pointStyle:r,borderRadius:a&&(l||f.borderRadius),index:c}}):[]}},onClick(e,t,r){r.chart.toggleDataVisibility(t.index),r.chart.update()}}}});class p5 extends l0{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(e){const t=this._cachedMeta,{dataset:r,data:i=[],_dataset:o}=t,a=this.chart._animationsDisabled;let{start:l,count:d}=Cee(t,i,a);this._drawStart=l,this._drawCount=d,Aee(t)&&(l=0,d=i.length),r._chart=this.chart,r._datasetIndex=this.index,r._decimated=!!o._decimated,r.points=i;const c=this.resolveDatasetElementOptions(e);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(r,void 0,{animated:!a,options:c},e),this.updateElements(i,l,d,e)}updateElements(e,t,r,i){const o=i==="reset",{iScale:a,vScale:l,_stacked:d,_dataset:c}=this._cachedMeta,{sharedOptions:u,includeOptions:f}=this._getSharedOptions(t,i),p=a.axis,g=l.axis,{spanGaps:m,segment:y}=this.options,v=m0(m)?m:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||i==="none",w=t+r,S=e.length;let _=t>0&&this.getParsed(t-1);for(let b=0;b=w){T.skip=!0;continue}const F=this.getParsed(b),A=Ur(F[g]),D=T[p]=a.getPixelForValue(F[p],b),P=T[g]=o||A?l.getBasePixel():l.getPixelForValue(d?this.applyStack(l,F,d):F[g],b);T.skip=isNaN(D)||isNaN(P)||A,T.stop=b>0&&Math.abs(F[p]-_[p])>v,y&&(T.parsed=F,T.raw=c.data[b]),f&&(T.options=u||this.resolveDataElementOptions(b,C.active?"active":i)),x||this.updateElement(C,b,T,i),_=F}}getMaxOverflow(){const e=this._cachedMeta,t=e.dataset,r=t.options&&t.options.borderWidth||0,i=e.data||[];if(!i.length)return r;const o=i[0].size(this.resolveDataElementOptions(0)),a=i[i.length-1].size(this.resolveDataElementOptions(i.length-1));return Math.max(r,o,a)/2}draw(){const e=this._cachedMeta;e.dataset.updateControlPoints(this.chart.chartArea,e.iScale.axis),super.draw()}}ve(p5,"id","line"),ve(p5,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),ve(p5,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});function nm(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class N6{constructor(e){ve(this,"options");this.options=e||{}}static override(e){Object.assign(N6.prototype,e)}init(){}formats(){return nm()}parse(){return nm()}format(){return nm()}add(){return nm()}diff(){return nm()}startOf(){return nm()}endOf(){return nm()}}var nne={_date:N6};function rne(n,e,t,r){const{controller:i,data:o,_sorted:a}=n,l=i._cachedMeta.iScale,d=n.dataset&&n.dataset.options?n.dataset.options.spanGaps:null;if(l&&e===l.axis&&e!=="r"&&a&&o.length){const c=l._reversePixels?wee:vm;if(r){if(i._sharedOptions){const u=o[0],f=typeof u.getRange=="function"&&u.getRange(e);if(f){const p=c(o,e,t-f),g=c(o,e,t+f);return{lo:p.lo,hi:g.hi}}}}else{const u=c(o,e,t);if(d){const{vScale:f}=i._cachedMeta,{_parsed:p}=n,g=p.slice(0,u.lo+1).reverse().findIndex(y=>!Ur(y[f.axis]));u.lo-=Math.max(0,g);const m=p.slice(u.hi).findIndex(y=>!Ur(y[f.axis]));u.hi+=Math.max(0,m)}return u}}return{lo:0,hi:o.length-1}}function kF(n,e,t,r,i){const o=n.getSortedVisibleDatasetMetas(),a=t[e];for(let l=0,d=o.length;l{d[a]&&d[a](e[t],i)&&(o.push({element:d,datasetIndex:c,index:u}),l=l||d.inRange(e.x,e.y,i))}),r&&!l?[]:o}var ane={modes:{index(n,e,t,r){const i=om(e,n),o=t.axis||"x",a=t.includeInvisible||!1,l=t.intersect?fP(n,i,o,r,a):pP(n,i,o,!1,r,a),d=[];return l.length?(n.getSortedVisibleDatasetMetas().forEach(c=>{const u=l[0].index,f=c.data[u];f&&!f.skip&&d.push({element:f,datasetIndex:c.index,index:u})}),d):[]},dataset(n,e,t,r){const i=om(e,n),o=t.axis||"xy",a=t.includeInvisible||!1;let l=t.intersect?fP(n,i,o,r,a):pP(n,i,o,!1,r,a);if(l.length>0){const d=l[0].datasetIndex,c=n.getDatasetMeta(d).data;l=[];for(let u=0;ut.pos===e)}function WO(n,e){return n.filter(t=>mU.indexOf(t.pos)===-1&&t.box.axis===e)}function Dw(n,e){return n.sort((t,r)=>{const i=e?r:t,o=e?t:r;return i.weight===o.weight?i.index-o.index:i.weight-o.weight})}function lne(n){const e=[];let t,r,i,o,a,l;for(t=0,r=(n||[]).length;tc.box.fullSize),!0),r=Dw(Fw(e,"left"),!0),i=Dw(Fw(e,"right")),o=Dw(Fw(e,"top"),!0),a=Dw(Fw(e,"bottom")),l=WO(e,"x"),d=WO(e,"y");return{fullSize:t,leftAndTop:r.concat(o),rightAndBottom:i.concat(d).concat(a).concat(l),chartArea:Fw(e,"chartArea"),vertical:r.concat(i).concat(d),horizontal:o.concat(a).concat(l)}}function UO(n,e,t,r){return Math.max(n[t],e[t])+Math.max(n[r],e[r])}function yU(n,e){n.top=Math.max(n.top,e.top),n.left=Math.max(n.left,e.left),n.bottom=Math.max(n.bottom,e.bottom),n.right=Math.max(n.right,e.right)}function hne(n,e,t,r){const{pos:i,box:o}=t,a=n.maxPadding;if(!Yn(i)){t.size&&(n[i]-=t.size);const f=r[t.stack]||{size:0,count:1};f.size=Math.max(f.size,t.horizontal?o.height:o.width),t.size=f.size/f.count,n[i]+=t.size}o.getPadding&&yU(a,o.getPadding());const l=Math.max(0,e.outerWidth-UO(a,n,"left","right")),d=Math.max(0,e.outerHeight-UO(a,n,"top","bottom")),c=l!==n.w,u=d!==n.h;return n.w=l,n.h=d,t.horizontal?{same:c,other:u}:{same:u,other:c}}function fne(n){const e=n.maxPadding;function t(r){const i=Math.max(e[r]-n[r],0);return n[r]+=i,i}n.y+=t("top"),n.x+=t("left"),t("right"),t("bottom")}function pne(n,e){const t=e.maxPadding;function r(i){const o={left:0,top:0,right:0,bottom:0};return i.forEach(a=>{o[a]=Math.max(e[a],t[a])}),o}return r(n?["left","right"]:["top","bottom"])}function tS(n,e,t,r){const i=[];let o,a,l,d,c,u;for(o=0,a=n.length,c=0;o{typeof y.beforeLayout=="function"&&y.beforeLayout()});const u=d.reduce((y,v)=>v.box.options&&v.box.options.display===!1?y:y+1,0)||1,f=Object.freeze({outerWidth:e,outerHeight:t,padding:i,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/u,hBoxMaxHeight:a/2}),p=Object.assign({},i);yU(p,sa(r));const g=Object.assign({maxPadding:p,w:o,h:a,x:i.left,y:i.top},i),m=cne(d.concat(c),f);tS(l.fullSize,g,f,m),tS(d,g,f,m),tS(c,g,f,m)&&tS(d,g,f,m),fne(g),HO(l.leftAndTop,g,f,m),g.x+=g.w,g.y+=g.h,HO(l.rightAndBottom,g,f,m),n.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},Yr(l.chartArea,y=>{const v=y.box;Object.assign(v,n.chartArea),v.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})})}};class xU{acquireContext(e,t){}releaseContext(e){return!1}addEventListener(e,t,r){}removeEventListener(e,t,r){}getDevicePixelRatio(){return 1}getMaximumSize(e,t,r,i){return t=Math.max(0,t||e.width),r=r||e.height,{width:t,height:Math.max(0,i?Math.floor(t/i):r)}}isAttached(e){return!0}updateConfig(e){}}class gne extends xU{acquireContext(e){return e&&e.getContext&&e.getContext("2d")||null}updateConfig(e){e.options.animation=!1}}const g5="$chartjs",mne={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},qO=n=>n===null||n==="";function yne(n,e){const t=n.style,r=n.getAttribute("height"),i=n.getAttribute("width");if(n[g5]={initial:{height:r,width:i,style:{display:t.display,height:t.height,width:t.width}}},t.display=t.display||"block",t.boxSizing=t.boxSizing||"border-box",qO(i)){const o=AO(n,"width");o!==void 0&&(n.width=o)}if(qO(r))if(n.style.height==="")n.height=n.width/(e||2);else{const o=AO(n,"height");o!==void 0&&(n.height=o)}return n}const bU=mte?{passive:!0}:!1;function xne(n,e,t){n&&n.addEventListener(e,t,bU)}function bne(n,e,t){n&&n.canvas&&n.canvas.removeEventListener(e,t,bU)}function vne(n,e){const t=mne[n.type]||n.type,{x:r,y:i}=om(n,e);return{type:t,chart:e,native:n,x:r!==void 0?r:null,y:i!==void 0?i:null}}function YA(n,e){for(const t of n)if(t===e||t.contains(e))return!0}function wne(n,e,t){const r=n.canvas,i=new MutationObserver(o=>{let a=!1;for(const l of o)a=a||YA(l.addedNodes,r),a=a&&!YA(l.removedNodes,r);a&&t()});return i.observe(document,{childList:!0,subtree:!0}),i}function Sne(n,e,t){const r=n.canvas,i=new MutationObserver(o=>{let a=!1;for(const l of o)a=a||YA(l.removedNodes,r),a=a&&!YA(l.addedNodes,r);a&&t()});return i.observe(document,{childList:!0,subtree:!0}),i}const Rj=new Map;let VO=0;function vU(){const n=window.devicePixelRatio;n!==VO&&(VO=n,Rj.forEach((e,t)=>{t.currentDevicePixelRatio!==n&&e()}))}function jne(n,e){Rj.size||window.addEventListener("resize",vU),Rj.set(n,e)}function kne(n){Rj.delete(n),Rj.size||window.removeEventListener("resize",vU)}function _ne(n,e,t){const r=n.canvas,i=r&&O6(r);if(!i)return;const o=tU((l,d)=>{const c=i.clientWidth;t(l,d),c{const d=l[0],c=d.contentRect.width,u=d.contentRect.height;c===0&&u===0||o(c,u)});return a.observe(i),jne(n,o),a}function gP(n,e,t){t&&t.disconnect(),e==="resize"&&kne(n)}function Cne(n,e,t){const r=n.canvas,i=tU(o=>{n.ctx!==null&&t(vne(o,n))},n);return xne(r,e,i),i}class Ane extends xU{acquireContext(e,t){const r=e&&e.getContext&&e.getContext("2d");return r&&r.canvas===e?(yne(e,t),r):null}releaseContext(e){const t=e.canvas;if(!t[g5])return!1;const r=t[g5].initial;["height","width"].forEach(o=>{const a=r[o];Ur(a)?t.removeAttribute(o):t.setAttribute(o,a)});const i=r.style||{};return Object.keys(i).forEach(o=>{t.style[o]=i[o]}),t.width=t.width,delete t[g5],!0}addEventListener(e,t,r){this.removeEventListener(e,t);const i=e.$proxies||(e.$proxies={}),a={attach:wne,detach:Sne,resize:_ne}[t]||Cne;i[t]=a(e,t,r)}removeEventListener(e,t){const r=e.$proxies||(e.$proxies={}),i=r[t];if(!i)return;({attach:gP,detach:gP,resize:gP}[t]||bne)(e,t,i),r[t]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(e,t,r,i){return gte(e,t,r,i)}isAttached(e){const t=e&&O6(e);return!!(t&&t.isConnected)}}function Tne(n){return!z6()||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas?gne:Ane}class Oo{constructor(){ve(this,"x");ve(this,"y");ve(this,"active",!1);ve(this,"options");ve(this,"$animations")}tooltipPosition(e){const{x:t,y:r}=this.getProps(["x","y"],e);return{x:t,y:r}}hasValue(){return m0(this.x)&&m0(this.y)}getProps(e,t){const r=this.$animations;if(!t||!r)return this;const i={};return e.forEach(o=>{i[o]=r[o]&&r[o].active()?r[o]._to:this[o]}),i}}ve(Oo,"defaults",{}),ve(Oo,"defaultRoutes");function Fne(n,e){const t=n.options.ticks,r=Dne(n),i=Math.min(t.maxTicksLimit||r,r),o=t.major.enabled?Pne(e):[],a=o.length,l=o[0],d=o[a-1],c=[];if(a>i)return Rne(e,c,o,a/i),c;const u=Ene(o,e,i);if(a>0){let f,p;const g=a>1?Math.round((d-l)/(a-1)):null;for(S2(e,c,u,Ur(g)?0:l-g,l),f=0,p=a-1;fi)return d}return Math.max(i,1)}function Pne(n){const e=[];let t,r;for(t=0,r=n.length;tn==="left"?"right":n==="right"?"left":n,GO=(n,e,t)=>e==="top"||e==="left"?n[e]+t:n[e]-t,KO=(n,e)=>Math.min(e||n,n);function XO(n,e){const t=[],r=n.length/e,i=n.length;let o=0;for(;oa+l)))return d}function zne(n,e){Yr(n,t=>{const r=t.gc,i=r.length/2;let o;if(i>e){for(o=0;or?r:t,r=i&&t>r?t:r,{min:Hc(t,Hc(r,t)),max:Hc(r,Hc(t,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const e=this.chart.data;return this.options.labels||(this.isHorizontal()?e.xLabels:e.yLabels)||e.labels||[]}getLabelItems(e=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(e))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){li(this.options.beforeUpdate,[this])}update(e,t,r){const{beginAtZero:i,grace:o,ticks:a}=this.options,l=a.sampleSize;this.beforeUpdate(),this.maxWidth=e,this.maxHeight=t,this._margins=r=Object.assign({left:0,right:0,top:0,bottom:0},r),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+r.left+r.right:this.height+r.top+r.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Kee(this,o,i),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const d=l=o||r<=1||!this.isHorizontal()){this.labelRotation=i;return}const u=this._getLabelSizes(),f=u.widest.width,p=u.highest.height,g=Wl(this.chart.width-f,0,this.maxWidth);l=e.offset?this.maxWidth/r:g/(r-1),f+6>l&&(l=g/(r-(e.offset?.5:1)),d=this.maxHeight-Ew(e.grid)-t.padding-YO(e.title,this.chart.options.font),c=Math.sqrt(f*f+p*p),a=$9(Math.min(Math.asin(Wl((u.highest.height+6)/l,-1,1)),Math.asin(Wl(d/c,-1,1))-Math.asin(Wl(p/c,-1,1)))),a=Math.max(i,Math.min(o,a))),this.labelRotation=a}afterCalculateLabelRotation(){li(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){li(this.options.beforeFit,[this])}fit(){const e={width:0,height:0},{chart:t,options:{ticks:r,title:i,grid:o}}=this,a=this._isVisible(),l=this.isHorizontal();if(a){const d=YO(i,t.options.font);if(l?(e.width=this.maxWidth,e.height=Ew(o)+d):(e.height=this.maxHeight,e.width=Ew(o)+d),r.display&&this.ticks.length){const{first:c,last:u,widest:f,highest:p}=this._getLabelSizes(),g=r.padding*2,m=fo(this.labelRotation),y=Math.cos(m),v=Math.sin(m);if(l){const x=r.mirror?0:v*f.width+y*p.height;e.height=Math.min(this.maxHeight,e.height+x+g)}else{const x=r.mirror?0:y*f.width+v*p.height;e.width=Math.min(this.maxWidth,e.width+x+g)}this._calculatePadding(c,u,v,y)}}this._handleMargins(),l?(this.width=this._length=t.width-this._margins.left-this._margins.right,this.height=e.height):(this.width=e.width,this.height=this._length=t.height-this._margins.top-this._margins.bottom)}_calculatePadding(e,t,r,i){const{ticks:{align:o,padding:a},position:l}=this.options,d=this.labelRotation!==0,c=l!=="top"&&this.axis==="x";if(this.isHorizontal()){const u=this.getPixelForTick(0)-this.left,f=this.right-this.getPixelForTick(this.ticks.length-1);let p=0,g=0;d?c?(p=i*e.width,g=r*t.height):(p=r*e.height,g=i*t.width):o==="start"?g=t.width:o==="end"?p=e.width:o!=="inner"&&(p=e.width/2,g=t.width/2),this.paddingLeft=Math.max((p-u+a)*this.width/(this.width-u),0),this.paddingRight=Math.max((g-f+a)*this.width/(this.width-f),0)}else{let u=t.height/2,f=e.height/2;o==="start"?(u=0,f=e.height):o==="end"&&(u=t.height,f=0),this.paddingTop=u+a,this.paddingBottom=f+a}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){li(this.options.afterFit,[this])}isHorizontal(){const{axis:e,position:t}=this.options;return t==="top"||t==="bottom"||e==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(e){this.beforeTickToLabelConversion(),this.generateTickLabels(e);let t,r;for(t=0,r=e.length;t({width:a[A]||0,height:l[A]||0});return{first:F(0),last:F(t-1),widest:F(C),highest:F(T),widths:a,heights:l}}getLabelForValue(e){return e}getPixelForValue(e,t){return NaN}getValueForPixel(e){}getPixelForTick(e){const t=this.ticks;return e<0||e>t.length-1?null:this.getPixelForValue(t[e].value)}getPixelForDecimal(e){this._reversePixels&&(e=1-e);const t=this._startPixel+e*this._length;return vee(this._alignToPixels?tm(this.chart,t,0):t)}getDecimalForPixel(e){const t=(e-this._startPixel)/this._length;return this._reversePixels?1-t:t}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:e,max:t}=this;return e<0&&t<0?t:e>0&&t>0?e:0}getContext(e){const t=this.ticks||[];if(e>=0&&el*i?l/r:d/i:d*i0}_computeGridLineItems(e){const t=this.axis,r=this.chart,i=this.options,{grid:o,position:a,border:l}=i,d=o.offset,c=this.isHorizontal(),f=this.ticks.length+(d?1:0),p=Ew(o),g=[],m=l.setContext(this.getContext()),y=m.display?m.width:0,v=y/2,x=function(M){return tm(r,M,y)};let w,S,_,b,C,T,F,A,D,P,L,W;if(a==="top")w=x(this.bottom),T=this.bottom-p,A=w-v,P=x(e.top)+v,W=e.bottom;else if(a==="bottom")w=x(this.top),P=e.top,W=x(e.bottom)-v,T=w+v,A=this.top+p;else if(a==="left")w=x(this.right),C=this.right-p,F=w-v,D=x(e.left)+v,L=e.right;else if(a==="right")w=x(this.left),D=e.left,L=x(e.right)-v,C=w+v,F=this.left+p;else if(t==="x"){if(a==="center")w=x((e.top+e.bottom)/2+.5);else if(Yn(a)){const M=Object.keys(a)[0],I=a[M];w=x(this.chart.scales[M].getPixelForValue(I))}P=e.top,W=e.bottom,T=w+v,A=T+p}else if(t==="y"){if(a==="center")w=x((e.left+e.right)/2);else if(Yn(a)){const M=Object.keys(a)[0],I=a[M];w=x(this.chart.scales[M].getPixelForValue(I))}C=w-v,F=C-p,D=e.left,L=e.right}const O=In(i.ticks.maxTicksLimit,f),U=Math.max(1,Math.ceil(f/O));for(S=0;S0&&(ye-=J/2);break}te={left:ye,top:ne,width:J+re.width,height:me+re.height,color:U.backdropColor}}v.push({label:_,font:A,textOffset:L,options:{rotation:y,color:I,strokeColor:H,strokeWidth:z,textAlign:G,textBaseline:W,translation:[b,C],backdrop:te}})}return v}_getXAxisLabelAlignment(){const{position:e,ticks:t}=this.options;if(-fo(this.labelRotation))return e==="top"?"left":"right";let i="center";return t.align==="start"?i="left":t.align==="end"?i="right":t.align==="inner"&&(i="inner"),i}_getYAxisLabelAlignment(e){const{position:t,ticks:{crossAlign:r,mirror:i,padding:o}}=this.options,a=this._getLabelSizes(),l=e+o,d=a.widest.width;let c,u;return t==="left"?i?(u=this.right+o,r==="near"?c="left":r==="center"?(c="center",u+=d/2):(c="right",u+=d)):(u=this.right-l,r==="near"?c="right":r==="center"?(c="center",u-=d/2):(c="left",u=this.left)):t==="right"?i?(u=this.left+o,r==="near"?c="right":r==="center"?(c="center",u-=d/2):(c="left",u-=d)):(u=this.left+l,r==="near"?c="left":r==="center"?(c="center",u+=d/2):(c="right",u=this.right)):c="right",{textAlign:c,x:u}}_computeLabelArea(){if(this.options.ticks.mirror)return;const e=this.chart,t=this.options.position;if(t==="left"||t==="right")return{top:0,left:this.left,bottom:e.height,right:this.right};if(t==="top"||t==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:e.width}}drawBackground(){const{ctx:e,options:{backgroundColor:t},left:r,top:i,width:o,height:a}=this;t&&(e.save(),e.fillStyle=t,e.fillRect(r,i,o,a),e.restore())}getLineWidthForValue(e){const t=this.options.grid;if(!this._isVisible()||!t.display)return 0;const i=this.ticks.findIndex(o=>o.value===e);return i>=0?t.setContext(this.getContext(i)).lineWidth:0}drawGrid(e){const t=this.options.grid,r=this.ctx,i=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(e));let o,a;const l=(d,c,u)=>{!u.width||!u.color||(r.save(),r.lineWidth=u.width,r.strokeStyle=u.color,r.setLineDash(u.borderDash||[]),r.lineDashOffset=u.borderDashOffset,r.beginPath(),r.moveTo(d.x,d.y),r.lineTo(c.x,c.y),r.stroke(),r.restore())};if(t.display)for(o=0,a=i.length;o{this.draw(o)}}]:[{z:r,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:i,draw:()=>{this.drawBorder()}},{z:t,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(e){const t=this.chart.getSortedVisibleDatasetMetas(),r=this.axis+"AxisID",i=[];let o,a;for(o=0,a=t.length;o{const r=t.split("."),i=r.pop(),o=[n].concat(r).join("."),a=e[t].split("."),l=a.pop(),d=a.join(".");hs.route(o,i,d,l)})}function qne(n){return"id"in n&&"defaults"in n}class Vne{constructor(){this.controllers=new j2(l0,"datasets",!0),this.elements=new j2(Oo,"elements"),this.plugins=new j2(Object,"plugins"),this.scales=new j2(m1,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...e){this._each("register",e)}remove(...e){this._each("unregister",e)}addControllers(...e){this._each("register",e,this.controllers)}addElements(...e){this._each("register",e,this.elements)}addPlugins(...e){this._each("register",e,this.plugins)}addScales(...e){this._each("register",e,this.scales)}getController(e){return this._get(e,this.controllers,"controller")}getElement(e){return this._get(e,this.elements,"element")}getPlugin(e){return this._get(e,this.plugins,"plugin")}getScale(e){return this._get(e,this.scales,"scale")}removeControllers(...e){this._each("unregister",e,this.controllers)}removeElements(...e){this._each("unregister",e,this.elements)}removePlugins(...e){this._each("unregister",e,this.plugins)}removeScales(...e){this._each("unregister",e,this.scales)}_each(e,t,r){[...t].forEach(i=>{const o=r||this._getRegistryForType(i);r||o.isForType(i)||o===this.plugins&&i.id?this._exec(e,o,i):Yr(i,a=>{const l=r||this._getRegistryForType(a);this._exec(e,l,a)})})}_exec(e,t,r){const i=T6(e);li(r["before"+i],[],r),t[e](r),li(r["after"+i],[],r)}_getRegistryForType(e){for(let t=0;to.filter(l=>!a.some(d=>l.plugin.id===d.plugin.id));this._notify(i(t,r),e,"stop"),this._notify(i(r,t),e,"start")}}function Kne(n){const e={},t=[],r=Object.keys(Jc.plugins.items);for(let o=0;o1&&QO(n[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${n}' axis. Please provide 'axis' or 'position' option.`)}function $O(n,e,t){if(t[e+"AxisID"]===n)return{axis:e}}function ere(n,e){if(e.data&&e.data.datasets){const t=e.data.datasets.filter(r=>r.xAxisID===n||r.yAxisID===n);if(t.length)return $O(n,"x",t[0])||$O(n,"y",t[0])}return{}}function tre(n,e){const t=y0[n.type]||{scales:{}},r=e.scales||{},i=gB(n.type,e),o=Object.create(null);return Object.keys(r).forEach(a=>{const l=r[a];if(!Yn(l))return console.error(`Invalid scale configuration for scale: ${a}`);if(l._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${a}`);const d=mB(a,l,ere(a,n),hs.scales[l.type]),c=Zne(d,i),u=t.scales||{};o[a]=US(Object.create(null),[{axis:d},l,u[d],u[c]])}),n.data.datasets.forEach(a=>{const l=a.type||n.type,d=a.indexAxis||gB(l,e),u=(y0[l]||{}).scales||{};Object.keys(u).forEach(f=>{const p=$ne(f,d),g=a[p+"AxisID"]||p;o[g]=o[g]||Object.create(null),US(o[g],[{axis:p},r[g],u[f]])})}),Object.keys(o).forEach(a=>{const l=o[a];US(l,[hs.scales[l.type],hs.scale])}),o}function wU(n){const e=n.options||(n.options={});e.plugins=In(e.plugins,{}),e.scales=tre(n,e)}function SU(n){return n=n||{},n.datasets=n.datasets||[],n.labels=n.labels||[],n}function nre(n){return n=n||{},n.data=SU(n.data),wU(n),n}const ZO=new Map,jU=new Set;function k2(n,e){let t=ZO.get(n);return t||(t=e(),ZO.set(n,t),jU.add(t)),t}const Pw=(n,e,t)=>{const r=g0(e,t);r!==void 0&&n.add(r)};let rre=class{constructor(e){this._config=nre(e),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(e){this._config.type=e}get data(){return this._config.data}set data(e){this._config.data=SU(e)}get options(){return this._config.options}set options(e){this._config.options=e}get plugins(){return this._config.plugins}update(){const e=this._config;this.clearCache(),wU(e)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(e){return k2(e,()=>[[`datasets.${e}`,""]])}datasetAnimationScopeKeys(e,t){return k2(`${e}.transition.${t}`,()=>[[`datasets.${e}.transitions.${t}`,`transitions.${t}`],[`datasets.${e}`,""]])}datasetElementScopeKeys(e,t){return k2(`${e}-${t}`,()=>[[`datasets.${e}.elements.${t}`,`datasets.${e}`,`elements.${t}`,""]])}pluginScopeKeys(e){const t=e.id,r=this.type;return k2(`${r}-plugin-${t}`,()=>[[`plugins.${t}`,...e.additionalOptionScopes||[]]])}_cachedScopes(e,t){const r=this._scopeCache;let i=r.get(e);return(!i||t)&&(i=new Map,r.set(e,i)),i}getOptionScopes(e,t,r){const{options:i,type:o}=this,a=this._cachedScopes(e,r),l=a.get(t);if(l)return l;const d=new Set;t.forEach(u=>{e&&(d.add(e),u.forEach(f=>Pw(d,e,f))),u.forEach(f=>Pw(d,i,f)),u.forEach(f=>Pw(d,y0[o]||{},f)),u.forEach(f=>Pw(d,hs,f)),u.forEach(f=>Pw(d,fB,f))});const c=Array.from(d);return c.length===0&&c.push(Object.create(null)),jU.has(t)&&a.set(t,c),c}chartOptionScopes(){const{options:e,type:t}=this;return[e,y0[t]||{},hs.datasets[t]||{},{type:t},hs,fB]}resolveNamedOptions(e,t,r,i=[""]){const o={$shared:!0},{resolver:a,subPrefixes:l}=JO(this._resolverCache,e,i);let d=a;if(sre(a,t)){o.$shared=!1,r=il(r)?r():r;const c=this.createResolver(e,r,l);d=i1(a,r,c)}for(const c of t)o[c]=d[c];return o}createResolver(e,t,r=[""],i){const{resolver:o}=JO(this._resolverCache,e,r);return Yn(t)?i1(o,t,void 0,i):o}};function JO(n,e,t){let r=n.get(e);r||(r=new Map,n.set(e,r));const i=t.join();let o=r.get(i);return o||(o={resolver:B6(e,t),subPrefixes:t.filter(l=>!l.toLowerCase().includes("hover"))},r.set(i,o)),o}const ire=n=>Yn(n)&&Object.getOwnPropertyNames(n).some(e=>il(n[e]));function sre(n,e){const{isScriptable:t,isIndexable:r}=oU(n);for(const i of e){const o=t(i),a=r(i),l=(a||o)&&n[i];if(o&&(il(l)||ire(l))||a&&ki(l))return!0}return!1}var ore="4.5.1";const are=["top","bottom","left","right","chartArea"];function eL(n,e){return n==="top"||n==="bottom"||are.indexOf(n)===-1&&e==="x"}function tL(n,e){return function(t,r){return t[n]===r[n]?t[e]-r[e]:t[n]-r[n]}}function nL(n){const e=n.chart,t=e.options.animation;e.notifyPlugins("afterRender"),li(t&&t.onComplete,[n],e)}function lre(n){const e=n.chart,t=e.options.animation;li(t&&t.onProgress,[n],e)}function kU(n){return z6()&&typeof n=="string"?n=document.getElementById(n):n&&n.length&&(n=n[0]),n&&n.canvas&&(n=n.canvas),n}const m5={},rL=n=>{const e=kU(n);return Object.values(m5).filter(t=>t.canvas===e).pop()};function dre(n,e,t){const r=Object.keys(n);for(const i of r){const o=+i;if(o>=e){const a=n[i];delete n[i],(t>0||o>e)&&(n[o+t]=a)}}}function cre(n,e,t,r){return!t||n.type==="mouseout"?null:r?e:n}var Kf;let pf=(Kf=class{static register(...e){Jc.add(...e),iL()}static unregister(...e){Jc.remove(...e),iL()}constructor(e,t){const r=this.config=new rre(t),i=kU(e),o=rL(i);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=r.createResolver(r.chartOptionScopes(),this.getContext());this.platform=new(r.platform||Tne(i)),this.platform.updateConfig(r);const l=this.platform.acquireContext(i,a.aspectRatio),d=l&&l.canvas,c=d&&d.height,u=d&&d.width;if(this.id=aee(),this.ctx=l,this.canvas=d,this.width=u,this.height=c,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new Gne,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=kee(f=>this.update(f),a.resizeDelay||0),this._dataChanges=[],m5[this.id]=this,!l||!d){console.error("Failed to create chart: can't acquire context from the given item");return}ch.listen(this,"complete",nL),ch.listen(this,"progress",lre),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:e,maintainAspectRatio:t},width:r,height:i,_aspectRatio:o}=this;return Ur(e)?t&&o?o:i?r/i:null:e}get data(){return this.config.data}set data(e){this.config.data=e}get options(){return this._options}set options(e){this.config.options=e}get registry(){return Jc}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():CO(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return jO(this.canvas,this.ctx),this}stop(){return ch.stop(this),this}resize(e,t){ch.running(this)?this._resizeBeforeDraw={width:e,height:t}:this._resize(e,t)}_resize(e,t){const r=this.options,i=this.canvas,o=r.maintainAspectRatio&&this.aspectRatio,a=this.platform.getMaximumSize(i,e,t,o),l=r.devicePixelRatio||this.platform.getDevicePixelRatio(),d=this.width?"resize":"attach";this.width=a.width,this.height=a.height,this._aspectRatio=this.aspectRatio,CO(this,l,!0)&&(this.notifyPlugins("resize",{size:a}),li(r.onResize,[this,a],this),this.attached&&this._doResize(d)&&this.render())}ensureScalesHaveIDs(){const t=this.options.scales||{};Yr(t,(r,i)=>{r.id=i})}buildOrUpdateScales(){const e=this.options,t=e.scales,r=this.scales,i=Object.keys(r).reduce((a,l)=>(a[l]=!1,a),{});let o=[];t&&(o=o.concat(Object.keys(t).map(a=>{const l=t[a],d=mB(a,l),c=d==="r",u=d==="x";return{options:l,dposition:c?"chartArea":u?"bottom":"left",dtype:c?"radialLinear":u?"category":"linear"}}))),Yr(o,a=>{const l=a.options,d=l.id,c=mB(d,l),u=In(l.type,a.dtype);(l.position===void 0||eL(l.position,c)!==eL(a.dposition))&&(l.position=a.dposition),i[d]=!0;let f=null;if(d in r&&r[d].type===u)f=r[d];else{const p=Jc.getScale(u);f=new p({id:d,type:u,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(l,e)}),Yr(i,(a,l)=>{a||delete r[l]}),Yr(r,a=>{Ed.configure(this,a,a.options),Ed.addBox(this,a)})}_updateMetasets(){const e=this._metasets,t=this.data.datasets.length,r=e.length;if(e.sort((i,o)=>i.index-o.index),r>t){for(let i=t;it.length&&delete this._stacks,e.forEach((r,i)=>{t.filter(o=>o===r._dataset).length===0&&this._destroyDatasetMeta(i)})}buildOrUpdateControllers(){const e=[],t=this.data.datasets;let r,i;for(this._removeUnreferencedMetasets(),r=0,i=t.length;r{this.getDatasetMeta(t).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(e){const t=this.config;t.update();const r=this._options=t.createResolver(t.chartOptionScopes(),this.getContext()),i=this._animationsDisabled=!r.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:e,cancelable:!0})===!1)return;const o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let a=0;for(let c=0,u=this.data.datasets.length;c{c.reset()}),this._updateDatasets(e),this.notifyPlugins("afterUpdate",{mode:e}),this._layers.sort(tL("z","_idx"));const{_active:l,_lastEvent:d}=this;d?this._eventHandler(d,!0):l.length&&this._updateHoverStyles(l,l,!0),this.render()}_updateScales(){Yr(this.scales,e=>{Ed.removeBox(this,e)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const e=this.options,t=new Set(Object.keys(this._listeners)),r=new Set(e.events);(!pO(t,r)||!!this._responsiveListeners!==e.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:e}=this,t=this._getUniformDataChanges()||[];for(const{method:r,start:i,count:o}of t){const a=r==="_removeElements"?-o:o;dre(e,i,a)}}_getUniformDataChanges(){const e=this._dataChanges;if(!e||!e.length)return;this._dataChanges=[];const t=this.data.datasets.length,r=o=>new Set(e.filter(a=>a[0]===o).map((a,l)=>l+","+a.splice(1).join(","))),i=r(0);for(let o=1;oo.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(e){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;Ed.update(this,this.width,this.height,e);const t=this.chartArea,r=t.width<=0||t.height<=0;this._layers=[],Yr(this.boxes,i=>{r&&i.position==="chartArea"||(i.configure&&i.configure(),this._layers.push(...i._layers()))},this),this._layers.forEach((i,o)=>{i._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(e){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:e,cancelable:!0})!==!1){for(let t=0,r=this.data.datasets.length;t=0;--t)this._drawDataset(e[t]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(e){const t=this.ctx,r={meta:e,index:e.index,cancelable:!0},i=Dte(this,e);this.notifyPlugins("beforeDatasetDraw",r)!==!1&&(i&&wF(t,i),e.controller.draw(),i&&SF(t),r.cancelable=!1,this.notifyPlugins("afterDatasetDraw",r))}isPointInArea(e){return Dj(e,this.chartArea,this._minPadding)}getElementsAtEventForMode(e,t,r,i){const o=ane.modes[t];return typeof o=="function"?o(this,e,r,i):[]}getDatasetMeta(e){const t=this.data.datasets[e],r=this._metasets;let i=r.filter(o=>o&&o._dataset===t).pop();return i||(i={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:t&&t.order||0,index:e,_dataset:t,_parsed:[],_sorted:!1},r.push(i)),i}getContext(){return this.$context||(this.$context=P0(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(e){const t=this.data.datasets[e];if(!t)return!1;const r=this.getDatasetMeta(e);return typeof r.hidden=="boolean"?!r.hidden:!t.hidden}setDatasetVisibility(e,t){const r=this.getDatasetMeta(e);r.hidden=!t}toggleDataVisibility(e){this._hiddenIndices[e]=!this._hiddenIndices[e]}getDataVisibility(e){return!this._hiddenIndices[e]}_updateVisibility(e,t,r){const i=r?"show":"hide",o=this.getDatasetMeta(e),a=o.controller._resolveAnimations(void 0,i);ol(t)?(o.data[t].hidden=!r,this.update()):(this.setDatasetVisibility(e,r),a.update(o,{visible:r}),this.update(l=>l.datasetIndex===e?i:void 0))}hide(e,t){this._updateVisibility(e,t,!1)}show(e,t){this._updateVisibility(e,t,!0)}_destroyDatasetMeta(e){const t=this._metasets[e];t&&t.controller&&t.controller._destroy(),delete this._metasets[e]}_stop(){let e,t;for(this.stop(),ch.remove(this),e=0,t=this.data.datasets.length;e{t.addEventListener(this,o,a),e[o]=a},i=(o,a,l)=>{o.offsetX=a,o.offsetY=l,this._eventHandler(o)};Yr(this.options.events,o=>r(o,i))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const e=this._responsiveListeners,t=this.platform,r=(d,c)=>{t.addEventListener(this,d,c),e[d]=c},i=(d,c)=>{e[d]&&(t.removeEventListener(this,d,c),delete e[d])},o=(d,c)=>{this.canvas&&this.resize(d,c)};let a;const l=()=>{i("attach",l),this.attached=!0,this.resize(),r("resize",o),r("detach",a)};a=()=>{this.attached=!1,i("resize",o),this._stop(),this._resize(0,0),r("attach",l)},t.isAttached(this.canvas)?l():a()}unbindEvents(){Yr(this._listeners,(e,t)=>{this.platform.removeEventListener(this,t,e)}),this._listeners={},Yr(this._responsiveListeners,(e,t)=>{this.platform.removeEventListener(this,t,e)}),this._responsiveListeners=void 0}updateHoverStyle(e,t,r){const i=r?"set":"remove";let o,a,l,d;for(t==="dataset"&&(o=this.getDatasetMeta(e[0].datasetIndex),o.controller["_"+i+"DatasetHoverStyle"]()),l=0,d=e.length;l{const l=this.getDatasetMeta(o);if(!l)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:l.data[a],index:a}});!HA(r,t)&&(this._active=r,this._lastEvent=null,this._updateHoverStyles(r,t))}notifyPlugins(e,t,r){return this._plugins.notify(this,e,t,r)}isPluginEnabled(e){return this._plugins._cache.filter(t=>t.plugin.id===e).length===1}_updateHoverStyles(e,t,r){const i=this.options.hover,o=(d,c)=>d.filter(u=>!c.some(f=>u.datasetIndex===f.datasetIndex&&u.index===f.index)),a=o(t,e),l=r?e:o(e,t);a.length&&this.updateHoverStyle(a,i.mode,!1),l.length&&i.mode&&this.updateHoverStyle(l,i.mode,!0)}_eventHandler(e,t){const r={event:e,replay:t,cancelable:!0,inChartArea:this.isPointInArea(e)},i=a=>(a.options.events||this.options.events).includes(e.native.type);if(this.notifyPlugins("beforeEvent",r,i)===!1)return;const o=this._handleEvent(e,t,r.inChartArea);return r.cancelable=!1,this.notifyPlugins("afterEvent",r,i),(o||r.changed)&&this.render(),this}_handleEvent(e,t,r){const{_active:i=[],options:o}=this,a=t,l=this._getActiveElements(e,i,r,a),d=fee(e),c=cre(e,this._lastEvent,r,d);r&&(this._lastEvent=null,li(o.onHover,[e,l,this],this),d&&li(o.onClick,[e,l,this],this));const u=!HA(l,i);return(u||t)&&(this._active=l,this._updateHoverStyles(l,i,t)),this._lastEvent=c,u}_getActiveElements(e,t,r,i){if(e.type==="mouseout")return[];if(!r)return t;const o=this.options.hover;return this.getElementsAtEventForMode(e,o.mode,o,i)}},ve(Kf,"defaults",hs),ve(Kf,"instances",m5),ve(Kf,"overrides",y0),ve(Kf,"registry",Jc),ve(Kf,"version",ore),ve(Kf,"getChart",rL),Kf);function iL(){return Yr(pf.instances,n=>n._plugins.invalidate())}function _U(n,e,t=e){n.lineCap=In(t.borderCapStyle,e.borderCapStyle),n.setLineDash(In(t.borderDash,e.borderDash)),n.lineDashOffset=In(t.borderDashOffset,e.borderDashOffset),n.lineJoin=In(t.borderJoinStyle,e.borderJoinStyle),n.lineWidth=In(t.borderWidth,e.borderWidth),n.strokeStyle=In(t.borderColor,e.borderColor)}function ure(n,e,t){n.lineTo(t.x,t.y)}function hre(n){return n.stepped?Oee:n.tension||n.cubicInterpolationMode==="monotone"?Lee:ure}function CU(n,e,t={}){const r=n.length,{start:i=0,end:o=r-1}=t,{start:a,end:l}=e,d=Math.max(i,a),c=Math.min(o,l),u=il&&o>l;return{count:r,start:d,loop:e.loop,ilen:c(a+(c?l-_:_))%o,S=()=>{y!==v&&(n.lineTo(u,v),n.lineTo(u,y),n.lineTo(u,x))};for(d&&(g=i[w(0)],n.moveTo(g.x,g.y)),p=0;p<=l;++p){if(g=i[w(p)],g.skip)continue;const _=g.x,b=g.y,C=_|0;C===m?(bv&&(v=b),u=(f*u+_)/++f):(S(),n.lineTo(_,b),m=C,f=0,y=v=b),x=b}S()}function yB(n){const e=n.options,t=e.borderDash&&e.borderDash.length;return!n._decimated&&!n._loop&&!e.tension&&e.cubicInterpolationMode!=="monotone"&&!e.stepped&&!t?pre:fre}function gre(n){return n.stepped?yte:n.tension||n.cubicInterpolationMode==="monotone"?xte:am}function mre(n,e,t,r){let i=e._path;i||(i=e._path=new Path2D,e.path(i,t,r)&&i.closePath()),_U(n,e.options),n.stroke(i)}function yre(n,e,t,r){const{segments:i,options:o}=e,a=yB(e);for(const l of i)_U(n,o,l.style),n.beginPath(),a(n,e,l,{start:t,end:t+r-1})&&n.closePath(),n.stroke()}const xre=typeof Path2D=="function";function bre(n,e,t,r){xre&&!e.options.segment?mre(n,e,t,r):yre(n,e,t,r)}class qx extends Oo{constructor(e){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,e&&Object.assign(this,e)}updateControlPoints(e,t){const r=this.options;if((r.tension||r.cubicInterpolationMode==="monotone")&&!r.stepped&&!this._pointsUpdated){const i=r.spanGaps?this._loop:this._fullLoop;dte(this._points,r,e,i,t),this._pointsUpdated=!0}}set points(e){this._points=e,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=Cte(this,this.options.segment))}first(){const e=this.segments,t=this.points;return e.length&&t[e[0].start]}last(){const e=this.segments,t=this.points,r=e.length;return r&&t[e[r-1].end]}interpolate(e,t){const r=this.options,i=e[t],o=this.points,a=jte(this,{property:t,start:i,end:i});if(!a.length)return;const l=[],d=gre(r);let c,u;for(c=0,u=a.length;ce!=="borderDash"&&e!=="fill"});function sL(n,e,t,r){const i=n.options,{[t]:o}=n.getProps([t],r);return Math.abs(e-o){let{boxHeight:t=e,boxWidth:r=e}=n;return n.usePointStyle&&(t=Math.min(t,e),r=n.pointStyleWidth||Math.min(r,e)),{boxWidth:r,boxHeight:t,itemHeight:Math.max(e,t)}},_re=(n,e)=>n!==null&&e!==null&&n.datasetIndex===e.datasetIndex&&n.index===e.index;class aL extends Oo{constructor(e){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,t,r){this.maxWidth=e,this.maxHeight=t,this._margins=r,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const e=this.options.labels||{};let t=li(e.generateLabels,[this.chart],this)||[];e.filter&&(t=t.filter(r=>e.filter(r,this.chart.data))),e.sort&&(t=t.sort((r,i)=>e.sort(r,i,this.chart.data))),this.options.reverse&&t.reverse(),this.legendItems=t}fit(){const{options:e,ctx:t}=this;if(!e.display){this.width=this.height=0;return}const r=e.labels,i=Us(r.font),o=i.size,a=this._computeTitleHeight(),{boxWidth:l,itemHeight:d}=oL(r,o);let c,u;t.font=i.string,this.isHorizontal()?(c=this.maxWidth,u=this._fitRows(a,o,l,d)+10):(u=this.maxHeight,c=this._fitCols(a,i,l,d)+10),this.width=Math.min(c,e.maxWidth||this.maxWidth),this.height=Math.min(u,e.maxHeight||this.maxHeight)}_fitRows(e,t,r,i){const{ctx:o,maxWidth:a,options:{labels:{padding:l}}}=this,d=this.legendHitBoxes=[],c=this.lineWidths=[0],u=i+l;let f=e;o.textAlign="left",o.textBaseline="middle";let p=-1,g=-u;return this.legendItems.forEach((m,y)=>{const v=r+t/2+o.measureText(m.text).width;(y===0||c[c.length-1]+v+2*l>a)&&(f+=u,c[c.length-(y>0?0:1)]=0,g+=u,p++),d[y]={left:0,top:g,row:p,width:v,height:i},c[c.length-1]+=v+l}),f}_fitCols(e,t,r,i){const{ctx:o,maxHeight:a,options:{labels:{padding:l}}}=this,d=this.legendHitBoxes=[],c=this.columnSizes=[],u=a-e;let f=l,p=0,g=0,m=0,y=0;return this.legendItems.forEach((v,x)=>{const{itemWidth:w,itemHeight:S}=Cre(r,t,o,v,i);x>0&&g+S+2*l>u&&(f+=p+l,c.push({width:p,height:g}),m+=p+l,y++,p=g=0),d[x]={left:m,top:g,col:y,width:w,height:S},p=Math.max(p,w),g+=S+l}),f+=p,c.push({width:p,height:g}),f}adjustHitBoxes(){if(!this.options.display)return;const e=this._computeTitleHeight(),{legendHitBoxes:t,options:{align:r,labels:{padding:i},rtl:o}}=this,a=ib(o,this.left,this.width);if(this.isHorizontal()){let l=0,d=ta(r,this.left+i,this.right-this.lineWidths[l]);for(const c of t)l!==c.row&&(l=c.row,d=ta(r,this.left+i,this.right-this.lineWidths[l])),c.top+=this.top+e+i,c.left=a.leftForLtr(a.x(d),c.width),d+=c.width+i}else{let l=0,d=ta(r,this.top+e+i,this.bottom-this.columnSizes[l].height);for(const c of t)c.col!==l&&(l=c.col,d=ta(r,this.top+e+i,this.bottom-this.columnSizes[l].height)),c.top=d,c.left+=this.left+i,c.left=a.leftForLtr(a.x(c.left),c.width),d+=c.height+i}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){const e=this.ctx;wF(e,this),this._draw(),SF(e)}}_draw(){const{options:e,columnSizes:t,lineWidths:r,ctx:i}=this,{align:o,labels:a}=e,l=hs.color,d=ib(e.rtl,this.left,this.width),c=Us(a.font),{padding:u}=a,f=c.size,p=f/2;let g;this.drawTitle(),i.textAlign=d.textAlign("left"),i.textBaseline="middle",i.lineWidth=.5,i.font=c.string;const{boxWidth:m,boxHeight:y,itemHeight:v}=oL(a,f),x=function(C,T,F){if(isNaN(m)||m<=0||isNaN(y)||y<0)return;i.save();const A=In(F.lineWidth,1);if(i.fillStyle=In(F.fillStyle,l),i.lineCap=In(F.lineCap,"butt"),i.lineDashOffset=In(F.lineDashOffset,0),i.lineJoin=In(F.lineJoin,"miter"),i.lineWidth=A,i.strokeStyle=In(F.strokeStyle,l),i.setLineDash(In(F.lineDash,[])),a.usePointStyle){const D={radius:y*Math.SQRT2/2,pointStyle:F.pointStyle,rotation:F.rotation,borderWidth:A},P=d.xPlus(C,m/2),L=T+p;rU(i,D,P,L,a.pointStyleWidth&&m)}else{const D=T+Math.max((f-y)/2,0),P=d.leftForLtr(C,m),L=o0(F.borderRadius);i.beginPath(),Object.values(L).some(W=>W!==0)?Pj(i,{x:P,y:D,w:m,h:y,radius:L}):i.rect(P,D,m,y),i.fill(),A!==0&&i.stroke()}i.restore()},w=function(C,T,F){Ej(i,F.text,C,T+v/2,c,{strikethrough:F.hidden,textAlign:d.textAlign(F.textAlign)})},S=this.isHorizontal(),_=this._computeTitleHeight();S?g={x:ta(o,this.left+u,this.right-r[0]),y:this.top+u+_,line:0}:g={x:this.left+u,y:ta(o,this.top+_+u,this.bottom-t[0].height),line:0},uU(this.ctx,e.textDirection);const b=v+u;this.legendItems.forEach((C,T)=>{i.strokeStyle=C.fontColor,i.fillStyle=C.fontColor;const F=i.measureText(C.text).width,A=d.textAlign(C.textAlign||(C.textAlign=a.textAlign)),D=m+p+F;let P=g.x,L=g.y;d.setWidth(this.width),S?T>0&&P+D+u>this.right&&(L=g.y+=b,g.line++,P=g.x=ta(o,this.left+u,this.right-r[g.line])):T>0&&L+b>this.bottom&&(P=g.x=P+t[g.line].width+u,g.line++,L=g.y=ta(o,this.top+_+u,this.bottom-t[g.line].height));const W=d.x(P);if(x(W,L,C),P=_ee(A,P+m+p,S?P+D:this.right,e.rtl),w(d.x(P),L,C),S)g.x+=D+u;else if(typeof C.text!="string"){const O=c.lineHeight;g.y+=TU(C,O)+u}else g.y+=b}),hU(this.ctx,e.textDirection)}drawTitle(){const e=this.options,t=e.title,r=Us(t.font),i=sa(t.padding);if(!t.display)return;const o=ib(e.rtl,this.left,this.width),a=this.ctx,l=t.position,d=r.size/2,c=i.top+d;let u,f=this.left,p=this.width;if(this.isHorizontal())p=Math.max(...this.lineWidths),u=this.top+c,f=ta(e.align,f,this.right-p);else{const m=this.columnSizes.reduce((y,v)=>Math.max(y,v.height),0);u=c+ta(e.align,this.top,this.bottom-m-e.labels.padding-this._computeTitleHeight())}const g=ta(l,f,f+p);a.textAlign=o.textAlign(E6(l)),a.textBaseline="middle",a.strokeStyle=t.color,a.fillStyle=t.color,a.font=r.string,Ej(a,t.text,g,u,r)}_computeTitleHeight(){const e=this.options.title,t=Us(e.font),r=sa(e.padding);return e.display?t.lineHeight+r.height:0}_getLegendItemAt(e,t){let r,i,o;if(bm(e,this.left,this.right)&&bm(t,this.top,this.bottom)){for(o=this.legendHitBoxes,r=0;ro.length>a.length?o:a)),e+t.size/2+r.measureText(i).width}function Tre(n,e,t){let r=n;return typeof e.text!="string"&&(r=TU(e,t)),r}function TU(n,e){const t=n.text?n.text.length:0;return e*t}function Fre(n,e){return!!((n==="mousemove"||n==="mouseout")&&(e.onHover||e.onLeave)||e.onClick&&(n==="click"||n==="mouseup"))}var W6={id:"legend",_element:aL,start(n,e,t){const r=n.legend=new aL({ctx:n.ctx,options:t,chart:n});Ed.configure(n,r,t),Ed.addBox(n,r)},stop(n){Ed.removeBox(n,n.legend),delete n.legend},beforeUpdate(n,e,t){const r=n.legend;Ed.configure(n,r,t),r.options=t},afterUpdate(n){const e=n.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(n,e){e.replay||n.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(n,e,t){const r=e.datasetIndex,i=t.chart;i.isDatasetVisible(r)?(i.hide(r),e.hidden=!0):(i.show(r),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:n=>n.chart.options.color,boxWidth:40,padding:10,generateLabels(n){const e=n.data.datasets,{labels:{usePointStyle:t,pointStyle:r,textAlign:i,color:o,useBorderRadius:a,borderRadius:l}}=n.legend.options;return n._getSortedDatasetMetas().map(d=>{const c=d.controller.getStyle(t?0:void 0),u=sa(c.borderWidth);return{text:e[d.index].label,fillStyle:c.backgroundColor,fontColor:o,hidden:!d.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(u.width+u.height)/4,strokeStyle:c.borderColor,pointStyle:r||c.pointStyle,rotation:c.rotation,textAlign:i||c.textAlign,borderRadius:a&&(l||c.borderRadius),datasetIndex:d.index}},this)}},title:{color:n=>n.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:n=>!n.startsWith("on"),labels:{_scriptable:n=>!["generateLabels","filter","sort"].includes(n)}}};class FU extends Oo{constructor(e){super(),this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,t){const r=this.options;if(this.left=0,this.top=0,!r.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=e,this.height=this.bottom=t;const i=ki(r.text)?r.text.length:1;this._padding=sa(r.padding);const o=i*Us(r.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const e=this.options.position;return e==="top"||e==="bottom"}_drawArgs(e){const{top:t,left:r,bottom:i,right:o,options:a}=this,l=a.align;let d=0,c,u,f;return this.isHorizontal()?(u=ta(l,r,o),f=t+e,c=o-r):(a.position==="left"?(u=r+e,f=ta(l,i,t),d=Or*-.5):(u=o-e,f=ta(l,t,i),d=Or*.5),c=i-t),{titleX:u,titleY:f,maxWidth:c,rotation:d}}draw(){const e=this.ctx,t=this.options;if(!t.display)return;const r=Us(t.font),o=r.lineHeight/2+this._padding.top,{titleX:a,titleY:l,maxWidth:d,rotation:c}=this._drawArgs(o);Ej(e,t.text,0,0,r,{color:t.color,maxWidth:d,rotation:c,textAlign:E6(t.align),textBaseline:"middle",translation:[a,l]})}}function Dre(n,e){const t=new FU({ctx:n.ctx,options:e,chart:n});Ed.configure(n,t,e),Ed.addBox(n,t),n.titleBlock=t}var U6={id:"title",_element:FU,start(n,e,t){Dre(n,t)},stop(n){const e=n.titleBlock;Ed.removeBox(n,e),delete n.titleBlock},beforeUpdate(n,e,t){const r=n.titleBlock;Ed.configure(n,r,t),r.options=t},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const nS={average(n){if(!n.length)return!1;let e,t,r=new Set,i=0,o=0;for(e=0,t=n.length;el+d)/r.size,y:i/o}},nearest(n,e){if(!n.length)return!1;let t=e.x,r=e.y,i=Number.POSITIVE_INFINITY,o,a,l;for(o=0,a=n.length;o-1?n.split(` `):n}function Ere(n,e){const{element:t,datasetIndex:r,index:i}=e,o=n.getDatasetMeta(r).controller,{label:a,value:l}=o.getLabelAndValue(i);return{chart:n,label:a,parsed:o.getParsed(i),raw:n.data.datasets[r].data[i],formattedValue:l,dataset:o.getDataset(),dataIndex:i,datasetIndex:r,element:t}}function lL(n,e){const t=n.chart.ctx,{body:r,footer:i,title:o}=n,{boxWidth:a,boxHeight:l}=e,d=Us(e.bodyFont),c=Us(e.titleFont),u=Us(e.footerFont),f=o.length,p=i.length,g=r.length,m=sa(e.padding);let y=m.height,v=0,x=r.reduce((_,b)=>_+b.before.length+b.lines.length+b.after.length,0);if(x+=n.beforeBody.length+n.afterBody.length,f&&(y+=f*c.lineHeight+(f-1)*e.titleSpacing+e.titleMarginBottom),x){const _=e.displayColors?Math.max(l,d.lineHeight):d.lineHeight;y+=g*_+(x-g)*d.lineHeight+(x-1)*e.bodySpacing}p&&(y+=e.footerMarginTop+p*u.lineHeight+(p-1)*e.footerSpacing);let w=0;const S=function(_){v=Math.max(v,t.measureText(_).width+w)};return t.save(),t.font=c.string,Yr(n.title,S),t.font=d.string,Yr(n.beforeBody.concat(n.afterBody),S),w=e.displayColors?a+2+e.boxPadding:0,Yr(r,_=>{Yr(_.before,S),Yr(_.lines,S),Yr(_.after,S)}),w=0,t.font=u.string,Yr(n.footer,S),t.restore(),v+=m.width,{width:v,height:y}}function Pre(n,e){const{y:t,height:r}=e;return tn.height-r/2?"bottom":"center"}function Rre(n,e,t,r){const{x:i,width:o}=r,a=t.caretSize+t.caretPadding;if(n==="left"&&i+o+a>e.width||n==="right"&&i-o-a<0)return!0}function Bre(n,e,t,r){const{x:i,width:o}=t,{width:a,chartArea:{left:l,right:d}}=n;let c="center";return r==="center"?c=i<=(l+d)/2?"left":"right":i<=o/2?c="left":i>=a-o/2&&(c="right"),Rre(c,n,e,t)&&(c="center"),c}function dL(n,e,t){const r=t.yAlign||e.yAlign||Pre(n,t);return{xAlign:t.xAlign||e.xAlign||Bre(n,e,t,r),yAlign:r}}function Ire(n,e){let{x:t,width:r}=n;return e==="right"?t-=r:e==="center"&&(t-=r/2),t}function Mre(n,e,t){let{y:r,height:i}=n;return e==="top"?r+=t:e==="bottom"?r-=i+t:r-=i/2,r}function cL(n,e,t,r){const{caretSize:i,caretPadding:o,cornerRadius:a}=n,{xAlign:l,yAlign:d}=t,c=i+o,{topLeft:u,topRight:f,bottomLeft:p,bottomRight:g}=o0(a);let m=Ire(e,l);const y=Mre(e,d,c);return d==="center"?l==="left"?m+=c:l==="right"&&(m-=c):l==="left"?m-=Math.max(u,p)+i:l==="right"&&(m+=Math.max(f,g)+i),{x:Wl(m,0,r.width-e.width),y:Wl(y,0,r.height-e.height)}}function _2(n,e,t){const r=sa(t.padding);return e==="center"?n.x+n.width/2:e==="right"?n.x+n.width-r.right:n.x+r.left}function uL(n){return Qc([],uh(n))}function zre(n,e,t){return P0(n,{tooltip:e,tooltipItems:t,type:"tooltip"})}function hL(n,e){const t=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return t?n.override(t):n}const DU={beforeTitle:ih,title(n){if(n.length>0){const e=n[0],t=e.chart.data.labels,r=t?t.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(r>0&&e.dataIndex"u"?DU[e].call(t,r):i}class xB extends Oo{constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const t=this.chart,r=this.options.setContext(this.getContext()),i=r.enabled&&t.options.animation&&r.animations,o=new L6(this.chart,i);return i._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=zre(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,t){const{callbacks:r}=t,i=za(r,"beforeTitle",this,e),o=za(r,"title",this,e),a=za(r,"afterTitle",this,e);let l=[];return l=Qc(l,uh(i)),l=Qc(l,uh(o)),l=Qc(l,uh(a)),l}getBeforeBody(e,t){return uL(za(t.callbacks,"beforeBody",this,e))}getBody(e,t){const{callbacks:r}=t,i=[];return Yr(e,o=>{const a={before:[],lines:[],after:[]},l=hL(r,o);Qc(a.before,uh(za(l,"beforeLabel",this,o))),Qc(a.lines,za(l,"label",this,o)),Qc(a.after,uh(za(l,"afterLabel",this,o))),i.push(a)}),i}getAfterBody(e,t){return uL(za(t.callbacks,"afterBody",this,e))}getFooter(e,t){const{callbacks:r}=t,i=za(r,"beforeFooter",this,e),o=za(r,"footer",this,e),a=za(r,"afterFooter",this,e);let l=[];return l=Qc(l,uh(i)),l=Qc(l,uh(o)),l=Qc(l,uh(a)),l}_createItems(e){const t=this._active,r=this.chart.data,i=[],o=[],a=[];let l=[],d,c;for(d=0,c=t.length;de.filter(u,f,p,r))),e.itemSort&&(l=l.sort((u,f)=>e.itemSort(u,f,r))),Yr(l,u=>{const f=hL(e.callbacks,u);i.push(za(f,"labelColor",this,u)),o.push(za(f,"labelPointStyle",this,u)),a.push(za(f,"labelTextColor",this,u))}),this.labelColors=i,this.labelPointStyles=o,this.labelTextColors=a,this.dataPoints=l,l}update(e,t){const r=this.options.setContext(this.getContext()),i=this._active;let o,a=[];if(!i.length)this.opacity!==0&&(o={opacity:0});else{const l=nS[r.position].call(this,i,this._eventPosition);a=this._createItems(r),this.title=this.getTitle(a,r),this.beforeBody=this.getBeforeBody(a,r),this.body=this.getBody(a,r),this.afterBody=this.getAfterBody(a,r),this.footer=this.getFooter(a,r);const d=this._size=lL(this,r),c=Object.assign({},l,d),u=dL(this.chart,r,c),f=cL(r,c,u,this.chart);this.xAlign=u.xAlign,this.yAlign=u.yAlign,o={opacity:1,x:f.x,y:f.y,width:d.width,height:d.height,caretX:l.x,caretY:l.y}}this._tooltipItems=a,this.$context=void 0,o&&this._resolveAnimations().update(this,o),e&&r.external&&r.external.call(this,{chart:this.chart,tooltip:this,replay:t})}drawCaret(e,t,r,i){const o=this.getCaretPosition(e,r,i);t.lineTo(o.x1,o.y1),t.lineTo(o.x2,o.y2),t.lineTo(o.x3,o.y3)}getCaretPosition(e,t,r){const{xAlign:i,yAlign:o}=this,{caretSize:a,cornerRadius:l}=r,{topLeft:d,topRight:c,bottomLeft:u,bottomRight:f}=o0(l),{x:p,y:g}=e,{width:m,height:y}=t;let v,x,w,S,_,b;return o==="center"?(_=g+y/2,i==="left"?(v=p,x=v-a,S=_+a,b=_-a):(v=p+m,x=v+a,S=_-a,b=_+a),w=v):(i==="left"?x=p+Math.max(d,u)+a:i==="right"?x=p+m-Math.max(c,f)-a:x=this.caretX,o==="top"?(S=g,_=S-a,v=x-a,w=x+a):(S=g+y,_=S+a,v=x+a,w=x-a),b=S),{x1:v,x2:x,x3:w,y1:S,y2:_,y3:b}}drawTitle(e,t,r){const i=this.title,o=i.length;let a,l,d;if(o){const c=ib(r.rtl,this.x,this.width);for(e.x=_2(this,r.titleAlign,r),t.textAlign=c.textAlign(r.titleAlign),t.textBaseline="middle",a=Us(r.titleFont),l=r.titleSpacing,t.fillStyle=r.titleColor,t.font=a.string,d=0;dw!==0)?(e.beginPath(),e.fillStyle=o.multiKeyBackground,Pj(e,{x:y,y:m,w:c,h:d,radius:x}),e.fill(),e.stroke(),e.fillStyle=a.backgroundColor,e.beginPath(),Pj(e,{x:v,y:m+1,w:c-2,h:d-2,radius:x}),e.fill()):(e.fillStyle=o.multiKeyBackground,e.fillRect(y,m,c,d),e.strokeRect(y,m,c,d),e.fillStyle=a.backgroundColor,e.fillRect(v,m+1,c-2,d-2))}e.fillStyle=this.labelTextColors[r]}drawBody(e,t,r){const{body:i}=this,{bodySpacing:o,bodyAlign:a,displayColors:l,boxHeight:d,boxWidth:c,boxPadding:u}=r,f=Us(r.bodyFont);let p=f.lineHeight,g=0;const m=ib(r.rtl,this.x,this.width),y=function(F){t.fillText(F,m.x(e.x+g),e.y+p/2),e.y+=p+o},v=m.textAlign(a);let x,w,S,_,b,C,T;for(t.textAlign=a,t.textBaseline="middle",t.font=f.string,e.x=_2(this,v,r),t.fillStyle=r.bodyColor,Yr(this.beforeBody,y),g=l&&v!=="right"?a==="center"?c/2+u:c+2+u:0,_=0,C=i.length;_0&&t.stroke()}_updateAnimationTarget(e){const t=this.chart,r=this.$animations,i=r&&r.x,o=r&&r.y;if(i||o){const a=nS[e.position].call(this,this._active,this._eventPosition);if(!a)return;const l=this._size=lL(this,e),d=Object.assign({},a,this._size),c=dL(t,e,d),u=cL(e,d,c,t);(i._to!==u.x||o._to!==u.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=l.width,this.height=l.height,this.caretX=a.x,this.caretY=a.y,this._resolveAnimations().update(this,u))}}_willRender(){return!!this.opacity}draw(e){const t=this.options.setContext(this.getContext());let r=this.opacity;if(!r)return;this._updateAnimationTarget(t);const i={width:this.width,height:this.height},o={x:this.x,y:this.y};r=Math.abs(r)<.001?0:r;const a=sa(t.padding),l=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;t.enabled&&l&&(e.save(),e.globalAlpha=r,this.drawBackground(o,e,i,t),uU(e,t.textDirection),o.y+=a.top,this.drawTitle(o,e,t),this.drawBody(o,e,t),this.drawFooter(o,e,t),hU(e,t.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,t){const r=this._active,i=e.map(({datasetIndex:l,index:d})=>{const c=this.chart.getDatasetMeta(l);if(!c)throw new Error("Cannot find a dataset at index "+l);return{datasetIndex:l,element:c.data[d],index:d}}),o=!HA(r,i),a=this._positionChanged(i,t);(o||a)&&(this._active=i,this._eventPosition=t,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,t,r=!0){if(t&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const i=this.options,o=this._active||[],a=this._getActiveElements(e,o,t,r),l=this._positionChanged(a,e),d=t||!HA(a,o)||l;return d&&(this._active=a,(i.enabled||i.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,t))),d}_getActiveElements(e,t,r,i){const o=this.options;if(e.type==="mouseout")return[];if(!i)return t.filter(l=>this.chart.data.datasets[l.datasetIndex]&&this.chart.getDatasetMeta(l.datasetIndex).controller.getParsed(l.index)!==void 0);const a=this.chart.getElementsAtEventForMode(e,o.mode,o,r);return o.reverse&&a.reverse(),a}_positionChanged(e,t){const{caretX:r,caretY:i,options:o}=this,a=nS[o.position].call(this,e,t);return a!==!1&&(r!==a.x||i!==a.y)}}ve(xB,"positioners",nS);var H6={id:"tooltip",_element:xB,positioners:nS,afterInit(n,e,t){t&&(n.tooltip=new xB({chart:n,options:t}))},beforeUpdate(n,e,t){n.tooltip&&n.tooltip.initialize(t)},reset(n,e,t){n.tooltip&&n.tooltip.initialize(t)},afterDraw(n){const e=n.tooltip;if(e&&e._willRender()){const t={tooltip:e};if(n.notifyPlugins("beforeTooltipDraw",{...t,cancelable:!0})===!1)return;e.draw(n.ctx),n.notifyPlugins("afterTooltipDraw",t)}},afterEvent(n,e){if(n.tooltip){const t=e.replay;n.tooltip.handleEvent(e.event,t,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(n,e)=>e.bodyFont.size,boxWidth:(n,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:DU},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:n=>n!=="filter"&&n!=="itemSort"&&n!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};const Ore=(n,e,t,r)=>(typeof e=="string"?(t=n.push(e)-1,r.unshift({index:t,label:e})):isNaN(e)&&(t=null),t);function Lre(n,e,t,r){const i=n.indexOf(e);if(i===-1)return Ore(n,e,t,r);const o=n.lastIndexOf(e);return i!==o?t:i}const Nre=(n,e)=>n===null?null:Wl(Math.round(n),0,e);function fL(n){const e=this.getLabels();return n>=0&&nt.length-1?null:this.getPixelForValue(t[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}ve(Bj,"id","category"),ve(Bj,"defaults",{ticks:{callback:fL}});function Wre(n,e){const t=[],{bounds:i,step:o,min:a,max:l,precision:d,count:c,maxTicks:u,maxDigits:f,includeBounds:p}=n,g=o||1,m=u-1,{min:y,max:v}=e,x=!Ur(a),w=!Ur(l),S=!Ur(c),_=(v-y)/(f+1);let b=gO((v-y)/m/g)*g,C,T,F,A;if(b<1e-14&&!x&&!w)return[{value:y},{value:v}];A=Math.ceil(v/b)-Math.floor(y/b),A>m&&(b=gO(A*b/m/g)*g),Ur(d)||(C=Math.pow(10,d),b=Math.ceil(b*C)/C),i==="ticks"?(T=Math.floor(y/b)*b,F=Math.ceil(v/b)*b):(T=y,F=v),x&&w&&o&&yee((l-a)/o,b/1e3)?(A=Math.round(Math.min((l-a)/b,u)),b=(l-a)/A,T=a,F=l):S?(T=x?a:T,F=w?l:F,A=c-1,b=(F-T)/A):(A=(F-T)/b,HS(A,Math.round(A),b/1e3)?A=Math.round(A):A=Math.ceil(A));const D=Math.max(mO(b),mO(T));C=Math.pow(10,Ur(d)?D:d),T=Math.round(T*C)/C,F=Math.round(F*C)/C;let P=0;for(x&&(p&&T!==a?(t.push({value:a}),Tl)break;t.push({value:L})}return w&&p&&F!==l?t.length&&HS(t[t.length-1].value,l,pL(l,_,n))?t[t.length-1].value=l:t.push({value:l}):(!w||F===l)&&t.push({value:F}),t}function pL(n,e,{horizontal:t,minRotation:r}){const i=fo(r),o=(t?Math.sin(i):Math.cos(i))||.001,a=.75*e*(""+n).length;return Math.min(e/o,a)}class Ure extends m1{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,t){return Ur(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:t,maxDefined:r}=this.getUserBounds();let{min:i,max:o}=this;const a=d=>i=t?i:d,l=d=>o=r?o:d;if(e){const d=zu(i),c=zu(o);d<0&&c<0?l(0):d>0&&c>0&&a(0)}if(i===o){let d=o===0?1:Math.abs(o*.05);l(o+d),e||a(i-d)}this.min=i,this.max=o}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:t,stepSize:r}=e,i;return r?(i=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,i>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${i} ticks. Limiting to 1000.`),i=1e3)):(i=this.computeTickLimit(),t=t||11),t&&(i=Math.min(t,i)),i}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,t=e.ticks;let r=this.getTickLimit();r=Math.max(2,r);const i={maxTicks:r,bounds:e.bounds,min:e.min,max:e.max,precision:t.precision,step:t.stepSize,count:t.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:t.minRotation||0,includeBounds:t.includeBounds!==!1},o=this._range||this,a=Wre(i,o);return e.bounds==="ticks"&&xee(a,this,"value"),e.reverse?(a.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),a}configure(){const e=this.ticks;let t=this.min,r=this.max;if(super.configure(),this.options.offset&&e.length){const i=(r-t)/Math.max(e.length-1,1)/2;t-=i,r+=i}this._startValue=t,this._endValue=r,this._valueRange=r-t}getLabelForValue(e){return R6(e,this.chart.options.locale,this.options.ticks.format)}}class Ij extends Ure{determineDataLimits(){const{min:e,max:t}=this.getMinMax(!0);this.min=sl(e)?e:0,this.max=sl(t)?t:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),t=e?this.width:this.height,r=fo(this.options.ticks.minRotation),i=(e?Math.sin(r):Math.cos(r))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(t/Math.min(40,o.lineHeight/i))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}ve(Ij,"id","linear"),ve(Ij,"defaults",{ticks:{callback:nU.formatters.numeric}});const _F={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Za=Object.keys(_F);function gL(n,e){return n-e}function mL(n,e){if(Ur(e))return null;const t=n._adapter,{parser:r,round:i,isoWeekday:o}=n._parseOpts;let a=e;return typeof r=="function"&&(a=r(a)),sl(a)||(a=typeof r=="string"?t.parse(a,r):t.parse(a)),a===null?null:(i&&(a=i==="week"&&(m0(o)||o===!0)?t.startOf(a,"isoWeek",o):t.startOf(a,i)),+a)}function yL(n,e,t,r){const i=Za.length;for(let o=Za.indexOf(n);o=Za.indexOf(t);o--){const a=Za[o];if(_F[a].common&&n._adapter.diff(i,r,a)>=e-1)return a}return Za[t?Za.indexOf(t):0]}function qre(n){for(let e=Za.indexOf(n)+1,t=Za.length;e=e?t[r]:t[i];n[o]=!0}}function Vre(n,e,t,r){const i=n._adapter,o=+i.startOf(e[0].value,r),a=e[e.length-1].value;let l,d;for(l=o;l<=a;l=+i.add(l,1,r))d=t[l],d>=0&&(e[d].major=!0);return e}function bL(n,e,t){const r=[],i={},o=e.length;let a,l;for(a=0;a+e.value))}initOffsets(e=[]){let t=0,r=0,i,o;this.options.offset&&e.length&&(i=this.getDecimalForValue(e[0]),e.length===1?t=1-i:t=(this.getDecimalForValue(e[1])-i)/2,o=this.getDecimalForValue(e[e.length-1]),e.length===1?r=o:r=(o-this.getDecimalForValue(e[e.length-2]))/2);const a=e.length<3?.5:.25;t=Wl(t,0,a),r=Wl(r,0,a),this._offsets={start:t,end:r,factor:1/(t+1+r)}}_generate(){const e=this._adapter,t=this.min,r=this.max,i=this.options,o=i.time,a=o.unit||yL(o.minUnit,t,r,this._getLabelCapacity(t)),l=In(i.ticks.stepSize,1),d=a==="week"?o.isoWeekday:!1,c=m0(d)||d===!0,u={};let f=t,p,g;if(c&&(f=+e.startOf(f,"isoWeek",d)),f=+e.startOf(f,c?"day":a),e.diff(r,t,a)>1e5*l)throw new Error(t+" and "+r+" are too far apart with stepSize of "+l+" "+a);const m=i.ticks.source==="data"&&this.getDataTimestamps();for(p=f,g=0;p+y)}getLabelForValue(e){const t=this._adapter,r=this.options.time;return r.tooltipFormat?t.format(e,r.tooltipFormat):t.format(e,r.displayFormats.datetime)}format(e,t){const i=this.options.time.displayFormats,o=this._unit,a=t||i[o];return this._adapter.format(e,a)}_tickFormatFunction(e,t,r,i){const o=this.options,a=o.ticks.callback;if(a)return li(a,[e,t,r],this);const l=o.time.displayFormats,d=this._unit,c=this._majorUnit,u=d&&l[d],f=c&&l[c],p=r[t],g=c&&f&&p&&p.major;return this._adapter.format(e,i||(g?f:u))}generateTickLabels(e){let t,r,i;for(t=0,r=e.length;t0?l:1}getDataTimestamps(){let e=this._cache.data||[],t,r;if(e.length)return e;const i=this.getMatchingVisibleMetas();if(this._normalized&&i.length)return this._cache.data=i[0].controller.getAllParsedValues(this);for(t=0,r=i.length;t=n[r].pos&&e<=n[i].pos&&({lo:r,hi:i}=vm(n,"pos",e)),{pos:o,time:l}=n[r],{pos:a,time:d}=n[i]):(e>=n[r].time&&e<=n[i].time&&({lo:r,hi:i}=vm(n,"time",e)),{time:o,pos:l}=n[r],{time:a,pos:d}=n[i]);const c=a-o;return c?l+(d-l)*(e-o)/c:l}class vL extends QA{constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),t=this._table=this.buildLookupTable(e);this._minPos=C2(t,this.min),this._tableRange=C2(t,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:t,max:r}=this,i=[],o=[];let a,l,d,c,u;for(a=0,l=e.length;a=t&&c<=r&&i.push(c);if(i.length<2)return[{time:t,pos:0},{time:r,pos:1}];for(a=0,l=i.length;ai-o)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const t=this.getDataTimestamps(),r=this.getLabelTimestamps();return t.length&&r.length?e=this.normalize(t.concat(r)):e=t.length?t:r,e=this._cache.all=e,e}getDecimalForValue(e){return(C2(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const t=this._offsets,r=this.getDecimalForPixel(e)/t.factor-t.end;return C2(this._table,r*this._tableRange+this._minPos,!0)}}ve(vL,"id","timeseries"),ve(vL,"defaults",QA.defaults);const EU="label";function wL(n,e){typeof n=="function"?n(e):n&&(n.current=e)}function Gre(n,e){const t=n.options;t&&e&&Object.assign(t,e)}function PU(n,e){n.labels=e}function RU(n,e,t=EU){const r=[];n.datasets=e.map(i=>{const o=n.datasets.find(a=>a[t]===i[t]);return!o||!i.data||r.includes(o)?{...i}:(r.push(o),Object.assign(o,i),o)})}function Kre(n,e=EU){const t={labels:[],datasets:[]};return PU(t,n.labels),RU(t,n.datasets,e),t}function Xre(n,e){const{height:t=150,width:r=300,redraw:i=!1,datasetIdKey:o,type:a,data:l,options:d,plugins:c=[],fallbackContent:u,updateMode:f,...p}=n,g=k.useRef(null),m=k.useRef(null),y=()=>{g.current&&(m.current=new pf(g.current,{type:a,data:Kre(l,o),options:d&&{...d},plugins:c}),wL(e,m.current))},v=()=>{wL(e,null),m.current&&(m.current.destroy(),m.current=null)};return k.useEffect(()=>{!i&&m.current&&d&&Gre(m.current,d)},[i,d]),k.useEffect(()=>{!i&&m.current&&PU(m.current.config.data,l.labels)},[i,l.labels]),k.useEffect(()=>{!i&&m.current&&l.datasets&&RU(m.current.config.data,l.datasets,o)},[i,l.datasets]),k.useEffect(()=>{m.current&&(i?(v(),setTimeout(y)):m.current.update(f))},[i,d,l.labels,l.datasets,f]),k.useEffect(()=>{m.current&&(v(),setTimeout(y))},[a]),k.useEffect(()=>(y(),()=>v()),[]),s.jsx("canvas",{ref:g,role:"img",height:t,width:r,...p,children:u})}const Yre=k.forwardRef(Xre);function BU(n,e){return pf.register(e),k.forwardRef((t,r)=>s.jsx(Yre,{...t,ref:r,type:n}))}const IU=BU("line",p5),Qre=BU("bar",f5);/*! * chartjs-plugin-annotation v3.1.0 * https://www.chartjs.org/chartjs-plugin-annotation/index * (c) 2024 chartjs-plugin-annotation Contributors * Released under the MIT License */const SL={modes:{point(n,e){return x5(n,e,{intersect:!0})},nearest(n,e,t){return Jre(n,e,t)},x(n,e,t){return x5(n,e,{intersect:t.intersect,axis:"x"})},y(n,e,t){return x5(n,e,{intersect:t.intersect,axis:"y"})}}};function q6(n,e,t){return(SL.modes[t.mode]||SL.modes.nearest)(n,e,t)}function $re(n,e,t){return t!=="x"&&t!=="y"?n.inRange(e.x,e.y,"x",!0)||n.inRange(e.x,e.y,"y",!0):n.inRange(e.x,e.y,t,!0)}function Zre(n,e,t){return t==="x"?{x:n.x,y:e.y}:t==="y"?{x:e.x,y:n.y}:e}function x5(n,e,t){return n.filter(r=>t.intersect?r.inRange(e.x,e.y):$re(r,e,t.axis))}function Jre(n,e,t){let r=Number.POSITIVE_INFINITY;return x5(n,e,t).reduce((i,o)=>{const a=o.getCenterPoint(),l=Zre(e,a,t.axis),d=r1(e,l);return di._index-o._index).slice(0,1)}function R0(n,e,t){const r=Math.cos(t),i=Math.sin(t),o=e.x,a=e.y;return{x:o+r*(n.x-o)-i*(n.y-a),y:a+i*(n.x-o)+r*(n.y-a)}}const eie=(n,e)=>e>n||n.length>e.length&&n.slice(0,e.length)===e,wm=.001,CF=(n,e,t)=>Math.min(t,Math.max(e,n)),MU=(n,e)=>n.value>=n.start-e&&n.value<=n.end+e;function tie(n,e,t){for(const r of Object.keys(n))n[r]=CF(n[r],e,t);return n}function nie(n,e,t,r){return!n||!e||t<=0?!1:Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)<=Math.pow(t+r,2)}function zU(n,{x:e,y:t,x2:r,y2:i},o,{borderWidth:a,hitTolerance:l}){const d=(a+l)/2,c=n.x>=e-d-wm&&n.x<=r+d+wm,u=n.y>=t-d-wm&&n.y<=i+d+wm;return o==="x"?c:(o==="y"||c)&&u}function OU(n,{rect:e,center:t},r,{rotation:i,borderWidth:o,hitTolerance:a}){const l=R0(n,t,fo(-i));return zU(l,e,r,{borderWidth:o,hitTolerance:a})}function B0(n,e){const{centerX:t,centerY:r}=n.getProps(["centerX","centerY"],e);return{x:t,y:r}}function rie(n,e,t,r=!0){const i=t.split(".");let o=0;for(const a of e.split(".")){const l=i[o++];if(parseInt(a,10)typeof n=="string"&&n.endsWith("%"),NU=n=>parseFloat(n)/100,WU=n=>CF(NU(n),0,1),Rw=(n,e)=>({x:n,y:e,x2:n,y2:e,width:0,height:0}),iie={box:n=>Rw(n.centerX,n.centerY),doughnutLabel:n=>Rw(n.centerX,n.centerY),ellipse:n=>({centerX:n.centerX,centerY:n.centerX,radius:0,width:0,height:0}),label:n=>Rw(n.centerX,n.centerY),line:n=>Rw(n.x,n.y),point:n=>({centerX:n.centerX,centerY:n.centerY,radius:0,width:0,height:0}),polygon:n=>Rw(n.centerX,n.centerY)};function V6(n,e){return e==="start"?0:e==="end"?n:LU(e)?WU(e)*n:n/2}function Mg(n,e,t=!0){return typeof e=="number"?e:LU(e)?(t?WU(e):NU(e))*n:n}function sie(n,e){const{x:t,width:r}=n,i=e.textAlign;return i==="center"?t+r/2:i==="end"||i==="right"?t+r:t}function UU(n,e,{borderWidth:t,position:r,xAdjust:i,yAdjust:o},a){const l=Yn(a),d=e.width+(l?a.width:0)+t,c=e.height+(l?a.height:0)+t,u=G6(r),f=jL(n.x,d,i,u.x),p=jL(n.y,c,o,u.y);return{x:f,y:p,x2:f+d,y2:p+c,width:d,height:c,centerX:f+d/2,centerY:p+c/2}}function G6(n,e="center"){return Yn(n)?{x:In(n.x,e),y:In(n.y,e)}:(n=In(n,e),{x:n,y:n})}const HU=(n,e)=>n&&n.autoFit&&e<1;function qU(n,e){const t=n.font,r=ki(t)?t:[t];return HU(n,e)?r.map(function(i){const o=Us(i);return o.size=Math.floor(i.size*e),o.lineHeight=i.lineHeight,Us(o)}):r.map(i=>Us(i))}function VU(n){return n&&(ol(n.xValue)||ol(n.yValue))}function jL(n,e,t=0,r){return n-V6(e,r)+t}function y1(n,e,t){const r=t.init;if(r){if(r===!0)return KU(e,t)}else return;return oie(n,e,t)}function GU(n,e,t){let r=!1;return e.forEach(i=>{il(n[i])?(r=!0,t[i]=n[i]):ol(t[i])&&delete t[i]}),r}function KU(n,e){const t=e.type||"line";return iie[t](n)}function oie(n,e,t){const r=li(t.init,[{chart:n,properties:e,options:t}]);if(r===!0)return KU(e,t);if(Yn(r))return r}const xP=new Map,aie=n=>isNaN(n)||n<=0,lie=n=>n.reduce(function(e,t){return e+=t.string,e},"");function AF(n){if(n&&typeof n=="object"){const e=n.toString();return e==="[object HTMLImageElement]"||e==="[object HTMLCanvasElement]"}}function TF(n,{x:e,y:t},r){r&&(n.translate(e,t),n.rotate(fo(r)),n.translate(-e,-t))}function Cf(n,e){if(e&&e.borderWidth)return n.lineCap=e.borderCapStyle||"butt",n.setLineDash(e.borderDash),n.lineDashOffset=e.borderDashOffset,n.lineJoin=e.borderJoinStyle||"miter",n.lineWidth=e.borderWidth,n.strokeStyle=e.borderColor,!0}function x1(n,e){n.shadowColor=e.backgroundShadowColor,n.shadowBlur=e.shadowBlur,n.shadowOffsetX=e.shadowOffsetX,n.shadowOffsetY=e.shadowOffsetY}function FF(n,e){const t=e.content;if(AF(t))return{width:Mg(t.width,e.width),height:Mg(t.height,e.height)};const r=qU(e),i=e.textStrokeWidth,o=ki(t)?t:[t],a=o.join()+lie(r)+i+(n._measureText?"-spriting":"");return xP.has(a)||xP.set(a,hie(n,o,r,i)),xP.get(a)}function XU(n,e,t){const{x:r,y:i,width:o,height:a}=e;n.save(),x1(n,t);const l=Cf(n,t);n.fillStyle=t.backgroundColor,n.beginPath(),Pj(n,{x:r,y:i,w:o,h:a,radius:tie(o0(t.borderRadius),0,Math.min(o,a)/2)}),n.closePath(),n.fill(),l&&(n.shadowColor=t.borderShadowColor,n.stroke()),n.restore()}function YU(n,e,t,r){const i=t.content;if(AF(i)){n.save(),n.globalAlpha=gie(t.opacity,i.style.opacity),n.drawImage(i,e.x,e.y,e.width,e.height),n.restore();return}const o=ki(i)?i:[i],a=qU(t,r),l=t.color,d=ki(l)?l:[l],c=sie(e,t),u=e.y+t.textStrokeWidth/2;n.save(),n.textBaseline="middle",n.textAlign=t.textAlign,die(n,t)&&fie(n,{x:c,y:u},o,a),pie(n,{x:c,y:u},o,{fonts:a,colors:d}),n.restore()}function die(n,e){if(e.textStrokeWidth>0)return n.lineJoin="round",n.miterLimit=2,n.lineWidth=e.textStrokeWidth,n.strokeStyle=e.textStrokeColor,!0}function cie(n,e,t,r){const{radius:i,options:o}=e,a=o.pointStyle,l=o.rotation;let d=(l||0)*F6;if(AF(a)){n.save(),n.translate(t,r),n.rotate(d),n.drawImage(a,-a.width/2,-a.height/2,a.width,a.height),n.restore();return}aie(i)||uie(n,{x:t,y:r,radius:i,rotation:l,style:a,rad:d})}function uie(n,{x:e,y:t,radius:r,rotation:i,style:o,rad:a}){let l,d,c,u;switch(n.beginPath(),o){default:n.arc(e,t,r,0,Eo),n.closePath();break;case"triangle":n.moveTo(e+Math.sin(a)*r,t-Math.cos(a)*r),a+=GA,n.lineTo(e+Math.sin(a)*r,t-Math.cos(a)*r),a+=GA,n.lineTo(e+Math.sin(a)*r,t-Math.cos(a)*r),n.closePath();break;case"rectRounded":u=r*.516,c=r-u,l=Math.cos(a+jd)*c,d=Math.sin(a+jd)*c,n.arc(e-l,t-d,u,a-Or,a-Po),n.arc(e+d,t-l,u,a-Po,a),n.arc(e+l,t+d,u,a,a+Po),n.arc(e-d,t+l,u,a+Po,a+Or),n.closePath();break;case"rect":if(!i){c=Math.SQRT1_2*r,n.rect(e-c,t-c,2*c,2*c);break}a+=jd;case"rectRot":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+d,t-l),n.lineTo(e+l,t+d),n.lineTo(e-d,t+l),n.closePath();break;case"crossRot":a+=jd;case"cross":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d),n.moveTo(e+d,t-l),n.lineTo(e-d,t+l);break;case"star":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d),n.moveTo(e+d,t-l),n.lineTo(e-d,t+l),a+=jd,l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d),n.moveTo(e+d,t-l),n.lineTo(e-d,t+l);break;case"line":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d);break;case"dash":n.moveTo(e,t),n.lineTo(e+Math.cos(a)*r,t+Math.sin(a)*r);break}n.fill()}function hie(n,e,t,r){n.save();const i=e.length;let o=0,a=r;for(let l=0;l0||i.borderWidth===0)&&(n.moveTo(d.x,d.y),n.lineTo(c.x,c.y)),n.moveTo(u.x,u.y),n.lineTo(f.x,f.y);const p=R0({x:t,y:r},e.getCenterPoint(),fo(-e.rotation));n.lineTo(p.x,p.y),n.stroke(),n.restore()}function yie(n,e){const{x:t,y:r,x2:i,y2:o}=n,a=xie(n,e);let l,d;return e==="left"||e==="right"?(l={x:t+a,y:r},d={x:l.x,y:o}):(l={x:t,y:r+a},d={x:i,y:l.y}),{separatorStart:l,separatorEnd:d}}function xie(n,e){const{width:t,height:r,options:i}=n,o=i.callout.margin+i.borderWidth/2;return e==="right"?t+o:e==="bottom"?r+o:-o}function bie(n,e,t){const{y:r,width:i,height:o,options:a}=n,l=a.callout.start,d=vie(e,a.callout);let c,u;return e==="left"||e==="right"?(c={x:t.x,y:r+Mg(o,l)},u={x:c.x+d,y:c.y}):(c={x:t.x+Mg(i,l),y:t.y},u={x:c.x,y:c.y+d}),{sideStart:c,sideEnd:u}}function vie(n,e){const t=e.side;return n==="left"||n==="top"?-t:t}function wie(n,e){const t=e.position;return QU.includes(t)?t:Sie(n,e)}function Sie(n,e){const{x:t,y:r,x2:i,y2:o,width:a,height:l,pointX:d,pointY:c,centerX:u,centerY:f,rotation:p}=n,g={x:u,y:f},m=e.start,y=Mg(a,m),v=Mg(l,m),x=[t,t+y,t+y,i],w=[r+v,o,r,o],S=[];for(let _=0;_<4;_++){const b=R0({x:x[_],y:w[_]},g,fo(p));S.push({position:QU[_],distance:r1(b,{x:d,y:c})})}return S.sort((_,b)=>_.distance-b.distance)[0].position}function jie(n,e,t){const{pointX:r,pointY:i}=n,o=e.margin;let a=r,l=i;return t==="left"?a+=o:t==="right"?a-=o:t==="top"?l+=o:t==="bottom"&&(l-=o),n.inRange(a,l)}const kL={xScaleID:{min:"xMin",max:"xMax",start:"left",end:"right",startProp:"x",endProp:"x2"},yScaleID:{min:"yMin",max:"yMax",start:"bottom",end:"top",startProp:"y",endProp:"y2"}};function o1(n,e,t){return e=typeof e=="number"?e:n.parse(e),sl(e)?n.getPixelForValue(e):t}function x0(n,e,t){const r=e[t];if(r||t==="scaleID")return r;const i=t.charAt(0),o=Object.values(n).filter(a=>a.axis&&a.axis===i);return o.length?o[0].id:i}function $U(n,e){if(n){const t=n.options.reverse,r=o1(n,e.min,t?e.end:e.start),i=o1(n,e.max,t?e.start:e.end);return{start:r,end:i}}}function ZU(n,e){const{chartArea:t,scales:r}=n,i=r[x0(r,e,"xScaleID")],o=r[x0(r,e,"yScaleID")];let a=t.width/2,l=t.height/2;return i&&(a=o1(i,e.xValue,i.left+i.width/2)),o&&(l=o1(o,e.yValue,o.top+o.height/2)),{x:a,y:l}}function K6(n,e){const t=n.scales,r=t[x0(t,e,"xScaleID")],i=t[x0(t,e,"yScaleID")];if(!r&&!i)return{};let{left:o,right:a}=r||n.chartArea,{top:l,bottom:d}=i||n.chartArea;const c=_L(r,{min:e.xMin,max:e.xMax,start:o,end:a});o=c.start,a=c.end;const u=_L(i,{min:e.yMin,max:e.yMax,start:d,end:l});return l=u.start,d=u.end,{x:o,y:l,x2:a,y2:d,width:a-o,height:d-l,centerX:o+(a-o)/2,centerY:l+(d-l)/2}}function JU(n,e){if(!VU(e)){const t=K6(n,e);let r=e.radius;(!r||isNaN(r))&&(r=Math.min(t.width,t.height)/2,e.radius=r);const i=r*2,o=t.centerX+e.xAdjust,a=t.centerY+e.yAdjust;return{x:o-r,y:a-r,x2:o+r,y2:a+r,centerX:o,centerY:a,width:i,height:i,radius:r}}return _ie(n,e)}function kie(n,e){const{scales:t,chartArea:r}=n,i=t[e.scaleID],o={x:r.left,y:r.top,x2:r.right,y2:r.bottom};return i?Cie(i,o,e):Aie(t,o,e),o}function eH(n,e){const t=K6(n,e);return t.initProperties=y1(n,t,e),t.elements=[{type:"label",optionScope:"label",properties:Die(n,t,e),initProperties:t.initProperties}],t}function _ie(n,e){const t=ZU(n,e),r=e.radius*2;return{x:t.x-e.radius+e.xAdjust,y:t.y-e.radius+e.yAdjust,x2:t.x+e.radius+e.xAdjust,y2:t.y+e.radius+e.yAdjust,centerX:t.x+e.xAdjust,centerY:t.y+e.yAdjust,radius:e.radius,width:r,height:r}}function _L(n,e){const t=$U(n,e)||e;return{start:Math.min(t.start,t.end),end:Math.max(t.start,t.end)}}function Cie(n,e,t){const r=o1(n,t.value,NaN),i=o1(n,t.endValue,r);n.isHorizontal()?(e.x=r,e.x2=i):(e.y=r,e.y2=i)}function Aie(n,e,t){for(const r of Object.keys(kL)){const i=n[x0(n,t,r)];if(i){const{min:o,max:a,start:l,end:d,startProp:c,endProp:u}=kL[r],f=$U(i,{min:t[o],max:t[a],start:i[l],end:i[d]});e[c]=f.start,e[u]=f.end}}}function Tie({properties:n,options:e},t,r,i){const{x:o,x2:a,width:l}=n;return tH({start:o,end:a,borderWidth:e.borderWidth},{position:r.x,padding:{start:i.left,end:i.right},adjust:e.label.xAdjust,size:t.width})}function Fie({properties:n,options:e},t,r,i){const{y:o,y2:a,height:l}=n;return tH({start:o,end:a,borderWidth:e.borderWidth},{position:r.y,padding:{start:i.top,end:i.bottom},adjust:e.label.yAdjust,size:t.height})}function tH(n,e){const{start:t,end:r,borderWidth:i}=n,{position:o,padding:{start:a,end:l},adjust:d}=e,c=r-i-t-a-l-e.size;return t+i/2+d+V6(c,o)}function Die(n,e,t){const r=t.label;r.backgroundColor="transparent",r.callout.display=!1;const i=G6(r.position),o=sa(r.padding),a=FF(n.ctx,r),l=Tie({properties:e,options:t},a,i,o),d=Fie({properties:e,options:t},a,i,o),c=a.width+o.width,u=a.height+o.height;return{x:l,y:d,x2:l+c,y2:d+u,width:c,height:u,centerX:l+c/2,centerY:d+u/2,rotation:r.rotation}}const bB=["enter","leave"],X6=bB.concat("click");function Eie(n,e,t){e.listened=GU(t,X6,e.listeners),e.moveListened=!1,bB.forEach(r=>{il(t[r])&&(e.moveListened=!0)}),(!e.listened||!e.moveListened)&&e.annotations.forEach(r=>{!e.listened&&il(r.click)&&(e.listened=!0),e.moveListened||bB.forEach(i=>{il(r[i])&&(e.listened=!0,e.moveListened=!0)})})}function Pie(n,e,t){if(n.listened)switch(e.type){case"mousemove":case"mouseout":return Rie(n,e,t);case"click":return Bie(n,e,t)}}function Rie(n,e,t){if(!n.moveListened)return;let r;e.type==="mousemove"?r=q6(n.visibleElements,e,t.interaction):r=[];const i=n.hovered;n.hovered=r;const o={state:n,event:e};let a=CL(o,"leave",i,r);return CL(o,"enter",r,i)||a}function CL({state:n,event:e},t,r,i){let o;for(const a of r)i.indexOf(a)<0&&(o=nH(a.options[t]||n.listeners[t],a,e)||o);return o}function Bie(n,e,t){const r=n.listeners,i=q6(n.visibleElements,e,t.interaction);let o;for(const a of i)o=nH(a.options.click||r.click,a,e)||o;return o}function nH(n,e,t){return li(n,[e.$context,t])===!0}const $A=["afterDraw","beforeDraw"];function Iie(n,e,t){const r=e.visibleElements;e.hooked=GU(t,$A,e.hooks),e.hooked||r.forEach(i=>{e.hooked||$A.forEach(o=>{il(i.options[o])&&(e.hooked=!0)})})}function AL(n,e,t){if(n.hooked){const r=e.options[t]||n.hooks[t];return li(r,[e.$context])}}function Mie(n,e,t){const r=Wie(n.scales,e,t);let i=TL(e,r,"min","suggestedMin");i=TL(e,r,"max","suggestedMax")||i,i&&il(e.handleTickRangeOptions)&&e.handleTickRangeOptions()}function zie(n,e){for(const t of n)Lie(t,e)}function TL(n,e,t,r){if(sl(e[t])&&!Oie(n.options,t,r)){const i=n[t]!==e[t];return n[t]=e[t],i}}function Oie(n,e,t){return ol(n[e])||ol(n[t])}function Lie(n,e){for(const t of["scaleID","xScaleID","yScaleID"]){const r=x0(e,n,t);r&&!e[r]&&Nie(n,t)&&console.warn(`No scale found with id '${r}' for annotation '${n.id}'`)}}function Nie(n,e){if(e==="scaleID")return!0;const t=e.charAt(0);for(const r of["Min","Max","Value"])if(ol(n[t+r]))return!0;return!1}function Wie(n,e,t){const r=e.axis,i=e.id,o=r+"ScaleID",a={min:In(e.min,Number.NEGATIVE_INFINITY),max:In(e.max,Number.POSITIVE_INFINITY)};for(const l of t)l.scaleID===i?FL(l,e,["value","endValue"],a):x0(n,l,o)===i&&FL(l,e,[r+"Min",r+"Max",r+"Value"],a);return a}function FL(n,e,t,r){for(const i of t){const o=n[i];if(ol(o)){const a=e.parse(o);r.min=Math.min(r.min,a),r.max=Math.max(r.max,a)}}}class b1 extends Oo{inRange(e,t,r,i){const{x:o,y:a}=R0({x:e,y:t},this.getCenterPoint(i),fo(-this.options.rotation));return zU({x:o,y:a},this.getProps(["x","y","x2","y2"],i),r,this.options)}getCenterPoint(e){return B0(this,e)}draw(e){e.save(),TF(e,this.getCenterPoint(),this.options.rotation),XU(e,this,this.options),e.restore()}get label(){return this.elements&&this.elements[0]}resolveElementProperties(e,t){return eH(e,t)}}b1.id="boxAnnotation";b1.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderRadius:0,borderShadowColor:"transparent",borderWidth:1,display:!0,init:void 0,hitTolerance:0,label:{backgroundColor:"transparent",borderWidth:0,callout:{display:!1},color:"black",content:null,display:!1,drawTime:void 0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:"bold"},height:void 0,hitTolerance:void 0,opacity:void 0,padding:6,position:"center",rotation:void 0,textAlign:"start",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,yAdjust:0,z:void 0},rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,xMax:void 0,xMin:void 0,xScaleID:void 0,yMax:void 0,yMin:void 0,yScaleID:void 0,z:0};b1.defaultRoutes={borderColor:"color",backgroundColor:"color"};b1.descriptors={label:{_fallback:!0}};class DF extends Oo{inRange(e,t,r,i){return OU({x:e,y:t},{rect:this.getProps(["x","y","x2","y2"],i),center:this.getCenterPoint(i)},r,{rotation:this.rotation,borderWidth:0,hitTolerance:this.options.hitTolerance})}getCenterPoint(e){return B0(this,e)}draw(e){const t=this.options;!t.display||!t.content||(Kie(e,this),e.save(),TF(e,this.getCenterPoint(),this.rotation),YU(e,this,t,this._fitRatio),e.restore())}resolveElementProperties(e,t){const r=Uie(e,t);if(!r)return{};const{controllerMeta:i,point:o,radius:a}=qie(e,t,r);let l=FF(e.ctx,t);const d=Vie(l,a);HU(t,d)&&(l={width:l.width*d,height:l.height*d});const{position:c,xAdjust:u,yAdjust:f}=t,p=UU(o,l,{borderWidth:0,position:c,xAdjust:u,yAdjust:f});return{initProperties:y1(e,p,t),...p,...i,rotation:t.rotation,_fitRatio:d}}}DF.id="doughnutLabelAnnotation";DF.defaults={autoFit:!0,autoHide:!0,backgroundColor:"transparent",backgroundShadowColor:"transparent",borderColor:"transparent",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderShadowColor:"transparent",borderWidth:0,color:"black",content:null,display:!0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:void 0},height:void 0,hitTolerance:0,init:void 0,opacity:void 0,position:"center",rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,spacing:1,textAlign:"center",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,yAdjust:0};DF.defaultRoutes={};function Uie(n,e){return n.getSortedVisibleDatasetMetas().reduce(function(t,r){const i=r.controller;return i instanceof eS&&Hie(n,e,r.data)&&(!t||i.innerRadius=90?r:t},void 0)}function Hie(n,e,t){if(!e.autoHide)return!0;for(let r=0;rf,x=v?i+m:a-m,w=Gie(x,u,f,y);return{controllerMeta:{_centerX:u,_centerY:f,_radius:y,_counterclockwise:v,...w},point:g,radius:Math.min(l,Math.min(p.right-p.left,p.bottom-p.top)/2)}}function Vie({width:n,height:e},t){const r=Math.sqrt(Math.pow(n,2)+Math.pow(e,2));return t*2/r}function Gie(n,e,t,r){const i=Math.pow(t-n,2),o=Math.pow(r,2),a=e*-2,l=Math.pow(e,2)+i-o,d=Math.pow(a,2)-4*l;if(d<=0)return{_startAngle:0,_endAngle:Eo};const c=(-a-Math.sqrt(d))/2,u=(-a+Math.sqrt(d))/2;return{_startAngle:hB({x:e,y:t},{x:c,y:n}).angle,_endAngle:hB({x:e,y:t},{x:u,y:n}).angle}}function Kie(n,e){const{_centerX:t,_centerY:r,_radius:i,_startAngle:o,_endAngle:a,_counterclockwise:l,options:d}=e;n.save();const c=Cf(n,d);n.fillStyle=d.backgroundColor,n.beginPath(),n.arc(t,r,i,o,a,l),n.closePath(),n.fill(),c&&n.stroke(),n.restore()}class Y_ extends Oo{inRange(e,t,r,i){return OU({x:e,y:t},{rect:this.getProps(["x","y","x2","y2"],i),center:this.getCenterPoint(i)},r,{rotation:this.rotation,borderWidth:this.options.borderWidth,hitTolerance:this.options.hitTolerance})}getCenterPoint(e){return B0(this,e)}draw(e){const t=this.options,r=!ol(this._visible)||this._visible;!t.display||!t.content||!r||(e.save(),TF(e,this.getCenterPoint(),this.rotation),mie(e,this),XU(e,this,t),YU(e,Xie(this),t),e.restore())}resolveElementProperties(e,t){let r;if(VU(t))r=ZU(e,t);else{const{centerX:l,centerY:d}=K6(e,t);r={x:l,y:d}}const i=sa(t.padding),o=FF(e.ctx,t),a=UU(r,o,t,i);return{initProperties:y1(e,a,t),pointX:r.x,pointY:r.y,...a,rotation:t.rotation}}}Y_.id="labelAnnotation";Y_.defaults={adjustScaleRange:!0,backgroundColor:"transparent",backgroundShadowColor:"transparent",borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderRadius:0,borderShadowColor:"transparent",borderWidth:0,callout:{borderCapStyle:"butt",borderColor:void 0,borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:1,display:!1,margin:5,position:"auto",side:5,start:"50%"},color:"black",content:null,display:!0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:void 0},height:void 0,hitTolerance:0,init:void 0,opacity:void 0,padding:6,position:"center",rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,textAlign:"center",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,xMax:void 0,xMin:void 0,xScaleID:void 0,xValue:void 0,yAdjust:0,yMax:void 0,yMin:void 0,yScaleID:void 0,yValue:void 0,z:0};Y_.defaultRoutes={borderColor:"color"};function Xie({x:n,y:e,width:t,height:r,options:i}){const o=i.borderWidth/2,a=sa(i.padding);return{x:n+a.left+o,y:e+a.top+o,width:t-a.left-a.right-i.borderWidth,height:r-a.top-a.bottom-i.borderWidth}}const Y6=(n,e,t)=>({x:n.x+t*(e.x-n.x),y:n.y+t*(e.y-n.y)}),vB=(n,e,t)=>Y6(e,t,Math.abs((n-e.y)/(t.y-e.y))).x,DL=(n,e,t)=>Y6(e,t,Math.abs((n-e.x)/(t.x-e.x))).y,rS=n=>n*n,Yie=(n,e,{x:t,y:r,x2:i,y2:o},a)=>a==="y"?{start:Math.min(r,o),end:Math.max(r,o),value:e}:{start:Math.min(t,i),end:Math.max(t,i),value:n},EL=(n,e,t,r)=>(1-r)*(1-r)*n+2*(1-r)*r*e+r*r*t,wB=(n,e,t,r)=>({x:EL(n.x,e.x,t.x,r),y:EL(n.y,e.y,t.y,r)}),PL=(n,e,t,r)=>2*(1-r)*(e-n)+2*r*(t-e),RL=(n,e,t,r)=>-Math.atan2(PL(n.x,e.x,t.x,r),PL(n.y,e.y,t.y,r))+.5*Or;class Q_ extends Oo{inRange(e,t,r,i){const o=(this.options.borderWidth+this.options.hitTolerance)/2;if(r!=="x"&&r!=="y"){const a={mouseX:e,mouseY:t},{path:l,ctx:d}=this;if(l){Cf(d,this.options),d.lineWidth+=this.options.hitTolerance;const{chart:u}=this.$context,f=e*u.currentDevicePixelRatio,p=t*u.currentDevicePixelRatio,g=d.isPointInStroke(l,f,p)||SB(this,a,i);return d.restore(),g}const c=rS(o);return Jie(this,a,c,i)||SB(this,a,i)}return Qie(this,{mouseX:e,mouseY:t},r,{hitSize:o,useFinalPosition:i})}getCenterPoint(e){return B0(this,e)}draw(e){const{x:t,y:r,x2:i,y2:o,cp:a,options:l}=this;if(e.save(),!Cf(e,l))return e.restore();x1(e,l);const d=Math.sqrt(Math.pow(i-t,2)+Math.pow(o-r,2));if(l.curve&&a)return ase(e,this,a,d),e.restore();const{startOpts:c,endOpts:u,startAdjust:f,endAdjust:p}=rH(this),g=Math.atan2(o-r,i-t);e.translate(t,r),e.rotate(g),e.beginPath(),e.moveTo(0+f,0),e.lineTo(d-p,0),e.shadowColor=l.borderShadowColor,e.stroke(),jB(e,0,f,c),jB(e,d,-p,u),e.restore()}get label(){return this.elements&&this.elements[0]}resolveElementProperties(e,t){const r=kie(e,t),{x:i,y:o,x2:a,y2:l}=r,d=$ie(r,e.chartArea),c=d?Zie({x:i,y:o},{x:a,y:l},e.chartArea):{x:i,y:o,x2:a,y2:l,width:Math.abs(a-i),height:Math.abs(l-o)};if(c.centerX=(a+i)/2,c.centerY=(l+o)/2,c.initProperties=y1(e,c,t),t.curve){const f={x:c.x,y:c.y},p={x:c.x2,y:c.y2};c.cp=ose(c,t,r1(f,p))}const u=ese(e,c,t.label);return u._visible=d,c.elements=[{type:"label",optionScope:"label",properties:u,initProperties:c.initProperties}],c}}Q_.id="lineAnnotation";const BL={backgroundColor:void 0,backgroundShadowColor:void 0,borderColor:void 0,borderDash:void 0,borderDashOffset:void 0,borderShadowColor:void 0,borderWidth:void 0,display:void 0,fill:void 0,length:void 0,shadowBlur:void 0,shadowOffsetX:void 0,shadowOffsetY:void 0,width:void 0};Q_.defaults={adjustScaleRange:!0,arrowHeads:{display:!1,end:Object.assign({},BL),fill:!1,length:12,start:Object.assign({},BL),width:6},borderDash:[],borderDashOffset:0,borderShadowColor:"transparent",borderWidth:2,curve:!1,controlPoint:{y:"-50%"},display:!0,endValue:void 0,init:void 0,hitTolerance:0,label:{backgroundColor:"rgba(0,0,0,0.8)",backgroundShadowColor:"transparent",borderCapStyle:"butt",borderColor:"black",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderRadius:6,borderShadowColor:"transparent",borderWidth:0,callout:Object.assign({},Y_.defaults.callout),color:"#fff",content:null,display:!1,drawTime:void 0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:"bold"},height:void 0,hitTolerance:void 0,opacity:void 0,padding:6,position:"center",rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,textAlign:"center",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,yAdjust:0,z:void 0},scaleID:void 0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,value:void 0,xMax:void 0,xMin:void 0,xScaleID:void 0,yMax:void 0,yMin:void 0,yScaleID:void 0,z:0};Q_.descriptors={arrowHeads:{start:{_fallback:!0},end:{_fallback:!0},_fallback:!0}};Q_.defaultRoutes={borderColor:"color"};function Qie(n,{mouseX:e,mouseY:t},r,{hitSize:i,useFinalPosition:o}){const a=Yie(e,t,n.getProps(["x","y","x2","y2"],o),r);return MU(a,i)||SB(n,{mouseX:e,mouseY:t},o,r)}function $ie({x:n,y:e,x2:t,y2:r},{top:i,right:o,bottom:a,left:l}){return!(no&&t>o||ea&&r>a)}function IL({x:n,y:e},t,{top:r,right:i,bottom:o,left:a}){return ni&&(e=DL(i,{x:n,y:e},t),n=i),eo&&(n=vB(o,{x:n,y:e},t),e=o),{x:n,y:e}}function Zie(n,e,t){const{x:r,y:i}=IL(n,e,t),{x:o,y:a}=IL(e,n,t);return{x:r,y:i,x2:o,y2:a,width:Math.abs(o-r),height:Math.abs(a-i)}}function Jie(n,{mouseX:e,mouseY:t},r=wm,i){const{x:o,y:a,x2:l,y2:d}=n.getProps(["x","y","x2","y2"],i),c=l-o,u=d-a,f=rS(c)+rS(u),p=f===0?-1:((e-o)*c+(t-a)*u)/f;let g,m;return p<0?(g=o,m=a):p>1?(g=l,m=d):(g=o+p*c,m=a+p*u),rS(e-g)+rS(t-m)<=r}function SB(n,{mouseX:e,mouseY:t},r,i){const o=n.label;return o.options.display&&o.inRange(e,t,i,r)}function ese(n,e,t){const r=t.borderWidth,i=sa(t.padding),o=FF(n.ctx,t),a=o.width+i.width+r,l=o.height+i.height+r;return nse(e,t,{width:a,height:l,padding:i},n.chartArea)}function tse(n){const{x:e,y:t,x2:r,y2:i}=n,o=Math.atan2(i-t,r-e);return o>Or/2?o-Or:o0&&(i.w/2+o.left-r.x)/a,c=l>0&&(i.h/2+o.top-r.y)/l;return CF(Math.max(d,c),0,.25)}function sse(n,e){const{x:t,x2:r,y:i,y2:o}=n,a=Math.min(i,o)-e.top,l=Math.min(t,r)-e.left,d=e.bottom-Math.max(i,o),c=e.right-Math.max(t,r);return{x:Math.min(l,c),y:Math.min(a,d),dx:l<=c?1:-1,dy:a<=d?1:-1}}function zL(n,e){const{size:t,min:r,max:i,padding:o}=e,a=t/2;return t>i-r?(i+r)/2:(r>=n-o-a&&(n=r+o+a),i<=n+o+a&&(n=i-o-a),n)}function rH(n){const e=n.options,t=e.arrowHeads&&e.arrowHeads.start,r=e.arrowHeads&&e.arrowHeads.end;return{startOpts:t,endOpts:r,startAdjust:OL(n,t),endAdjust:OL(n,r)}}function OL(n,e){if(!e||!e.display)return 0;const{length:t,width:r}=e,i=n.options.borderWidth/2,o={x:t,y:r+i};return Math.abs(vB(0,o,{x:0,y:i}))}function jB(n,e,t,r){if(!r||!r.display)return;const{length:i,width:o,fill:a,backgroundColor:l,borderColor:d}=r,c=Math.abs(e-i)+t;n.beginPath(),x1(n,r),Cf(n,r),n.moveTo(c,-o),n.lineTo(e+t,0),n.lineTo(c,o),a===!0?(n.fillStyle=l||d,n.closePath(),n.fill(),n.shadowColor="transparent"):n.shadowColor=r.borderShadowColor,n.stroke()}function ose(n,e,t){const{x:r,y:i,x2:o,y2:a,centerX:l,centerY:d}=n,c=Math.atan2(a-i,o-r),u=G6(e.controlPoint,0),f={x:l+Mg(t,u.x,!1),y:d+Mg(t,u.y,!1)};return R0(f,{x:l,y:d},c)}function LL(n,{x:e,y:t},{angle:r,adjust:i},o){!o||!o.display||(n.save(),n.translate(e,t),n.rotate(r),jB(n,0,-i,o),n.restore())}function ase(n,e,t,r){const{x:i,y:o,x2:a,y2:l,options:d}=e,{startOpts:c,endOpts:u,startAdjust:f,endAdjust:p}=rH(e),g={x:i,y:o},m={x:a,y:l},y=RL(g,t,m,0),v=RL(g,t,m,1)-Or,x=wB(g,t,m,f/r),w=wB(g,t,m,1-p/r),S=new Path2D;n.beginPath(),S.moveTo(x.x,x.y),S.quadraticCurveTo(t.x,t.y,w.x,w.y),n.shadowColor=d.borderShadowColor,n.stroke(S),e.path=S,e.ctx=n,LL(n,x,{angle:y,adjust:f},c),LL(n,w,{angle:v,adjust:p},u)}class $_ extends Oo{inRange(e,t,r,i){const o=this.options.rotation,a=(this.options.borderWidth+this.options.hitTolerance)/2;if(r!=="x"&&r!=="y")return lse({x:e,y:t},this.getProps(["width","height","centerX","centerY"],i),o,a);const{x:l,y:d,x2:c,y2:u}=this.getProps(["x","y","x2","y2"],i),f=r==="y"?{start:d,end:u}:{start:l,end:c},p=R0({x:e,y:t},this.getCenterPoint(i),fo(-o));return p[r]>=f.start-a-wm&&p[r]<=f.end+a+wm}getCenterPoint(e){return B0(this,e)}draw(e){const{width:t,height:r,centerX:i,centerY:o,options:a}=this;e.save(),TF(e,this.getCenterPoint(),a.rotation),x1(e,this.options),e.beginPath(),e.fillStyle=a.backgroundColor;const l=Cf(e,a);e.ellipse(i,o,r/2,t/2,Or/2,0,2*Or),e.fill(),l&&(e.shadowColor=a.borderShadowColor,e.stroke()),e.restore()}get label(){return this.elements&&this.elements[0]}resolveElementProperties(e,t){return eH(e,t)}}$_.id="ellipseAnnotation";$_.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderDash:[],borderDashOffset:0,borderShadowColor:"transparent",borderWidth:1,display:!0,hitTolerance:0,init:void 0,label:Object.assign({},b1.defaults.label),rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,xMax:void 0,xMin:void 0,xScaleID:void 0,yMax:void 0,yMin:void 0,yScaleID:void 0,z:0};$_.defaultRoutes={borderColor:"color",backgroundColor:"color"};$_.descriptors={label:{_fallback:!0}};function lse(n,e,t,r){const{width:i,height:o,centerX:a,centerY:l}=e,d=i/2,c=o/2;if(d<=0||c<=0)return!1;const u=fo(t||0),f=Math.cos(u),p=Math.sin(u),g=Math.pow(f*(n.x-a)+p*(n.y-l),2),m=Math.pow(p*(n.x-a)-f*(n.y-l),2);return g/Math.pow(d+r,2)+m/Math.pow(c+r,2)<=1.0001}class EF extends Oo{inRange(e,t,r,i){const{x:o,y:a,x2:l,y2:d,width:c}=this.getProps(["x","y","x2","y2","width"],i),u=(this.options.borderWidth+this.options.hitTolerance)/2;return r!=="x"&&r!=="y"?nie({x:e,y:t},this.getCenterPoint(i),c/2,u):MU(r==="y"?{start:a,end:d,value:t}:{start:o,end:l,value:e},u)}getCenterPoint(e){return B0(this,e)}draw(e){const t=this.options,r=t.borderWidth;if(t.radius<.1)return;e.save(),e.fillStyle=t.backgroundColor,x1(e,t);const i=Cf(e,t);cie(e,this,this.centerX,this.centerY),i&&!AF(t.pointStyle)&&(e.shadowColor=t.borderShadowColor,e.stroke()),e.restore(),t.borderWidth=r}resolveElementProperties(e,t){const r=JU(e,t);return r.initProperties=y1(e,r,t),r}}EF.id="pointAnnotation";EF.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderDash:[],borderDashOffset:0,borderShadowColor:"transparent",borderWidth:1,display:!0,hitTolerance:0,init:void 0,pointStyle:"circle",radius:10,rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,xAdjust:0,xMax:void 0,xMin:void 0,xScaleID:void 0,xValue:void 0,yAdjust:0,yMax:void 0,yMin:void 0,yScaleID:void 0,yValue:void 0,z:0};EF.defaultRoutes={borderColor:"color",backgroundColor:"color"};class PF extends Oo{inRange(e,t,r,i){if(r!=="x"&&r!=="y")return this.options.radius>=.1&&this.elements.length>1&&cse(this.elements,e,t,i);const o=R0({x:e,y:t},this.getCenterPoint(i),fo(-this.options.rotation)),a=this.elements.map(c=>r==="y"?c.bY:c.bX),l=Math.min(...a),d=Math.max(...a);return o[r]>=l&&o[r]<=d}getCenterPoint(e){return B0(this,e)}draw(e){const{elements:t,options:r}=this;e.save(),e.beginPath(),e.fillStyle=r.backgroundColor,x1(e,r);const i=Cf(e,r);let o=!0;for(const a of t)o?(e.moveTo(a.x,a.y),o=!1):e.lineTo(a.x,a.y);e.closePath(),e.fill(),i&&(e.shadowColor=r.borderShadowColor,e.stroke()),e.restore()}resolveElementProperties(e,t){const r=JU(e,t),{sides:i,rotation:o}=t,a=[],l=2*Or/i;let d=o*F6;for(let c=0;ct!=o.bY>t&&e<(o.bX-l.bX)*(t-l.bY)/(o.bY-l.bY)+l.bX&&(i=!i),o=l}return i}const Fg={box:b1,doughnutLabel:DF,ellipse:$_,label:Y_,line:Q_,point:EF,polygon:PF};Object.keys(Fg).forEach(n=>{hs.describe(`elements.${Fg[n].id}`,{_fallback:"plugins.annotation.common"})});const use={update:Object.assign},hse=X6.concat($A),NL=(n,e)=>Yn(e)?_B(n,e):n,kB=n=>n==="color"||n==="font";function Q6(n="line"){return Fg[n]?n:(console.warn(`Unknown annotation type: '${n}', defaulting to 'line'`),"line")}function fse(n,e,t,r){const i=gse(n,t.animations,r),o=e.annotations,a=xse(e.elements,o);for(let l=0;lNL(a,i)):t[r]=NL(o,i)}return t}function yse(n,e,t,r){return e.$context||(e.$context=Object.assign(Object.create(n.getContext()),{element:e,get elements(){return t.filter(i=>i&&i.options)},id:r.id,type:"annotation"}))}function xse(n,e){const t=e.length,r=n.length;if(rt&&n.splice(t,r-t);return n}var bse="3.1.0";const Qf=new Map,WL=n=>n.type!=="doughnutLabel",vse=X6.concat($A);var wse={id:"annotation",version:bse,beforeRegister(){rie("chart.js","4.0",pf.version)},afterRegister(){pf.register(Fg)},afterUnregister(){pf.unregister(Fg)},beforeInit(n){Qf.set(n,{annotations:[],elements:[],visibleElements:[],listeners:{},listened:!1,moveListened:!1,hooks:{},hooked:!1,hovered:[]})},beforeUpdate(n,e,t){const r=Qf.get(n),i=r.annotations=[];let o=t.annotations;Yn(o)?Object.keys(o).forEach(a=>{const l=o[a];Yn(l)&&(l.id=a,i.push(l))}):ki(o)&&i.push(...o),zie(i.filter(WL),n.scales)},afterDataLimits(n,e){const t=Qf.get(n);Mie(n,e.scale,t.annotations.filter(WL).filter(r=>r.display&&r.adjustScaleRange))},afterUpdate(n,e,t){const r=Qf.get(n);Eie(n,r,t),fse(n,r,t,e.mode),r.visibleElements=r.elements.filter(i=>!i.skip&&i.options.display),Iie(n,r,t)},beforeDatasetsDraw(n,e,t){Bw(n,"beforeDatasetsDraw",t.clip)},afterDatasetsDraw(n,e,t){Bw(n,"afterDatasetsDraw",t.clip)},beforeDatasetDraw(n,e,t){Bw(n,e.index,t.clip)},beforeDraw(n,e,t){Bw(n,"beforeDraw",t.clip)},afterDraw(n,e,t){Bw(n,"afterDraw",t.clip)},beforeEvent(n,e,t){const r=Qf.get(n);Pie(r,e.event,t)&&(e.changed=!0)},afterDestroy(n){Qf.delete(n)},getAnnotations(n){const e=Qf.get(n);return e?e.elements:[]},_getAnnotationElementsAtEventForMode(n,e,t){return q6(n,e,t)},defaults:{animations:{numbers:{properties:["x","y","x2","y2","width","height","centerX","centerY","pointX","pointY","radius"],type:"number"},colors:{properties:["backgroundColor","borderColor"],type:"color"}},clip:!0,interaction:{mode:void 0,axis:void 0,intersect:void 0},common:{drawTime:"afterDatasetsDraw",init:!1,label:{}}},descriptors:{_indexable:!1,_scriptable:n=>!vse.includes(n)&&n!=="init",annotations:{_allKeys:!1,_fallback:(n,e)=>`elements.${Fg[Q6(e.type)].id}`},interaction:{_fallback:!0},common:{label:{_indexable:kB,_fallback:!0},_indexable:kB}},additionalOptionScopes:[""]};function Bw(n,e,t){const{ctx:r,chartArea:i}=n,o=Qf.get(n);t&&wF(r,i);const a=Sse(o.visibleElements,e).sort((l,d)=>l.element.options.z-d.element.options.z);for(const l of a)jse(r,i,o,l);t&&SF(r)}function Sse(n,e){const t=[];for(const r of n)if(r.options.drawTime===e&&t.push({element:r,main:!0}),r.elements&&r.elements.length)for(const i of r.elements)i.options.display&&i.options.drawTime===e&&t.push({element:i});return t}function jse(n,e,t,r){const i=r.element;r.main?(AL(t,i,"beforeDraw"),i.draw(n,e),AL(t,i,"afterDraw")):i.draw(n,e)}pf.register(Bj,Ij,GS,qx,U6,H6,W6,wse);const oH="bookings-stats-from-date",aH="bookings-stats-to-date",kse=()=>{const n=sessionStorage.getItem(oH),e=sessionStorage.getItem(aH);if(n&&e)return{from:n,to:e};const t=new Date,r=new Date(t);return r.setDate(t.getDate()-30),{from:r.toISOString().split("T")[0],to:t.toISOString().split("T")[0]}};function _se(){const{token:n}=gn(),e=kse(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(e.from),[d,c]=k.useState(e.to);k.useEffect(()=>{sessionStorage.setItem(oH,a),sessionStorage.setItem(aH,d)},[a,d]);const u=t!==a||i!==d,f=()=>{l(t),c(i)},[p,g]=k.useState(!1),[m,y]=k.useState(null),{data:v,isLoading:x}=Oe({queryKey:["resos-stats",a,d],queryFn:async()=>{const P=await fetch(`/api/resos/stats?from_date=${a}&to_date=${d}`,{headers:{Authorization:`Bearer ${n}`}});if(!P.ok)throw new Error("Failed to fetch stats");return P.json()},staleTime:2*60*1e3}),w=()=>{const P=new Date(a),L=new Date(d),W=Math.floor((L.getTime()-P.getTime())/(1e3*60*60*24)),O=new Date(P);O.setDate(O.getDate()-1);const U=new Date(O);return U.setDate(U.getDate()-W),{from:U.toISOString().split("T")[0],to:O.toISOString().split("T")[0]}},{data:S}=Oe({queryKey:["resos-stats-previous",a,d],queryFn:async()=>{const P=w(),L=await fetch(`/api/resos/stats?from_date=${P.from}&to_date=${P.to}`,{headers:{Authorization:`Bearer ${n}`}});if(!L.ok)throw new Error("Failed to fetch previous stats");return L.json()},enabled:p,staleTime:2*60*1e3}),{data:_}=Oe({queryKey:["resos-bookings",m],queryFn:async()=>{const P=await fetch(`/api/resos/bookings/${m}`,{headers:{Authorization:`Bearer ${n}`}});if(!P.ok)throw new Error("Failed to fetch bookings");return P.json()},enabled:!!m}),b=()=>{const P=new Date,L=new Date;L.setDate(L.getDate()-30),r(L.toISOString().split("T")[0]),o(P.toISOString().split("T")[0])},C=()=>{const P=new Date,L=new Date;L.setDate(L.getDate()-90),r(L.toISOString().split("T")[0]),o(P.toISOString().split("T")[0])},T=P=>new Intl.NumberFormat("en-GB",{style:"currency",currency:"GBP",minimumFractionDigits:0,maximumFractionDigits:0}).format(P),F=P=>new Date(P).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),A=()=>{if(!v||!v.daily_breakdown||v.daily_breakdown.length===0)return s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"No data available"});const P=v.daily_breakdown.map(M=>F(M.date)),L=new Date().toISOString().split("T")[0],W=v.daily_breakdown.findIndex(M=>M.date===L),O=W!==-1,U=[{label:"Bookings",data:v.daily_breakdown.map(M=>M.total_bookings),borderColor:"rgb(102, 126, 234)",backgroundColor:"rgba(102, 126, 234, 0.1)",yAxisID:"y"},{label:"Covers",data:v.daily_breakdown.map(M=>M.total_covers),borderColor:"rgb(118, 75, 162)",backgroundColor:"rgba(118, 75, 162, 0.1)",yAxisID:"y"},{label:"Spend (£)",data:v.daily_breakdown.map(M=>M.total_spend),borderColor:"rgb(237, 100, 166)",backgroundColor:"rgba(237, 100, 166, 0.1)",yAxisID:"y1"}];return p&&(S!=null&&S.daily_breakdown)&&U.push({label:"Prev Bookings",data:S.daily_breakdown.map(M=>M.total_bookings),borderColor:"rgba(102, 126, 234, 0.4)",backgroundColor:"transparent",borderDash:[5,5],yAxisID:"y"},{label:"Prev Covers",data:S.daily_breakdown.map(M=>M.total_covers),borderColor:"rgba(118, 75, 162, 0.4)",backgroundColor:"transparent",borderDash:[5,5],yAxisID:"y"},{label:"Prev Spend (£)",data:S.daily_breakdown.map(M=>M.total_spend),borderColor:"rgba(237, 100, 166, 0.4)",backgroundColor:"transparent",borderDash:[5,5],yAxisID:"y1"}),s.jsx(IU,{data:{labels:P,datasets:U},options:{responsive:!0,maintainAspectRatio:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{position:"top"},tooltip:{callbacks:{label:M=>{let I=M.dataset.label||"";I&&(I+=": ");const H=M.parsed.y;return H!==null&&(I.includes("Spend")?I+=T(H):I+=H),I}}},annotation:O?{annotations:{todayLine:{type:"line",xMin:W,xMax:W,borderColor:"rgba(255, 99, 132, 0.8)",borderWidth:2,borderDash:[5,5],label:{display:!0,content:"Today",position:"start",backgroundColor:"rgba(255, 99, 132, 0.8)",color:"white",padding:4,font:{size:11,weight:"bold"}}}}}:{}},scales:{y:{type:"linear",display:!0,position:"left",title:{display:!0,text:"Bookings / Covers"}},y1:{type:"linear",display:!0,position:"right",title:{display:!0,text:"Spend (£)"},grid:{drawOnChartArea:!1}}},onClick:(M,I)=>{if(I.length>0){const H=I[0].index,z=v.daily_breakdown[H].date;y(z)}}}})},D=()=>{if(!m||!_)return null;const P=_.filter(W=>W.is_flagged),L=v==null?void 0:v.daily_breakdown.find(W=>W.date===m);return s.jsx("div",{style:lt.modalOverlay,onClick:()=>y(null),children:s.jsxs("div",{style:lt.modal,onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{style:lt.modalHeader,children:[s.jsxs("h2",{children:["Bookings for ",F(m)]}),s.jsx("button",{onClick:()=>y(null),style:lt.closeBtn,children:"×"})]}),s.jsxs("div",{style:lt.modalContent,children:[L&&s.jsxs("div",{style:lt.daySummary,children:[s.jsxs("div",{style:lt.summaryRow,children:[s.jsxs("span",{children:[s.jsx("strong",{children:L.total_bookings})," Bookings"]}),s.jsxs("span",{children:[s.jsx("strong",{children:L.total_covers})," Covers"]}),s.jsxs("span",{children:[s.jsx("strong",{children:T(L.total_spend)})," Total Spend"]})]}),s.jsxs("div",{style:lt.summaryRow,children:[s.jsxs("span",{children:["Food: ",T(L.food_spend)]}),s.jsxs("span",{children:["Beverage: ",T(L.beverage_spend)]}),s.jsxs("span",{children:[L.ticket_count," SambaPOS Tickets Matched"]})]})]}),P.length>0&&s.jsxs("div",{style:lt.flaggedSection,children:[s.jsx("h3",{children:"Notable Bookings 🦀"}),P.map(W=>s.jsxs("div",{style:lt.flaggedBooking,children:[s.jsx("div",{children:s.jsxs("strong",{children:[W.opening_hour_name," - ",W.booking_time]})}),s.jsxs("div",{children:["Party of ",W.people]}),W.allergies&&s.jsxs("div",{style:lt.allergyBadge,children:["Allergies: ",W.allergies]}),W.notes&&s.jsxs("div",{style:lt.noteText,children:["Notes: ",W.notes]}),W.flag_reasons&&s.jsxs("div",{style:lt.flagReasons,children:["Flags: ",W.flag_reasons.split(",").join(", ")]})]},W.id))]}),s.jsxs("h3",{children:["All Bookings (",_.length,")"]}),s.jsxs("table",{style:lt.bookingsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:lt.th,children:"Time"}),s.jsx("th",{style:lt.th,children:"Service"}),s.jsx("th",{style:lt.th,children:"Covers"}),s.jsx("th",{style:lt.th,children:"Status"}),s.jsx("th",{style:lt.th,children:"Hotel Guest"}),s.jsx("th",{style:lt.th,children:"Notes"})]})}),s.jsx("tbody",{children:_.map(W=>s.jsxs("tr",{style:W.is_flagged?lt.flaggedRow:{},children:[s.jsx("td",{style:lt.td,children:W.booking_time}),s.jsx("td",{style:lt.td,children:W.opening_hour_name}),s.jsx("td",{style:lt.td,children:W.people}),s.jsx("td",{style:lt.td,children:W.status}),s.jsx("td",{style:lt.td,children:W.is_hotel_guest?"Yes":"No"}),s.jsx("td",{style:lt.td,children:W.notes||"-"})]},W.id))})]})]})]})})};return x?s.jsxs("div",{style:lt.container,children:[s.jsx("h1",{children:"Bookings Stats Report"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"Loading..."})]}):v?s.jsxs("div",{style:lt.container,children:[s.jsx("h1",{children:"Bookings Stats Report"}),s.jsx("div",{style:lt.constructionBanner,children:"This page is still under construction and not completed yet."}),s.jsxs("div",{style:lt.toolbar,children:[s.jsxs("div",{style:lt.toolbarRow,children:[s.jsxs("div",{children:[s.jsx("label",{children:"From: "}),s.jsx("input",{type:"date",value:t,onChange:P=>r(P.target.value),style:lt.dateInput})]}),s.jsxs("div",{children:[s.jsx("label",{children:"To: "}),s.jsx("input",{type:"date",value:i,onChange:P=>o(P.target.value),style:lt.dateInput})]}),s.jsx("button",{onClick:b,style:lt.button,children:"Last 30 Days"}),s.jsx("button",{onClick:C,style:lt.button,children:"Last 90 Days"}),s.jsxs("button",{onClick:f,style:{...lt.generateButton,...u?lt.generateButtonActive:{}},children:["Generate Report",u?" *":""]})]}),s.jsxs("div",{style:lt.toolbarRow,children:[s.jsxs("label",{style:lt.checkbox,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:P=>g(P.target.checked)}),"Show Previous Period Comparison"]}),u&&s.jsx("span",{style:{color:"#d9534f",fontSize:"0.85rem",marginLeft:"1rem"},children:"Date range changed - click Generate Report to update"})]})]}),s.jsxs("div",{style:lt.summaryGrid,children:[s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Total Bookings"}),s.jsx("div",{style:lt.summaryValue,children:v.summary.total_bookings})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Total Covers"}),s.jsx("div",{style:lt.summaryValue,children:v.summary.total_covers})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Avg Lead Time"}),s.jsxs("div",{style:lt.summaryValue,children:[v.summary.avg_lead_time_days," days"]})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Resident %"}),s.jsxs("div",{style:lt.summaryValue,children:[v.summary.resident_pct_covers,"%"]}),s.jsx("div",{style:lt.summarySub,children:"by covers"})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Resident Spend"}),s.jsxs("div",{style:lt.summaryValue,children:[v.summary.resident_pct_spend,"%"]}),s.jsx("div",{style:lt.summarySub,children:"by value"})]})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Spend Analysis"}),s.jsxs("div",{style:lt.spendGrid,children:[s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Total Spend"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.total_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Food"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.food_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Beverage"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.beverage_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Resident Spend"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.resident_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Non-Resident Spend"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.non_resident_spend)})]})]}),s.jsxs("div",{style:lt.matchingInfo,children:[s.jsxs("span",{children:["✅ ",v.spend.matched_tickets," tickets matched to bookings"]}),v.spend.unmatched_tickets>0&&s.jsxs("span",{style:{marginLeft:"1rem",color:"#e94560"},children:["⚠️ ",v.spend.unmatched_tickets," tickets unmatched"]})]})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Trends"}),s.jsx("div",{style:lt.chartContainer,children:A()}),s.jsx("div",{style:lt.chartHint,children:"💡 Click any point on the graph to see detailed breakdown for that day"})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Average Spend by Service Period"}),v.service_period_breakdown&&v.service_period_breakdown.length>0?s.jsxs("table",{style:lt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:lt.th,children:"Service Period"}),s.jsx("th",{style:lt.th,children:"Total Spend"}),s.jsx("th",{style:lt.th,children:"Food"}),s.jsx("th",{style:lt.th,children:"Beverage"}),s.jsx("th",{style:lt.th,children:"Covers"}),s.jsx("th",{style:lt.th,children:"Tickets"}),s.jsx("th",{style:lt.th,children:"Avg per Cover"})]})}),s.jsx("tbody",{children:v.service_period_breakdown.map(P=>{const L=P.resos_covers>0&&P.samba_covers>0&&P.resos_covers!==P.samba_covers;return s.jsxs("tr",{children:[s.jsx("td",{style:lt.td,children:s.jsx("strong",{children:P.service_period})}),s.jsx("td",{style:lt.td,children:T(P.total_spend)}),s.jsx("td",{style:lt.td,children:T(P.food_spend)}),s.jsx("td",{style:lt.td,children:T(P.beverage_spend)}),s.jsxs("td",{style:lt.td,children:[s.jsxs("span",{style:L?{fontStyle:"italic"}:{},children:[P.covers,L?" *":""]}),L&&s.jsxs("div",{style:{color:"#d9534f",fontSize:"0.75rem",fontStyle:"italic"},children:["Resos: ",P.resos_covers," / SambaPOS: ",P.samba_covers]})]}),s.jsx("td",{style:lt.td,children:P.ticket_count}),s.jsx("td",{style:lt.td,children:s.jsx("strong",{children:T(P.avg_spend_per_cover)})})]},P.service_period)})})]}):s.jsx("div",{style:{padding:"1rem",color:"#666"},children:"No spend data available. Ensure SambaPOS integration is configured with GL codes in Settings."})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Daily Breakdown by Service Period"}),v.daily_service_breakdown&&v.daily_service_breakdown.length>0?(()=>{const P=new Set;v.daily_service_breakdown.forEach(O=>{Object.keys(O.periods).forEach(U=>P.add(U))});const W=["Breakfast","Lunch","Afternoon","Dinner"].filter(O=>P.has(O));return s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:lt.table,children:[s.jsxs("thead",{children:[s.jsxs("tr",{children:[s.jsx("th",{style:lt.th,children:"Date"}),W.map(O=>s.jsx("th",{style:{...lt.th,textAlign:"center"},children:O},O))]}),s.jsxs("tr",{style:{background:"#f8f9fa"},children:[s.jsx("th",{style:{...lt.th,fontSize:"0.75rem",padding:"0.5rem"}}),W.map(O=>s.jsx("th",{style:{...lt.th,fontSize:"0.75rem",padding:"0.5rem",textAlign:"center"},children:"Covers | Food | Bev"},O))]})]}),s.jsx("tbody",{children:v.daily_service_breakdown.map(O=>s.jsxs("tr",{children:[s.jsx("td",{style:{...lt.td,fontWeight:"bold"},children:F(O.date)}),W.map(U=>{const M=O.periods[U];if(!M)return s.jsx("td",{style:{...lt.td,textAlign:"center",color:"#ccc"},children:"-"},U);const I=M.resos_covers>0&&M.samba_covers>0&&M.resos_covers!==M.samba_covers;return s.jsx("td",{style:{...lt.td,textAlign:"center",fontSize:"0.85rem"},children:M.covers>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:I?{fontStyle:"italic"}:{},children:[M.covers," covers",I?" *":""]}),I&&s.jsxs("div",{style:{color:"#d9534f",fontSize:"0.7rem",fontStyle:"italic"},children:["Resos: ",M.resos_covers," / SambaPOS: ",M.samba_covers]}),s.jsxs("div",{style:{color:"#666",fontSize:"0.75rem"},children:[T(M.food)," | ",T(M.beverage)]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{color:"#999",fontSize:"0.75rem"},children:[M.ticket_count," ticket",M.ticket_count!==1?"s":""," (unmatched)"]}),s.jsxs("div",{style:{color:"#666",fontSize:"0.75rem"},children:[T(M.food)," | ",T(M.beverage)]})]})},U)})]},O.date))})]})})})():s.jsx("div",{style:{padding:"1rem",color:"#666"},children:"No daily breakdown data available."})]}),D()]}):s.jsxs("div",{style:lt.container,children:[s.jsx("h1",{children:"Bookings Stats Report"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"No data available"})]})}const lt={container:{padding:"2rem",background:"#f5f5f5",minHeight:"100vh"},constructionBanner:{background:"#fff3cd",color:"#856404",border:"1px solid #ffc107",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",textAlign:"center",fontWeight:500},toolbar:{background:"white",padding:"1.5rem",borderRadius:"12px",marginBottom:"1rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},toolbarRow:{display:"flex",gap:"1rem",marginBottom:"0.5rem",alignItems:"center"},dateInput:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem"},button:{padding:"0.5rem 1rem",background:"#667eea",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},generateButton:{padding:"0.5rem 1.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem",fontWeight:"bold",transition:"all 0.2s"},generateButtonActive:{background:"#dc3545",animation:"pulse 1.5s ease-in-out infinite"},checkbox:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.95rem",cursor:"pointer"},summaryGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:"1rem",marginBottom:"1.5rem"},summaryCard:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",textAlign:"center"},summaryLabel:{fontSize:"0.85rem",color:"#666",marginBottom:"0.5rem",textTransform:"uppercase",letterSpacing:"0.5px"},summaryValue:{fontSize:"2rem",fontWeight:"bold",color:"#333"},summarySub:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem"},section:{background:"white",padding:"1.5rem",borderRadius:"12px",marginBottom:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},spendGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1rem"},spendCard:{background:"#f8f9fa",padding:"1rem",borderRadius:"8px",textAlign:"center"},spendLabel:{fontSize:"0.85rem",color:"#666",marginBottom:"0.5rem"},spendValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#333"},matchingInfo:{fontSize:"0.9rem",color:"#666",padding:"0.5rem 0"},chartContainer:{height:"400px",position:"relative",marginTop:"1rem"},chartHint:{fontSize:"0.85rem",color:"#666",textAlign:"center",marginTop:"1rem",fontStyle:"italic"},table:{width:"100%",borderCollapse:"collapse",marginTop:"1rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",fontWeight:"600",fontSize:"0.9rem",background:"#f8f9fa"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",width:"90%",maxWidth:"900px",maxHeight:"90vh",overflow:"auto",padding:"24px"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem",paddingBottom:"1rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"2rem",cursor:"pointer",color:"#999"},modalContent:{fontSize:"0.95rem"},daySummary:{background:"#f8f9fa",padding:"1rem",borderRadius:"8px",marginBottom:"1.5rem"},summaryRow:{display:"flex",justifyContent:"space-around",gap:"1rem",marginBottom:"0.5rem",fontSize:"0.9rem"},flaggedSection:{background:"#fffbcc",borderLeft:"4px solid #ffcc00",padding:"1rem",marginBottom:"1.5rem",borderRadius:"4px"},flaggedBooking:{marginBottom:"1rem",paddingBottom:"0.5rem",borderBottom:"1px solid #ddd"},allergyBadge:{background:"#f8d7da",color:"#721c24",padding:"0.2rem 0.5rem",borderRadius:"4px",display:"inline-block",marginTop:"0.3rem",fontSize:"0.85rem"},noteText:{fontStyle:"italic",color:"#666",marginTop:"0.3rem",fontSize:"0.85rem"},flagReasons:{fontSize:"0.75rem",color:"#666",marginTop:"0.3rem"},bookingsTable:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem"},flaggedRow:{background:"#fffbcc"}},ZA={wastage:"#e94560",transfer:"#3498db",staff_food:"#27ae60",manual_adjustment:"#f39c12"},$6={wastage:"Wastage",transfer:"Transfer",staff_food:"Staff Food",manual_adjustment:"Manual Adjustment"},Cse=[{value:"spoiled",label:"Spoiled"},{value:"damaged",label:"Damaged"},{value:"expired",label:"Expired"},{value:"overproduction",label:"Overproduction"},{value:"quality_issue",label:"Quality Issue"},{value:"other",label:"Other"}],Ase=[{value:"breakfast",label:"Breakfast"},{value:"lunch",label:"Lunch"},{value:"dinner",label:"Dinner"},{value:"snack",label:"Snack"}];function Tse(){const{token:n}=gn(),e=pi(),[t]=K_(),[r,i]=k.useState(""),[o,a]=k.useState(t.get("date_from")||""),[l,d]=k.useState(t.get("date_to")||""),[c,u]=k.useState(null),[f,p]=k.useState(!1),[g,m]=k.useState("wastage"),y=new URLSearchParams;r&&y.append("entry_type",r),o&&y.append("date_from",o),l&&y.append("date_to",l);const v=y.toString(),{data:x,isLoading:w}=Oe({queryKey:["logbook",r,o,l],queryFn:async()=>{const A=v?`/api/logbook?${v}`:"/api/logbook",D=await fetch(A,{headers:{Authorization:`Bearer ${n}`}});if(!D.ok)throw new Error("Failed to fetch logbook entries");return D.json()},enabled:!!n}),S=new URLSearchParams;o&&S.append("date_from",o),l&&S.append("date_to",l);const _=S.toString(),{data:b}=Oe({queryKey:["logbook-summary",o,l],queryFn:async()=>{const A=_?`/api/logbook/summary?${_}`:"/api/logbook/summary",D=await fetch(A,{headers:{Authorization:`Bearer ${n}`}});if(!D.ok)throw new Error("Failed to fetch summary");return D.json()},enabled:!!n}),C=Ue({mutationFn:async A=>{const D=await fetch(`/api/logbook/${A}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!D.ok)throw new Error("Failed to delete entry");return D.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["logbook"]}),e.invalidateQueries({queryKey:["logbook-summary"]}),u(null)}}),T=A=>$6[A]||A,F=A=>{var D,P,L,W,O;switch(A.entry_type){case"wastage":return`Reason: ${(((D=A.type_data)==null?void 0:D.reason)||"Unknown").replace(/_/g," ")}`;case"transfer":return`Status: ${(((P=A.type_data)==null?void 0:P.status)||"pending").replace(/_/g," ")}`;case"staff_food":return`Meal: ${((L=A.type_data)==null?void 0:L.meal_type)||"Unknown"}${(W=A.type_data)!=null&&W.staff_count?` (${A.type_data.staff_count} staff)`:""}`;case"manual_adjustment":return(O=A.type_data)!=null&&O.adjustment_reason?`Reason: ${A.type_data.adjustment_reason}`:"";default:return""}};return w?s.jsx("div",{style:Me.loading,children:"Loading logbook..."}):s.jsxs("div",{children:[s.jsxs("div",{style:Me.header,children:[s.jsx("h2",{style:Me.title,children:"Kitchen Logbook"}),s.jsx("button",{onClick:()=>p(!0),style:Me.createBtn,children:"+ New Entry"})]}),b&&s.jsxs("div",{style:Me.summaryGrid,children:[s.jsxs("div",{style:Me.summaryCard,children:[s.jsx("div",{style:Me.summaryValue,children:b.total_entries}),s.jsx("div",{style:Me.summaryLabel,children:"Total Entries"})]}),s.jsxs("div",{style:Me.summaryCard,children:[s.jsxs("div",{style:Me.summaryValue,children:["£",b.total_cost.toFixed(2)]}),s.jsx("div",{style:Me.summaryLabel,children:"Total Cost"})]}),Object.entries(b.by_type).map(([A,D])=>s.jsxs("div",{style:{...Me.summaryCard,borderLeft:`4px solid ${ZA[A]||"#999"}`},children:[s.jsxs("div",{style:Me.summaryValue,children:["£",D.total_cost.toFixed(2)]}),s.jsxs("div",{style:Me.summaryLabel,children:[T(A)," (",D.count,")"]})]},A))]}),s.jsxs("div",{style:Me.filters,children:[s.jsxs("select",{value:r,onChange:A=>i(A.target.value),style:Me.filterSelect,children:[s.jsx("option",{value:"",children:"All Types"}),s.jsx("option",{value:"wastage",children:"Wastage"}),s.jsx("option",{value:"transfer",children:"Transfer"}),s.jsx("option",{value:"staff_food",children:"Staff Food"}),s.jsx("option",{value:"manual_adjustment",children:"Manual Adjustment"})]}),s.jsx("input",{type:"date",value:o,onChange:A=>a(A.target.value),style:Me.filterInput,placeholder:"From date"}),s.jsx("input",{type:"date",value:l,onChange:A=>d(A.target.value),style:Me.filterInput,placeholder:"To date"}),(r||o||l)&&s.jsx("button",{onClick:()=>{i(""),a(""),d("")},style:Me.clearBtn,children:"Clear Filters"})]}),!x||x.length===0?s.jsxs("div",{style:Me.empty,children:[s.jsx("p",{children:"No logbook entries found."}),s.jsx("button",{onClick:()=>p(!0),style:Me.link,children:"Create your first entry"})]}):s.jsx("div",{style:Me.list,children:x.map(A=>s.jsxs("div",{onClick:()=>u(A),style:Me.card,children:[s.jsx("div",{style:Me.cardLeft,children:s.jsx("div",{style:{...Me.typeBadge,background:ZA[A.entry_type]||"#999"},children:T(A.entry_type)})}),s.jsxs("div",{style:Me.cardMain,children:[s.jsxs("div",{style:Me.cardDate,children:[new Date(A.entry_date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"}),A.reference_number&&s.jsxs("span",{style:Me.refNumber,children:["Ref: ",A.reference_number]})]}),s.jsx("div",{style:Me.cardInfo,children:F(A)}),s.jsxs("div",{style:Me.cardItems,children:[A.line_items.slice(0,3).map((D,P)=>s.jsxs("span",{style:Me.itemPill,children:[D.product_name," (",D.quantity,")"]},P)),A.line_items.length>3&&s.jsxs("span",{style:Me.moreItems,children:["+",A.line_items.length-3," more"]})]}),A.notes&&s.jsx("div",{style:Me.cardNotes,children:A.notes.length>80?`${A.notes.substring(0,80)}...`:A.notes})]}),s.jsxs("div",{style:Me.cardRight,children:[s.jsxs("div",{style:Me.amount,children:["£",A.total_cost.toFixed(2)]}),s.jsxs("div",{style:Me.cardMeta,children:[A.line_items.length," item",A.line_items.length!==1?"s":""]}),A.attachments.length>0&&s.jsxs("div",{style:Me.attachmentBadge,children:[A.attachments.length," attachment",A.attachments.length!==1?"s":""]})]})]},A.id))}),c&&s.jsx(Fse,{entry:c,onClose:()=>u(null),onDelete:()=>C.mutate(c.id)}),f&&s.jsx(Dse,{entryType:g,setEntryType:m,onClose:()=>p(!1),onSuccess:()=>{p(!1),e.invalidateQueries({queryKey:["logbook"]}),e.invalidateQueries({queryKey:["logbook-summary"]})}})]})}function Fse({entry:n,onClose:e,onDelete:t}){var o,a,l,d,c;const[r,i]=k.useState(!1);return s.jsx("div",{style:Me.modalOverlay,onClick:e,children:s.jsxs("div",{style:Me.modal,onClick:u=>u.stopPropagation(),children:[s.jsxs("div",{style:Me.modalHeader,children:[s.jsxs("h3",{style:Me.modalTitle,children:[s.jsx("span",{style:{...Me.typeBadge,background:ZA[n.entry_type]||"#999",marginRight:"0.75rem"},children:$6[n.entry_type]||n.entry_type}),new Date(n.entry_date).toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long",year:"numeric"})]}),s.jsx("button",{onClick:e,style:Me.closeBtn,children:"×"})]}),s.jsxs("div",{style:Me.modalBody,children:[s.jsxs("div",{style:Me.detailGrid,children:[s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Total Cost"}),s.jsxs("span",{style:Me.detailValue,children:["£",n.total_cost.toFixed(2)]})]}),n.reference_number&&s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Reference"}),s.jsx("span",{style:Me.detailValue,children:n.reference_number})]}),s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Created By"}),s.jsx("span",{style:Me.detailValue,children:n.created_by_name||`User #${n.created_by}`})]}),s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Created At"}),s.jsx("span",{style:Me.detailValue,children:new Date(n.created_at).toLocaleString("en-GB")})]})]}),n.entry_type==="wastage"&&((o=n.type_data)==null?void 0:o.reason)!=null&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Reason:"})," ",String(n.type_data.reason).replace(/_/g," ")]}),n.entry_type==="transfer"&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Status:"})," ",String(((a=n.type_data)==null?void 0:a.status)||"pending").replace(/_/g," ")]}),n.entry_type==="staff_food"&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Meal:"})," ",String(((l=n.type_data)==null?void 0:l.meal_type)||"Unknown"),((d=n.type_data)==null?void 0:d.staff_count)!=null&&s.jsxs(s.Fragment,{children:[" | ",s.jsx("strong",{children:"Staff Count:"})," ",Number(n.type_data.staff_count)]})]}),n.entry_type==="manual_adjustment"&&((c=n.type_data)==null?void 0:c.adjustment_reason)!=null&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Adjustment Reason:"})," ",String(n.type_data.adjustment_reason)]}),n.notes&&s.jsxs("div",{style:Me.notesSection,children:[s.jsx("strong",{children:"Notes:"}),s.jsx("p",{style:Me.notesText,children:n.notes})]}),s.jsxs("div",{style:Me.lineItemsSection,children:[s.jsxs("h4",{style:Me.sectionTitle,children:["Items (",n.line_items.length,")"]}),s.jsxs("table",{style:Me.lineItemsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Me.th,children:"Product"}),s.jsx("th",{style:Me.th,children:"Qty"}),s.jsx("th",{style:Me.th,children:"Unit Price"}),s.jsx("th",{style:Me.th,children:"Total"})]})}),s.jsx("tbody",{children:n.line_items.map(u=>s.jsxs("tr",{children:[s.jsxs("td",{style:Me.td,children:[s.jsx("div",{children:u.product_name}),u.product_code&&s.jsx("div",{style:Me.productCode,children:u.product_code}),u.supplier_name&&s.jsx("div",{style:Me.supplierName,children:u.supplier_name})]}),s.jsxs("td",{style:Me.td,children:[u.quantity," ",u.unit||""]}),s.jsx("td",{style:Me.td,children:u.unit_price!=null?`£${u.unit_price.toFixed(2)}`:"-"}),s.jsxs("td",{style:Me.td,children:["£",u.total_cost.toFixed(2)]})]},u.id))}),s.jsx("tfoot",{children:s.jsxs("tr",{children:[s.jsx("td",{colSpan:3,style:{...Me.td,fontWeight:"bold",textAlign:"right"},children:"Total:"}),s.jsxs("td",{style:{...Me.td,fontWeight:"bold"},children:["£",n.total_cost.toFixed(2)]})]})})]})]}),n.attachments.length>0&&s.jsxs("div",{style:Me.attachmentsSection,children:[s.jsxs("h4",{style:Me.sectionTitle,children:["Attachments (",n.attachments.length,")"]}),s.jsx("div",{style:Me.attachmentsList,children:n.attachments.map(u=>s.jsxs("div",{style:Me.attachmentItem,children:[s.jsx("span",{children:u.file_name}),s.jsxs("span",{style:Me.attachmentSize,children:["(",(u.file_size_bytes/1024).toFixed(1)," KB)"]})]},u.id))})]}),s.jsx("div",{style:Me.deleteSection,children:r?s.jsxs("div",{style:Me.confirmDelete,children:[s.jsx("span",{children:"Are you sure?"}),s.jsx("button",{onClick:t,style:Me.confirmYes,children:"Yes, Delete"}),s.jsx("button",{onClick:()=>i(!1),style:Me.confirmNo,children:"Cancel"})]}):s.jsx("button",{onClick:()=>i(!0),style:Me.deleteBtn,children:"Delete Entry"})})]})]})})}function Dse({entryType:n,setEntryType:e,onClose:t,onSuccess:r}){const{token:i}=gn(),[o,a]=k.useState(new Date().toISOString().split("T")[0]),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState("spoiled"),[g,m]=k.useState("lunch"),[y,v]=k.useState(""),[x,w]=k.useState(""),[S,_]=k.useState([]),[b,C]=k.useState(""),[T,F]=k.useState([]),[A,D]=k.useState(!1),[P,L]=k.useState(null),W=async z=>{if(z.length<2){F([]);return}try{const G=await fetch(`/api/logbook/products/search?query=${encodeURIComponent(z)}`,{headers:{Authorization:`Bearer ${i}`}});if(G.ok){const te=await G.json();F(te)}}catch{}},O=z=>{const G={product_id:z==null?void 0:z.id,product_name:(z==null?void 0:z.name)||"",product_code:(z==null?void 0:z.product_code)||void 0,supplier_name:(z==null?void 0:z.supplier_name)||void 0,quantity:1,unit:(z==null?void 0:z.unit)||void 0,unit_price:(z==null?void 0:z.last_price)||void 0,total_cost:(z==null?void 0:z.last_price)||0};_([...S,G]),C(""),F([])},U=(z,G,te)=>{const re=[...S];if(re[z]={...re[z],[G]:te},G==="quantity"||G==="unit_price"){const me=G==="quantity"?te:re[z].quantity,J=G==="unit_price"?te:re[z].unit_price;re[z].total_cost=(me||0)*(J||0)}_(re)},M=z=>{_(S.filter((G,te)=>te!==z))},I=()=>S.reduce((z,G)=>z+(G.total_cost||0),0),H=async()=>{if(S.length===0){L("Please add at least one item");return}D(!0),L(null);try{let z="/api/logbook/",G={entry_date:o,notes:l||void 0,line_items:S};switch(n){case"wastage":z+="wastage",G.reason=f,G.reference_number=c||void 0;break;case"transfer":z+="transfer",G.destination_kitchen_id=1,G.reference_number=c||void 0;break;case"staff_food":z+="staff-food",G.meal_type=g,G.staff_count=y||void 0;break;case"manual_adjustment":z+="manual-adjustment",G.adjustment_reason=x,G.reference_number=c||void 0;break}const te=await fetch(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(G)});if(!te.ok){const re=await te.json();throw new Error(re.detail||"Failed to create entry")}r()}catch(z){L(z instanceof Error?z.message:"Failed to create entry")}finally{D(!1)}};return s.jsx("div",{style:Me.modalOverlay,onClick:t,children:s.jsxs("div",{style:{...Me.modal,maxWidth:"1000px"},onClick:z=>z.stopPropagation(),children:[s.jsxs("div",{style:Me.modalHeader,children:[s.jsx("h3",{style:Me.modalTitle,children:"New Logbook Entry"}),s.jsx("button",{onClick:t,style:Me.closeBtn,children:"×"})]}),s.jsxs("div",{style:Me.modalBody,children:[P&&s.jsx("div",{style:Me.errorMsg,children:P}),s.jsx("div",{style:Me.typeSelector,children:Object.entries($6).map(([z,G])=>s.jsx("button",{onClick:()=>e(z),style:{...Me.typeBtn,background:n===z?ZA[z]:"#f0f0f0",color:n===z?"white":"#333"},children:G},z))}),s.jsxs("div",{style:Me.topFieldsRow,children:[s.jsxs("div",{style:Me.leftFieldsColumn,children:[s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Date"}),s.jsx("input",{type:"date",value:o,onChange:z=>a(z.target.value),style:Me.input})]}),n==="wastage"&&s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Wastage Reason"}),s.jsx("select",{value:f,onChange:z=>p(z.target.value),style:Me.input,children:Cse.map(z=>s.jsx("option",{value:z.value,children:z.label},z.value))})]}),n==="transfer"&&s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Reference Number"}),s.jsx("input",{type:"text",value:c,onChange:z=>u(z.target.value),style:Me.input,placeholder:"Optional"})]}),n==="staff_food"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Meal Type"}),s.jsx("select",{value:g,onChange:z=>m(z.target.value),style:Me.input,children:Ase.map(z=>s.jsx("option",{value:z.value,children:z.label},z.value))})]}),s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Staff Count"}),s.jsx("input",{type:"number",value:y,onChange:z=>v(z.target.value?parseInt(z.target.value):""),style:Me.input,placeholder:"Optional",min:"1"})]})]}),n==="manual_adjustment"&&s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Adjustment Reason"}),s.jsx("input",{type:"text",value:x,onChange:z=>w(z.target.value),style:Me.input,placeholder:"e.g., Stock count correction"})]})]}),s.jsx("div",{style:Me.rightFieldsColumn,children:s.jsxs("div",{style:{...Me.formGroup,flex:1,display:"flex",flexDirection:"column"},children:[s.jsx("label",{style:Me.label,children:"Notes"}),s.jsx("textarea",{value:l,onChange:z=>d(z.target.value),style:{...Me.input,flex:1,minHeight:"100px",resize:"vertical"},placeholder:"Optional notes..."})]})})]}),s.jsxs("div",{style:Me.lineItemsSection,children:[s.jsxs("h4",{style:Me.sectionTitle,children:["Wastage Items (",S.length,")"]}),s.jsx("div",{style:Me.lineItemsTableContainer,children:s.jsxs("table",{style:Me.lineItemsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Me.th,children:"Product"}),s.jsx("th",{style:{...Me.th,width:"80px"},children:"Qty"}),s.jsx("th",{style:{...Me.th,width:"100px"},children:"Unit Price"}),s.jsx("th",{style:{...Me.th,width:"100px"},children:"Total"}),s.jsx("th",{style:{...Me.th,width:"40px"}})]})}),s.jsx("tbody",{children:S.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{...Me.td,textAlign:"center",color:"#999",padding:"1.5rem"},children:"No items added yet. Search below or add manually."})}):S.map((z,G)=>s.jsxs("tr",{children:[s.jsxs("td",{style:Me.td,children:[s.jsx("input",{type:"text",value:z.product_name,onChange:te=>U(G,"product_name",te.target.value),style:Me.tableInput,placeholder:"Product name"}),z.supplier_name&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#3498db",marginTop:"2px"},children:z.supplier_name})]}),s.jsx("td",{style:Me.td,children:s.jsx("input",{type:"number",value:z.quantity,onChange:te=>U(G,"quantity",parseFloat(te.target.value)||0),style:Me.tableInput,min:"0",step:"0.01"})}),s.jsx("td",{style:Me.td,children:s.jsx("input",{type:"number",value:z.unit_price||"",onChange:te=>U(G,"unit_price",te.target.value?parseFloat(te.target.value):void 0),style:Me.tableInput,min:"0",step:"0.01",placeholder:"£0.00"})}),s.jsx("td",{style:Me.td,children:s.jsx("input",{type:"number",value:z.total_cost,onChange:te=>U(G,"total_cost",parseFloat(te.target.value)||0),style:Me.tableInput,min:"0",step:"0.01"})}),s.jsx("td",{style:Me.td,children:s.jsx("button",{onClick:()=>M(G),style:Me.removeItemBtn,children:"×"})})]},G))}),S.length>0&&s.jsx("tfoot",{children:s.jsxs("tr",{children:[s.jsx("td",{colSpan:3,style:{...Me.td,fontWeight:"bold",textAlign:"right"},children:"Total:"}),s.jsxs("td",{style:{...Me.td,fontWeight:"bold"},children:["£",I().toFixed(2)]}),s.jsx("td",{})]})})]})}),s.jsx("button",{onClick:()=>O(),style:Me.manualAddBtn,children:"+ Add Manual Item"})]}),s.jsxs("div",{style:Me.productSearchSection,children:[s.jsx("h4",{style:Me.sectionTitle,children:"Search Products"}),s.jsx("input",{type:"text",value:b,onChange:z=>{C(z.target.value),W(z.target.value)},style:{...Me.input,marginBottom:"0.5rem"},placeholder:"Search by product name or code..."}),s.jsx("div",{style:Me.productSearchResultsContainer,children:b.length<2?s.jsx("div",{style:Me.searchPlaceholder,children:"Type at least 2 characters to search products..."}):T.length===0?s.jsxs("div",{style:Me.searchPlaceholder,children:['No products found matching "',b,'"']}):s.jsxs("table",{style:Me.searchResultsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Me.searchTh,children:"Supplier"}),s.jsx("th",{style:Me.searchTh,children:"Description"}),s.jsx("th",{style:{...Me.searchTh,width:"80px"},children:"Unit"}),s.jsx("th",{style:{...Me.searchTh,width:"80px"},children:"Price"}),s.jsx("th",{style:{...Me.searchTh,width:"60px"}})]})}),s.jsx("tbody",{children:T.map((z,G)=>s.jsxs("tr",{style:Me.searchResultRow,children:[s.jsx("td",{style:Me.searchTd,children:z.supplier_name||"-"}),s.jsxs("td",{style:Me.searchTd,children:[z.name,z.product_code&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#999",marginLeft:"0.5rem"},children:["(",z.product_code,")"]})]}),s.jsx("td",{style:Me.searchTd,children:z.unit||"-"}),s.jsx("td",{style:Me.searchTd,children:z.last_price!=null?`£${z.last_price.toFixed(2)}`:"-"}),s.jsx("td",{style:Me.searchTd,children:s.jsx("button",{onClick:()=>O(z),style:Me.addFromSearchBtn,children:"Add"})})]},`${G}-${z.name}-${z.product_code||""}`))})]})})]}),s.jsxs("div",{style:Me.submitRow,children:[s.jsx("button",{onClick:t,style:Me.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:H,style:Me.submitBtn,disabled:A||S.length===0,children:A?"Creating...":"Create Entry"})]})]})]})})}const Me={loading:{padding:"2rem",textAlign:"center",color:"#666"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},createBtn:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontWeight:"bold",cursor:"pointer"},summaryGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1.5rem"},summaryCard:{background:"white",padding:"1rem",borderRadius:"8px",textAlign:"center",boxShadow:"0 2px 4px rgba(0,0,0,0.05)"},summaryValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#1a1a2e"},summaryLabel:{fontSize:"0.85rem",color:"#666",marginTop:"0.25rem"},filters:{display:"flex",gap:"1rem",marginBottom:"1.5rem",flexWrap:"wrap"},filterSelect:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",minWidth:"150px"},filterInput:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem"},clearBtn:{padding:"0.5rem 1rem",borderRadius:"8px",border:"none",background:"#666",color:"white",cursor:"pointer",fontWeight:"bold"},empty:{padding:"3rem",textAlign:"center",color:"#666",background:"white",borderRadius:"12px"},link:{display:"inline-block",marginTop:"1rem",padding:"0.75rem 1.5rem",background:"transparent",color:"#e94560",border:"2px solid #e94560",borderRadius:"8px",textDecoration:"none",fontWeight:"bold",cursor:"pointer"},list:{display:"flex",flexDirection:"column",gap:"1rem"},card:{display:"flex",padding:"1rem",background:"white",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",cursor:"pointer",gap:"1rem"},cardLeft:{display:"flex",alignItems:"flex-start"},typeBadge:{padding:"0.35rem 0.75rem",borderRadius:"6px",fontSize:"0.75rem",fontWeight:"bold",color:"white",textTransform:"uppercase",whiteSpace:"nowrap"},cardMain:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},cardDate:{fontSize:"1rem",fontWeight:"bold",color:"#1a1a2e",display:"flex",alignItems:"center",gap:"0.75rem"},refNumber:{fontSize:"0.8rem",color:"#666",fontWeight:"normal"},cardInfo:{fontSize:"0.9rem",color:"#666"},cardItems:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginTop:"0.25rem"},itemPill:{padding:"0.2rem 0.5rem",background:"#f0f0f0",borderRadius:"4px",fontSize:"0.8rem",color:"#666"},moreItems:{fontSize:"0.8rem",color:"#999"},cardNotes:{fontSize:"0.85rem",color:"#888",fontStyle:"italic",marginTop:"0.25rem"},cardRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"0.25rem"},amount:{fontSize:"1.25rem",fontWeight:"bold",color:"#e94560"},cardMeta:{fontSize:"0.8rem",color:"#999"},attachmentBadge:{fontSize:"0.75rem",color:"#3498db"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",maxWidth:"700px",width:"95%",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)",display:"flex",flexDirection:"column"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},modalTitle:{margin:0,color:"#1a1a2e",display:"flex",alignItems:"center"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},modalBody:{padding:"1.5rem",overflowY:"auto",flex:1},detailGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1rem",padding:"1rem",background:"#f8f8f8",borderRadius:"8px"},detailItem:{display:"flex",flexDirection:"column"},detailLabel:{fontSize:"0.75rem",color:"#666",textTransform:"uppercase"},detailValue:{fontSize:"1rem",fontWeight:"bold",color:"#1a1a2e"},typeInfo:{padding:"0.75rem 1rem",background:"#f0f0f0",borderRadius:"8px",marginBottom:"1rem"},notesSection:{marginBottom:"1rem"},notesText:{margin:"0.5rem 0 0 0",padding:"0.75rem",background:"#fafafa",borderRadius:"8px",fontStyle:"italic",color:"#666"},lineItemsSection:{marginTop:"1.5rem"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1.1rem"},lineItemsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",background:"#f8f8f8"},td:{padding:"0.75rem",borderBottom:"1px solid #eee",verticalAlign:"top"},productCode:{fontSize:"0.75rem",color:"#999"},supplierName:{fontSize:"0.75rem",color:"#3498db"},attachmentsSection:{marginTop:"1.5rem"},attachmentsList:{display:"flex",flexDirection:"column",gap:"0.5rem"},attachmentItem:{padding:"0.5rem 0.75rem",background:"#f8f8f8",borderRadius:"4px",display:"flex",justifyContent:"space-between",alignItems:"center"},attachmentSize:{fontSize:"0.8rem",color:"#999"},deleteSection:{marginTop:"2rem",paddingTop:"1rem",borderTop:"1px solid #eee"},deleteBtn:{padding:"0.75rem 1.5rem",background:"#dc3545",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold"},confirmDelete:{display:"flex",alignItems:"center",gap:"1rem"},confirmYes:{padding:"0.5rem 1rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},confirmNo:{padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},errorMsg:{padding:"1rem",background:"#fee",color:"#c00",borderRadius:"8px",marginBottom:"1rem"},typeSelector:{display:"flex",gap:"0.5rem",marginBottom:"1.5rem",flexWrap:"wrap"},typeBtn:{padding:"0.5rem 1rem",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold",transition:"all 0.2s"},formGroup:{flex:1,display:"flex",flexDirection:"column",marginBottom:"1rem"},topFieldsRow:{display:"flex",gap:"1.5rem",marginBottom:"1.5rem"},leftFieldsColumn:{flex:"0 0 50%",display:"flex",flexDirection:"column"},rightFieldsColumn:{flex:"0 0 50%",display:"flex",flexDirection:"column"},lineItemsTableContainer:{maxHeight:"250px",overflowY:"auto",border:"1px solid #ddd",borderRadius:"8px"},manualAddBtn:{marginTop:"0.75rem",padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},productSearchSection:{marginTop:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",border:"1px solid #e9ecef"},productSearchResultsContainer:{height:"200px",overflowY:"auto",background:"white",border:"1px solid #ddd",borderRadius:"8px"},searchPlaceholder:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#999",fontSize:"0.9rem"},searchResultsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},searchTh:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",background:"#f8f8f8",position:"sticky",top:0,fontSize:"0.8rem"},searchTd:{padding:"0.5rem 0.75rem",borderBottom:"1px solid #eee",verticalAlign:"middle"},searchResultRow:{cursor:"pointer"},addFromSearchBtn:{padding:"0.35rem 0.75rem",background:"#27ae60",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",fontSize:"0.8rem"},label:{fontSize:"0.85rem",fontWeight:"bold",color:"#333",marginBottom:"0.5rem"},input:{padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem"},tableInput:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.9rem"},removeItemBtn:{width:"24px",height:"24px",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",fontSize:"1rem",lineHeight:1},submitRow:{display:"flex",justifyContent:"flex-end",gap:"1rem",marginTop:"1.5rem",paddingTop:"1rem",borderTop:"1px solid #eee"},cancelBtn:{padding:"0.75rem 1.5rem",background:"#6c757d",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold"},submitBtn:{padding:"0.75rem 1.5rem",background:"#27ae60",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold"}};/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var CB=function(n,e){return CB=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)r.hasOwnProperty(i)&&(t[i]=r[i])},CB(n,e)};function xt(n,e){CB(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var wn=function(){return wn=Object.assign||function(e){for(var t,r=1,i=arguments.length;r0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]>2],e+=Vx[(n[r]&3)<<4|n[r+1]>>4],e+=Vx[(n[r+1]&15)<<2|n[r+2]>>6],e+=Vx[n[r+2]&63];return t%3===2?e=e.substring(0,e.length-1)+"=":t%3===1&&(e=e.substring(0,e.length-2)+"=="),e},UL=function(n){var e=n.length*.75,t=n.length,r,i=0,o,a,l,d;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var c=new Uint8Array(e);for(r=0;r>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|d&63;return c},Rse=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,Bse=function(n){var e=n.trim(),t=e.substring(0,100),r=t.match(Rse);if(!r)return UL(e);var i=r[0],o=e.substring(i.length);return UL(o)},mn=function(n){return n.charCodeAt(0)},Ise=function(n){return n.codePointAt(0)},Z_=function(n,e){return _c(n.toString(16),e,"0").toUpperCase()},RF=function(n){return Z_(n,2)},gf=function(n){return String.fromCharCode(n)},Mse=function(n){return gf(parseInt(n,16))},_c=function(n,e,t){for(var r="",i=0,o=e-n.length;i=55296&&t<=56319&&n.length>i&&(r=n.charCodeAt(i),r>=56320&&r<=57343&&(o=2)),[n.slice(e,e+o),o]},Lse=function(n){for(var e=[],t=0,r=n.length;tt&&c(),a+=p,l+=g}}return c(),d},Use=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,hH=function(n){var e=n.match(Use);if(e){var t=e[1],r=e[2],i=r===void 0?"01":r,o=e[3],a=o===void 0?"01":o,l=e[4],d=l===void 0?"00":l,c=e[5],u=c===void 0?"00":c,f=e[6],p=f===void 0?"00":f,g=e[7],m=g===void 0?"Z":g,y=e[8],v=y===void 0?"00":y,x=e[9],w=x===void 0?"00":x,S=m==="Z"?"Z":""+m+v+":"+w,_=new Date(t+"-"+i+"-"+a+"T"+d+":"+u+":"+p+S);return _}},Z6=function(n,e){for(var t,r=0,i;r=0&&n<=65535},Jse=function(n){return n>=65536&&n<=1114111},pH=function(n){return Math.floor((n-65536)/1024)+55296},gH=function(n){return(n-65536)%1024+56320},Dg;(function(n){n.BigEndian="BigEndian",n.LittleEndian="LittleEndian"})(Dg||(Dg={}));var Mw="�".codePointAt(0),mH=function(n,e){if(e===void 0&&(e=!0),n.length<=1)return String.fromCodePoint(Mw);for(var t=e?toe(n):Dg.BigEndian,r=e?2:0,i=[];n.length-r>=2;){var o=qL(n[r++],n[r++],t);if(eoe(o))if(n.length-r<2)i.push(Mw);else{var a=qL(n[r++],n[r++],t);HL(a)?i.push(o,a):i.push(Mw)}else HL(o)?(r+=2,i.push(Mw)):i.push(o)}return r=55296&&n<=56319},HL=function(n){return n>=56320&&n<=57343},qL=function(n,e,t){if(t===Dg.LittleEndian)return e<<8|n;if(t===Dg.BigEndian)return n<<8|e;throw new Error("Invalid byteOrder: "+t)},toe=function(n){return yH(n)?Dg.BigEndian:xH(n)?Dg.LittleEndian:Dg.BigEndian},yH=function(n){return n[0]===254&&n[1]===255},xH=function(n){return n[0]===255&&n[1]===254},bH=function(n){return yH(n)||xH(n)},noe=function(n){var e=String(n);if(Math.abs(n)<1){var t=parseInt(n.toString().split("e-")[1]);if(t){var r=n<0;r&&(n*=-1),n*=Math.pow(10,t-1),e="0."+new Array(t).join("0")+n.toString().substring(2),r&&(e="-"+e)}}else{var t=parseInt(n.toString().split("+")[1]);t>20&&(t-=20,n/=Math.pow(10,t),e=n.toString()+new Array(t+1).join("0"))}return e},b5=function(n){return Math.ceil(n.toString(2).length/8)},hx=function(n){for(var e=new Uint8Array(b5(n)),t=1;t<=e.length;t++)e[t-1]=n>>(e.length-t)*8;return e},eC=function(n){throw new Error(n)},Rf={};(function(n){var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function t(o,a){return Object.prototype.hasOwnProperty.call(o,a)}n.assign=function(o){for(var a=Array.prototype.slice.call(arguments,1);a.length;){var l=a.shift();if(l){if(typeof l!="object")throw new TypeError(l+"must be non-object");for(var d in l)t(l,d)&&(o[d]=l[d])}}return o},n.shrinkBuf=function(o,a){return o.length===a?o:o.subarray?o.subarray(0,a):(o.length=a,o)};var r={arraySet:function(o,a,l,d,c){if(a.subarray&&o.subarray){o.set(a.subarray(l,l+d),c);return}for(var u=0;u=0;)n[e]=0}var ooe=0,vH=1,aoe=2,loe=3,doe=258,J6=29,nC=256,Mj=nC+1+J6,sb=30,e3=19,wH=2*Mj+1,Sm=15,bP=16,coe=7,t3=256,SH=16,jH=17,kH=18,TB=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],v5=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],uoe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],_H=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],hoe=512,wh=new Array((Mj+2)*2);w1(wh);var KS=new Array(sb*2);w1(KS);var zj=new Array(hoe);w1(zj);var Oj=new Array(doe-loe+1);w1(Oj);var n3=new Array(J6);w1(n3);var eT=new Array(sb);w1(eT);function vP(n,e,t,r,i){this.static_tree=n,this.extra_bits=e,this.extra_base=t,this.elems=r,this.max_length=i,this.has_stree=n&&n.length}var CH,AH,TH;function wP(n,e){this.dyn_tree=n,this.max_code=0,this.stat_desc=e}function FH(n){return n<256?zj[n]:zj[256+(n>>>7)]}function Lj(n,e){n.pending_buf[n.pending++]=e&255,n.pending_buf[n.pending++]=e>>>8&255}function el(n,e,t){n.bi_valid>bP-t?(n.bi_buf|=e<>bP-n.bi_valid,n.bi_valid+=t-bP):(n.bi_buf|=e<>>=1,t<<=1;while(--e>0);return t>>>1}function foe(n){n.bi_valid===16?(Lj(n,n.bi_buf),n.bi_buf=0,n.bi_valid=0):n.bi_valid>=8&&(n.pending_buf[n.pending++]=n.bi_buf&255,n.bi_buf>>=8,n.bi_valid-=8)}function poe(n,e){var t=e.dyn_tree,r=e.max_code,i=e.stat_desc.static_tree,o=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,l=e.stat_desc.extra_base,d=e.stat_desc.max_length,c,u,f,p,g,m,y=0;for(p=0;p<=Sm;p++)n.bl_count[p]=0;for(t[n.heap[n.heap_max]*2+1]=0,c=n.heap_max+1;cd&&(p=d,y++),t[u*2+1]=p,!(u>r)&&(n.bl_count[p]++,g=0,u>=l&&(g=a[u-l]),m=t[u*2],n.opt_len+=m*(p+g),o&&(n.static_len+=m*(i[u*2+1]+g)));if(y!==0){do{for(p=d-1;n.bl_count[p]===0;)p--;n.bl_count[p]--,n.bl_count[p+1]+=2,n.bl_count[d]--,y-=2}while(y>0);for(p=d;p!==0;p--)for(u=n.bl_count[p];u!==0;)f=n.heap[--c],!(f>r)&&(t[f*2+1]!==p&&(n.opt_len+=(p-t[f*2+1])*t[f*2],t[f*2+1]=p),u--)}}function EH(n,e,t){var r=new Array(Sm+1),i=0,o,a;for(o=1;o<=Sm;o++)r[o]=i=i+t[o-1]<<1;for(a=0;a<=e;a++){var l=n[a*2+1];l!==0&&(n[a*2]=DH(r[l]++,l))}}function goe(){var n,e,t,r,i,o=new Array(Sm+1);for(t=0,r=0;r>=7;r8?Lj(n,n.bi_buf):n.bi_valid>0&&(n.pending_buf[n.pending++]=n.bi_buf),n.bi_buf=0,n.bi_valid=0}function moe(n,e,t,r){RH(n),Lj(n,t),Lj(n,~t),roe.arraySet(n.pending_buf,n.window,e,t,n.pending),n.pending+=t}function KL(n,e,t,r){var i=e*2,o=t*2;return n[i]>1;a>=1;a--)SP(n,t,a);c=o;do a=n.heap[1],n.heap[1]=n.heap[n.heap_len--],SP(n,t,1),l=n.heap[1],n.heap[--n.heap_max]=a,n.heap[--n.heap_max]=l,t[c*2]=t[a*2]+t[l*2],n.depth[c]=(n.depth[a]>=n.depth[l]?n.depth[a]:n.depth[l])+1,t[a*2+1]=t[l*2+1]=c,n.heap[1]=c++,SP(n,t,1);while(n.heap_len>=2);n.heap[--n.heap_max]=n.heap[1],poe(n,e),EH(t,d,n.bl_count)}function YL(n,e,t){var r,i=-1,o,a=e[0*2+1],l=0,d=7,c=4;for(a===0&&(d=138,c=3),e[(t+1)*2+1]=65535,r=0;r<=t;r++)o=a,a=e[(r+1)*2+1],!(++l=3&&n.bl_tree[_H[e]*2+1]===0;e--);return n.opt_len+=3*(e+1)+5+5+4,e}function xoe(n,e,t,r){var i;for(el(n,e-257,5),el(n,t-1,5),el(n,r-4,4),i=0;i>>=1)if(e&1&&n.dyn_ltree[t*2]!==0)return VL;if(n.dyn_ltree[9*2]!==0||n.dyn_ltree[10*2]!==0||n.dyn_ltree[13*2]!==0)return GL;for(t=32;t0?(n.strm.data_type===soe&&(n.strm.data_type=boe(n)),FB(n,n.l_desc),FB(n,n.d_desc),a=yoe(n),i=n.opt_len+3+7>>>3,o=n.static_len+3+7>>>3,o<=i&&(i=o)):i=o=t+5,t+4<=i&&e!==-1?BH(n,e,t,r):n.strategy===ioe||o===i?(el(n,(vH<<1)+(r?1:0),3),XL(n,wh,KS)):(el(n,(aoe<<1)+(r?1:0),3),xoe(n,n.l_desc.max_code+1,n.d_desc.max_code+1,a+1),XL(n,n.dyn_ltree,n.dyn_dtree)),PH(n),r&&RH(n)}function joe(n,e,t){return n.pending_buf[n.d_buf+n.last_lit*2]=e>>>8&255,n.pending_buf[n.d_buf+n.last_lit*2+1]=e&255,n.pending_buf[n.l_buf+n.last_lit]=t&255,n.last_lit++,e===0?n.dyn_ltree[t*2]++:(n.matches++,e--,n.dyn_ltree[(Oj[t]+nC+1)*2]++,n.dyn_dtree[FH(e)*2]++),n.last_lit===n.lit_bufsize-1}v1._tr_init=voe;v1._tr_stored_block=BH;v1._tr_flush_block=Soe;v1._tr_tally=joe;v1._tr_align=woe;function koe(n,e,t,r){for(var i=n&65535|0,o=n>>>16&65535|0,a=0;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[r++]|0,o=o+i|0;while(--a);i%=65521,o%=65521}return i|o<<16|0}var IH=koe;function _oe(){for(var n,e=[],t=0;t<256;t++){n=t;for(var r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e}var Coe=_oe();function Aoe(n,e,t,r){var i=Coe,o=r+t;n^=-1;for(var a=r;a>>8^i[(n^e[a])&255];return n^-1}var MH=Aoe,r3={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},ja=Rf,Id=v1,zH=IH,$f=MH,Toe=r3,I0=0,Foe=1,Doe=3,Eg=4,ZL=5,Pu=0,JL=1,Md=-2,Eoe=-3,jP=-5,Poe=-1,Roe=1,T2=2,Boe=3,Ioe=4,Moe=0,zoe=2,BF=8,Ooe=9,Loe=15,Noe=8,Woe=29,Uoe=256,DB=Uoe+1+Woe,Hoe=30,qoe=19,Voe=2*DB+1,Goe=15,hr=3,gg=258,Dc=gg+hr+1,Koe=32,IF=42,EB=69,w5=73,S5=91,j5=103,jm=113,sS=666,Ns=1,rC=2,b0=3,S1=4,Xoe=3;function mg(n,e){return n.msg=Toe[e],e}function e4(n){return(n<<1)-(n>4?9:0)}function sp(n){for(var e=n.length;--e>=0;)n[e]=0}function Zf(n){var e=n.state,t=e.pending;t>n.avail_out&&(t=n.avail_out),t!==0&&(ja.arraySet(n.output,e.pending_buf,e.pending_out,t,n.next_out),n.next_out+=t,e.pending_out+=t,n.total_out+=t,n.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))}function Bo(n,e){Id._tr_flush_block(n,n.block_start>=0?n.block_start:-1,n.strstart-n.block_start,e),n.block_start=n.strstart,Zf(n.strm)}function Tr(n,e){n.pending_buf[n.pending++]=e}function zw(n,e){n.pending_buf[n.pending++]=e>>>8&255,n.pending_buf[n.pending++]=e&255}function Yoe(n,e,t,r){var i=n.avail_in;return i>r&&(i=r),i===0?0:(n.avail_in-=i,ja.arraySet(e,n.input,n.next_in,i,t),n.state.wrap===1?n.adler=zH(n.adler,e,i,t):n.state.wrap===2&&(n.adler=$f(n.adler,e,i,t)),n.next_in+=i,n.total_in+=i,i)}function OH(n,e){var t=n.max_chain_length,r=n.strstart,i,o,a=n.prev_length,l=n.nice_match,d=n.strstart>n.w_size-Dc?n.strstart-(n.w_size-Dc):0,c=n.window,u=n.w_mask,f=n.prev,p=n.strstart+gg,g=c[r+a-1],m=c[r+a];n.prev_length>=n.good_match&&(t>>=2),l>n.lookahead&&(l=n.lookahead);do if(i=e,!(c[i+a]!==m||c[i+a-1]!==g||c[i]!==c[r]||c[++i]!==c[r+1])){r+=2,i++;do;while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&ra){if(n.match_start=e,a=o,o>=l)break;g=c[r+a-1],m=c[r+a]}}while((e=f[e&u])>d&&--t!==0);return a<=n.lookahead?a:n.lookahead}function v0(n){var e=n.w_size,t,r,i,o,a;do{if(o=n.window_size-n.lookahead-n.strstart,n.strstart>=e+(e-Dc)){ja.arraySet(n.window,n.window,e,e,0),n.match_start-=e,n.strstart-=e,n.block_start-=e,r=n.hash_size,t=r;do i=n.head[--t],n.head[t]=i>=e?i-e:0;while(--r);r=e,t=r;do i=n.prev[--t],n.prev[t]=i>=e?i-e:0;while(--r);o+=e}if(n.strm.avail_in===0)break;if(r=Yoe(n.strm,n.window,n.strstart+n.lookahead,o),n.lookahead+=r,n.lookahead+n.insert>=hr)for(a=n.strstart-n.insert,n.ins_h=n.window[a],n.ins_h=(n.ins_h<n.pending_buf_size-5&&(t=n.pending_buf_size-5);;){if(n.lookahead<=1){if(v0(n),n.lookahead===0&&e===I0)return Ns;if(n.lookahead===0)break}n.strstart+=n.lookahead,n.lookahead=0;var r=n.block_start+t;if((n.strstart===0||n.strstart>=r)&&(n.lookahead=n.strstart-r,n.strstart=r,Bo(n,!1),n.strm.avail_out===0)||n.strstart-n.block_start>=n.w_size-Dc&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=0,e===Eg?(Bo(n,!0),n.strm.avail_out===0?b0:S1):(n.strstart>n.block_start&&(Bo(n,!1),n.strm.avail_out===0),Ns)}function kP(n,e){for(var t,r;;){if(n.lookahead=hr&&(n.ins_h=(n.ins_h<=hr)if(r=Id._tr_tally(n,n.strstart-n.match_start,n.match_length-hr),n.lookahead-=n.match_length,n.match_length<=n.max_lazy_match&&n.lookahead>=hr){n.match_length--;do n.strstart++,n.ins_h=(n.ins_h<=hr&&(n.ins_h=(n.ins_h<4096)&&(n.match_length=hr-1)),n.prev_length>=hr&&n.match_length<=n.prev_length){i=n.strstart+n.lookahead-hr,r=Id._tr_tally(n,n.strstart-1-n.prev_match,n.prev_length-hr),n.lookahead-=n.prev_length-1,n.prev_length-=2;do++n.strstart<=i&&(n.ins_h=(n.ins_h<=hr&&n.strstart>0&&(i=n.strstart-1,r=a[i],r===a[++i]&&r===a[++i]&&r===a[++i])){o=n.strstart+gg;do;while(r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&in.lookahead&&(n.match_length=n.lookahead)}if(n.match_length>=hr?(t=Id._tr_tally(n,1,n.match_length-hr),n.lookahead-=n.match_length,n.strstart+=n.match_length,n.match_length=0):(t=Id._tr_tally(n,0,n.window[n.strstart]),n.lookahead--,n.strstart++),t&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=0,e===Eg?(Bo(n,!0),n.strm.avail_out===0?b0:S1):n.last_lit&&(Bo(n,!1),n.strm.avail_out===0)?Ns:rC}function Zoe(n,e){for(var t;;){if(n.lookahead===0&&(v0(n),n.lookahead===0)){if(e===I0)return Ns;break}if(n.match_length=0,t=Id._tr_tally(n,0,n.window[n.strstart]),n.lookahead--,n.strstart++,t&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=0,e===Eg?(Bo(n,!0),n.strm.avail_out===0?b0:S1):n.last_lit&&(Bo(n,!1),n.strm.avail_out===0)?Ns:rC}function qc(n,e,t,r,i){this.good_length=n,this.max_lazy=e,this.nice_length=t,this.max_chain=r,this.func=i}var Gx;Gx=[new qc(0,0,0,0,Qoe),new qc(4,4,8,4,kP),new qc(4,5,16,8,kP),new qc(4,6,32,32,kP),new qc(4,4,16,16,fx),new qc(8,16,32,32,fx),new qc(8,16,128,128,fx),new qc(8,32,128,256,fx),new qc(32,128,258,1024,fx),new qc(32,258,258,4096,fx)];function Joe(n){n.window_size=2*n.w_size,sp(n.head),n.max_lazy_match=Gx[n.level].max_lazy,n.good_match=Gx[n.level].good_length,n.nice_match=Gx[n.level].nice_length,n.max_chain_length=Gx[n.level].max_chain,n.strstart=0,n.block_start=0,n.lookahead=0,n.insert=0,n.match_length=n.prev_length=hr-1,n.match_available=0,n.ins_h=0}function eae(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=BF,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new ja.Buf16(Voe*2),this.dyn_dtree=new ja.Buf16((2*Hoe+1)*2),this.bl_tree=new ja.Buf16((2*qoe+1)*2),sp(this.dyn_ltree),sp(this.dyn_dtree),sp(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new ja.Buf16(Goe+1),this.heap=new ja.Buf16(2*DB+1),sp(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new ja.Buf16(2*DB+1),sp(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function LH(n){var e;return!n||!n.state?mg(n,Md):(n.total_in=n.total_out=0,n.data_type=zoe,e=n.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?IF:jm,n.adler=e.wrap===2?0:1,e.last_flush=I0,Id._tr_init(e),Pu)}function NH(n){var e=LH(n);return e===Pu&&Joe(n.state),e}function tae(n,e){return!n||!n.state||n.state.wrap!==2?Md:(n.state.gzhead=e,Pu)}function WH(n,e,t,r,i,o){if(!n)return Md;var a=1;if(e===Poe&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),i<1||i>Ooe||t!==BF||r<8||r>15||e<0||e>9||o<0||o>Ioe)return mg(n,Md);r===8&&(r=9);var l=new eae;return n.state=l,l.strm=n,l.wrap=a,l.gzhead=null,l.w_bits=r,l.w_size=1<ZL||e<0)return n?mg(n,Md):Md;if(r=n.state,!n.output||!n.input&&n.avail_in!==0||r.status===sS&&e!==Eg)return mg(n,n.avail_out===0?jP:Md);if(r.strm=n,t=r.last_flush,r.last_flush=e,r.status===IF)if(r.wrap===2)n.adler=0,Tr(r,31),Tr(r,139),Tr(r,8),r.gzhead?(Tr(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Tr(r,r.gzhead.time&255),Tr(r,r.gzhead.time>>8&255),Tr(r,r.gzhead.time>>16&255),Tr(r,r.gzhead.time>>24&255),Tr(r,r.level===9?2:r.strategy>=T2||r.level<2?4:0),Tr(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Tr(r,r.gzhead.extra.length&255),Tr(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(n.adler=$f(n.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=EB):(Tr(r,0),Tr(r,0),Tr(r,0),Tr(r,0),Tr(r,0),Tr(r,r.level===9?2:r.strategy>=T2||r.level<2?4:0),Tr(r,Xoe),r.status=jm);else{var a=BF+(r.w_bits-8<<4)<<8,l=-1;r.strategy>=T2||r.level<2?l=0:r.level<6?l=1:r.level===6?l=2:l=3,a|=l<<6,r.strstart!==0&&(a|=Koe),a+=31-a%31,r.status=jm,zw(r,a),r.strstart!==0&&(zw(r,n.adler>>>16),zw(r,n.adler&65535)),n.adler=1}if(r.status===EB)if(r.gzhead.extra){for(i=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),Zf(n),i=r.pending,r.pending===r.pending_buf_size));)Tr(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=w5)}else r.status=w5;if(r.status===w5)if(r.gzhead.name){i=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),Zf(n),i=r.pending,r.pending===r.pending_buf_size)){o=1;break}r.gzindexi&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),o===0&&(r.gzindex=0,r.status=S5)}else r.status=S5;if(r.status===S5)if(r.gzhead.comment){i=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),Zf(n),i=r.pending,r.pending===r.pending_buf_size)){o=1;break}r.gzindexi&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),o===0&&(r.status=j5)}else r.status=j5;if(r.status===j5&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&Zf(n),r.pending+2<=r.pending_buf_size&&(Tr(r,n.adler&255),Tr(r,n.adler>>8&255),n.adler=0,r.status=jm)):r.status=jm),r.pending!==0){if(Zf(n),n.avail_out===0)return r.last_flush=-1,Pu}else if(n.avail_in===0&&e4(e)<=e4(t)&&e!==Eg)return mg(n,jP);if(r.status===sS&&n.avail_in!==0)return mg(n,jP);if(n.avail_in!==0||r.lookahead!==0||e!==I0&&r.status!==sS){var d=r.strategy===T2?Zoe(r,e):r.strategy===Boe?$oe(r,e):Gx[r.level].func(r,e);if((d===b0||d===S1)&&(r.status=sS),d===Ns||d===b0)return n.avail_out===0&&(r.last_flush=-1),Pu;if(d===rC&&(e===Foe?Id._tr_align(r):e!==ZL&&(Id._tr_stored_block(r,0,0,!1),e===Doe&&(sp(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),Zf(n),n.avail_out===0))return r.last_flush=-1,Pu}return e!==Eg?Pu:r.wrap<=0?JL:(r.wrap===2?(Tr(r,n.adler&255),Tr(r,n.adler>>8&255),Tr(r,n.adler>>16&255),Tr(r,n.adler>>24&255),Tr(r,n.total_in&255),Tr(r,n.total_in>>8&255),Tr(r,n.total_in>>16&255),Tr(r,n.total_in>>24&255)):(zw(r,n.adler>>>16),zw(r,n.adler&65535)),Zf(n),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?Pu:JL)}function iae(n){var e;return!n||!n.state?Md:(e=n.state.status,e!==IF&&e!==EB&&e!==w5&&e!==S5&&e!==j5&&e!==jm&&e!==sS?mg(n,Md):(n.state=null,e===jm?mg(n,Eoe):Pu))}function sae(n,e){var t=e.length,r,i,o,a,l,d,c,u;if(!n||!n.state||(r=n.state,a=r.wrap,a===2||a===1&&r.status!==IF||r.lookahead))return Md;for(a===1&&(n.adler=zH(n.adler,e,t,0)),r.wrap=0,t>=r.w_size&&(a===0&&(sp(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new ja.Buf8(r.w_size),ja.arraySet(u,e,t-r.w_size,r.w_size,0),e=u,t=r.w_size),l=n.avail_in,d=n.next_in,c=n.input,n.avail_in=t,n.next_in=0,n.input=e,v0(r);r.lookahead>=hr;){i=r.strstart,o=r.lookahead-(hr-1);do r.ins_h=(r.ins_h<=252?6:qf>=248?5:qf>=240?4:qf>=224?3:qf>=192?2:1;Nj[254]=Nj[254]=1;M0.string2buf=function(n){var e,t,r,i,o,a=n.length,l=0;for(i=0;i>>6,e[o++]=128|t&63):t<65536?(e[o++]=224|t>>>12,e[o++]=128|t>>>6&63,e[o++]=128|t&63):(e[o++]=240|t>>>18,e[o++]=128|t>>>12&63,e[o++]=128|t>>>6&63,e[o++]=128|t&63);return e};function qH(n,e){if(e<65534&&(n.subarray&&HH||!n.subarray&&UH))return String.fromCharCode.apply(null,MF.shrinkBuf(n,e));for(var t="",r=0;r4){l[r++]=65533,t+=o-1;continue}for(i&=o===2?31:o===3?15:7;o>1&&t1){l[r++]=65533;continue}i<65536?l[r++]=i:(i-=65536,l[r++]=55296|i>>10&1023,l[r++]=56320|i&1023)}return qH(l,r)};M0.utf8border=function(n,e){var t;for(e=e||n.length,e>n.length&&(e=n.length),t=e-1;t>=0&&(n[t]&192)===128;)t--;return t<0||t===0?e:t+Nj[n[t]]>e?t:e};function oae(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var VH=oae,XS=Hu,YS=Rf,PB=M0,RB=r3,aae=VH,GH=Object.prototype.toString,lae=0,_P=4,ob=0,t4=1,n4=2,dae=-1,cae=0,uae=8;function w0(n){if(!(this instanceof w0))return new w0(n);this.options=YS.assign({level:dae,method:uae,chunkSize:16384,windowBits:15,memLevel:8,strategy:cae,to:""},n||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new aae,this.strm.avail_out=0;var t=XS.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==ob)throw new Error(RB[t]);if(e.header&&XS.deflateSetHeader(this.strm,e.header),e.dictionary){var r;if(typeof e.dictionary=="string"?r=PB.string2buf(e.dictionary):GH.call(e.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(e.dictionary):r=e.dictionary,t=XS.deflateSetDictionary(this.strm,r),t!==ob)throw new Error(RB[t]);this._dict_set=!0}}w0.prototype.push=function(n,e){var t=this.strm,r=this.options.chunkSize,i,o;if(this.ended)return!1;o=e===~~e?e:e===!0?_P:lae,typeof n=="string"?t.input=PB.string2buf(n):GH.call(n)==="[object ArrayBuffer]"?t.input=new Uint8Array(n):t.input=n,t.next_in=0,t.avail_in=t.input.length;do{if(t.avail_out===0&&(t.output=new YS.Buf8(r),t.next_out=0,t.avail_out=r),i=XS.deflate(t,o),i!==t4&&i!==ob)return this.onEnd(i),this.ended=!0,!1;(t.avail_out===0||t.avail_in===0&&(o===_P||o===n4))&&(this.options.to==="string"?this.onData(PB.buf2binstring(YS.shrinkBuf(t.output,t.next_out))):this.onData(YS.shrinkBuf(t.output,t.next_out)))}while((t.avail_in>0||t.avail_out===0)&&i!==t4);return o===_P?(i=XS.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===ob):(o===n4&&(this.onEnd(ob),t.avail_out=0),!0)};w0.prototype.onData=function(n){this.chunks.push(n)};w0.prototype.onEnd=function(n){n===ob&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=YS.flattenChunks(this.chunks)),this.chunks=[],this.err=n,this.msg=this.strm.msg};function i3(n,e){var t=new w0(e);if(t.push(n,!0),t.err)throw t.msg||RB[t.err];return t.result}function hae(n,e){return e=e||{},e.raw=!0,i3(n,e)}function fae(n,e){return e=e||{},e.gzip=!0,i3(n,e)}tC.Deflate=w0;tC.deflate=i3;tC.deflateRaw=hae;tC.gzip=fae;var iC={},Rc={},F2=30,pae=12,gae=function(e,t){var r,i,o,a,l,d,c,u,f,p,g,m,y,v,x,w,S,_,b,C,T,F,A,D,P;r=e.state,i=e.next_in,D=e.input,o=i+(e.avail_in-5),a=e.next_out,P=e.output,l=a-(t-e.avail_out),d=a+(e.avail_out-257),c=r.dmax,u=r.wsize,f=r.whave,p=r.wnext,g=r.window,m=r.hold,y=r.bits,v=r.lencode,x=r.distcode,w=(1<>>24,m>>>=b,y-=b,b=_>>>16&255,b===0)P[a++]=_&65535;else if(b&16){C=_&65535,b&=15,b&&(y>>=b,y-=b),y<15&&(m+=D[i++]<>>24,m>>>=b,y-=b,b=_>>>16&255,b&16){if(T=_&65535,b&=15,yc){e.msg="invalid distance too far back",r.mode=F2;break e}if(m>>>=b,y-=b,b=a-l,T>b){if(b=T-b,b>f&&r.sane){e.msg="invalid distance too far back",r.mode=F2;break e}if(F=0,A=g,p===0){if(F+=u-b,b2;)P[a++]=A[F++],P[a++]=A[F++],P[a++]=A[F++],C-=3;C&&(P[a++]=A[F++],C>1&&(P[a++]=A[F++]))}else{F=a-T;do P[a++]=P[F++],P[a++]=P[F++],P[a++]=P[F++],C-=3;while(C>2);C&&(P[a++]=P[F++],C>1&&(P[a++]=P[F++]))}}else if(b&64){e.msg="invalid distance code",r.mode=F2;break e}else{_=x[(_&65535)+(m&(1<>3,i-=C,y-=C<<3,m&=(1<=1&&L[g]===0;g--);if(m>g&&(m=g),g===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,d.bits=1,0;for(p=1;p0&&(e===o4||g!==1))return-1;for(W[1]=0,u=1;ui4||e===a4&&w>s4)return 1;for(;;){M=u-v,l[f]P?(I=O[U+l[f]],H=A[D+l[f]]):(I=96,H=0),_=1<>v)+b]=M<<24|I<<16|H|0;while(b!==0);for(_=1<>=1;if(_!==0?(S&=_-1,S+=_):S=0,f++,--L[u]===0){if(u===g)break;u=t[r+l[f]]}if(u>m&&(S&T)!==C){for(v===0&&(v=m),F+=p,y=u-v,x=1<i4||e===a4&&w>s4)return 1;C=S&T,o[C]=m<<24|y<<16|F-a|0}}return S!==0&&(o[F+S]=u-v<<24|64<<16|0),d.bits=m,0},Ul=Rf,BB=IH,Vc=MH,wae=gae,QS=vae,Sae=0,KH=1,XH=2,l4=4,jae=5,D2=6,S0=0,kae=1,_ae=2,Nd=-2,YH=-3,QH=-4,Cae=-5,d4=8,$H=1,c4=2,u4=3,h4=4,f4=5,p4=6,g4=7,m4=8,y4=9,x4=10,tT=11,sh=12,AP=13,b4=14,TP=15,v4=16,w4=17,S4=18,j4=19,E2=20,P2=21,k4=22,_4=23,C4=24,A4=25,T4=26,FP=27,F4=28,D4=29,Di=30,ZH=31,Aae=32,Tae=852,Fae=592,Dae=15,Eae=Dae;function E4(n){return(n>>>24&255)+(n>>>8&65280)+((n&65280)<<8)+((n&255)<<24)}function Pae(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Ul.Buf16(320),this.work=new Ul.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function JH(n){var e;return!n||!n.state?Nd:(e=n.state,n.total_in=n.total_out=e.total=0,n.msg="",e.wrap&&(n.adler=e.wrap&1),e.mode=$H,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Ul.Buf32(Tae),e.distcode=e.distdyn=new Ul.Buf32(Fae),e.sane=1,e.back=-1,S0)}function eq(n){var e;return!n||!n.state?Nd:(e=n.state,e.wsize=0,e.whave=0,e.wnext=0,JH(n))}function tq(n,e){var t,r;return!n||!n.state||(r=n.state,e<0?(t=0,e=-e):(t=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?Nd:(r.window!==null&&r.wbits!==e&&(r.window=null),r.wrap=t,r.wbits=e,eq(n))}function nq(n,e){var t,r;return n?(r=new Pae,n.state=r,r.window=null,t=tq(n,e),t!==S0&&(n.state=null),t):Nd}function Rae(n){return nq(n,Eae)}var P4=!0,DP,EP;function Bae(n){if(P4){var e;for(DP=new Ul.Buf32(512),EP=new Ul.Buf32(32),e=0;e<144;)n.lens[e++]=8;for(;e<256;)n.lens[e++]=9;for(;e<280;)n.lens[e++]=7;for(;e<288;)n.lens[e++]=8;for(QS(KH,n.lens,0,288,DP,0,n.work,{bits:9}),e=0;e<32;)n.lens[e++]=5;QS(XH,n.lens,0,32,EP,0,n.work,{bits:5}),P4=!1}n.lencode=DP,n.lenbits=9,n.distcode=EP,n.distbits=5}function rq(n,e,t,r){var i,o=n.state;return o.window===null&&(o.wsize=1<=o.wsize?(Ul.arraySet(o.window,e,t-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>r&&(i=r),Ul.arraySet(o.window,e,t-r,i,o.wnext),r-=i,r?(Ul.arraySet(o.window,e,t-r,r,0),o.wnext=r,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,t.check=Vc(t.check,A,2,0),c=0,u=0,t.mode=c4;break}if(t.flags=0,t.head&&(t.head.done=!1),!(t.wrap&1)||(((c&255)<<8)+(c>>8))%31){n.msg="incorrect header check",t.mode=Di;break}if((c&15)!==d4){n.msg="unknown compression method",t.mode=Di;break}if(c>>>=4,u-=4,T=(c&15)+8,t.wbits===0)t.wbits=T;else if(T>t.wbits){n.msg="invalid window size",t.mode=Di;break}t.dmax=1<>8&1),t.flags&512&&(A[0]=c&255,A[1]=c>>>8&255,t.check=Vc(t.check,A,2,0)),c=0,u=0,t.mode=u4;case u4:for(;u<32;){if(l===0)break e;l--,c+=r[o++]<>>8&255,A[2]=c>>>16&255,A[3]=c>>>24&255,t.check=Vc(t.check,A,4,0)),c=0,u=0,t.mode=h4;case h4:for(;u<16;){if(l===0)break e;l--,c+=r[o++]<>8),t.flags&512&&(A[0]=c&255,A[1]=c>>>8&255,t.check=Vc(t.check,A,2,0)),c=0,u=0,t.mode=f4;case f4:if(t.flags&1024){for(;u<16;){if(l===0)break e;l--,c+=r[o++]<>>8&255,t.check=Vc(t.check,A,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=p4;case p4:if(t.flags&1024&&(g=t.length,g>l&&(g=l),g&&(t.head&&(T=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Array(t.head.extra_len)),Ul.arraySet(t.head.extra,r,o,g,T)),t.flags&512&&(t.check=Vc(t.check,r,g,o)),l-=g,o+=g,t.length-=g),t.length))break e;t.length=0,t.mode=g4;case g4:if(t.flags&2048){if(l===0)break e;g=0;do T=r[o+g++],t.head&&T&&t.length<65536&&(t.head.name+=String.fromCharCode(T));while(T&&g>9&1,t.head.done=!0),n.adler=t.check=0,t.mode=sh;break;case x4:for(;u<32;){if(l===0)break e;l--,c+=r[o++]<>>=u&7,u-=u&7,t.mode=FP;break}for(;u<3;){if(l===0)break e;l--,c+=r[o++]<>>=1,u-=1,c&3){case 0:t.mode=b4;break;case 1:if(Bae(t),t.mode=E2,e===D2){c>>>=2,u-=2;break e}break;case 2:t.mode=w4;break;case 3:n.msg="invalid block type",t.mode=Di}c>>>=2,u-=2;break;case b4:for(c>>>=u&7,u-=u&7;u<32;){if(l===0)break e;l--,c+=r[o++]<>>16^65535)){n.msg="invalid stored block lengths",t.mode=Di;break}if(t.length=c&65535,c=0,u=0,t.mode=TP,e===D2)break e;case TP:t.mode=v4;case v4:if(g=t.length,g){if(g>l&&(g=l),g>d&&(g=d),g===0)break e;Ul.arraySet(i,r,o,g,a),l-=g,o+=g,d-=g,a+=g,t.length-=g;break}t.mode=sh;break;case w4:for(;u<14;){if(l===0)break e;l--,c+=r[o++]<>>=5,u-=5,t.ndist=(c&31)+1,c>>>=5,u-=5,t.ncode=(c&15)+4,c>>>=4,u-=4,t.nlen>286||t.ndist>30){n.msg="too many length or distance symbols",t.mode=Di;break}t.have=0,t.mode=S4;case S4:for(;t.have>>=3,u-=3}for(;t.have<19;)t.lens[L[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,D={bits:t.lenbits},F=QS(Sae,t.lens,0,19,t.lencode,0,t.work,D),t.lenbits=D.bits,F){n.msg="invalid code lengths set",t.mode=Di;break}t.have=0,t.mode=j4;case j4:for(;t.have>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<>>=x,u-=x,t.lens[t.have++]=S;else{if(S===16){for(P=x+2;u>>=x,u-=x,t.have===0){n.msg="invalid bit length repeat",t.mode=Di;break}T=t.lens[t.have-1],g=3+(c&3),c>>>=2,u-=2}else if(S===17){for(P=x+3;u>>=x,u-=x,T=0,g=3+(c&7),c>>>=3,u-=3}else{for(P=x+7;u>>=x,u-=x,T=0,g=11+(c&127),c>>>=7,u-=7}if(t.have+g>t.nlen+t.ndist){n.msg="invalid bit length repeat",t.mode=Di;break}for(;g--;)t.lens[t.have++]=T}}if(t.mode===Di)break;if(t.lens[256]===0){n.msg="invalid code -- missing end-of-block",t.mode=Di;break}if(t.lenbits=9,D={bits:t.lenbits},F=QS(KH,t.lens,0,t.nlen,t.lencode,0,t.work,D),t.lenbits=D.bits,F){n.msg="invalid literal/lengths set",t.mode=Di;break}if(t.distbits=6,t.distcode=t.distdyn,D={bits:t.distbits},F=QS(XH,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,D),t.distbits=D.bits,F){n.msg="invalid distances set",t.mode=Di;break}if(t.mode=E2,e===D2)break e;case E2:t.mode=P2;case P2:if(l>=6&&d>=258){n.next_out=a,n.avail_out=d,n.next_in=o,n.avail_in=l,t.hold=c,t.bits=u,wae(n,p),a=n.next_out,i=n.output,d=n.avail_out,o=n.next_in,r=n.input,l=n.avail_in,c=t.hold,u=t.bits,t.mode===sh&&(t.back=-1);break}for(t.back=0;v=t.lencode[c&(1<>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<>_)],x=v>>>24,w=v>>>16&255,S=v&65535,!(_+x<=u);){if(l===0)break e;l--,c+=r[o++]<>>=_,u-=_,t.back+=_}if(c>>>=x,u-=x,t.back+=x,t.length=S,w===0){t.mode=T4;break}if(w&32){t.back=-1,t.mode=sh;break}if(w&64){n.msg="invalid literal/length code",t.mode=Di;break}t.extra=w&15,t.mode=k4;case k4:if(t.extra){for(P=t.extra;u>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=_4;case _4:for(;v=t.distcode[c&(1<>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<>_)],x=v>>>24,w=v>>>16&255,S=v&65535,!(_+x<=u);){if(l===0)break e;l--,c+=r[o++]<>>=_,u-=_,t.back+=_}if(c>>>=x,u-=x,t.back+=x,w&64){n.msg="invalid distance code",t.mode=Di;break}t.offset=S,t.extra=w&15,t.mode=C4;case C4:if(t.extra){for(P=t.extra;u>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){n.msg="invalid distance too far back",t.mode=Di;break}t.mode=A4;case A4:if(d===0)break e;if(g=p-d,t.offset>g){if(g=t.offset-g,g>t.whave&&t.sane){n.msg="invalid distance too far back",t.mode=Di;break}g>t.wnext?(g-=t.wnext,m=t.wsize-g):m=t.wnext-g,g>t.length&&(g=t.length),y=t.window}else y=i,m=a-t.offset,g=t.length;g>d&&(g=d),d-=g,t.length-=g;do i[a++]=y[m++];while(--g);t.length===0&&(t.mode=P2);break;case T4:if(d===0)break e;i[a++]=t.length,d--,t.mode=P2;break;case FP:if(t.wrap){for(;u<32;){if(l===0)break e;l--,c|=r[o++]<=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(n&&n.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Wae,this.strm.avail_out=0;var t=ab.inflateInit2(this.strm,e.windowBits);if(t!==ms.Z_OK)throw new Error(IB[t]);if(this.header=new Uae,ab.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=k5.string2buf(e.dictionary):sq.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=ab.inflateSetDictionary(this.strm,e.dictionary),t!==ms.Z_OK)))throw new Error(IB[t])}j0.prototype.push=function(n,e){var t=this.strm,r=this.options.chunkSize,i=this.options.dictionary,o,a,l,d,c,u=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?ms.Z_FINISH:ms.Z_NO_FLUSH,typeof n=="string"?t.input=k5.binstring2buf(n):sq.call(n)==="[object ArrayBuffer]"?t.input=new Uint8Array(n):t.input=n,t.next_in=0,t.avail_in=t.input.length;do{if(t.avail_out===0&&(t.output=new $S.Buf8(r),t.next_out=0,t.avail_out=r),o=ab.inflate(t,ms.Z_NO_FLUSH),o===ms.Z_NEED_DICT&&i&&(o=ab.inflateSetDictionary(this.strm,i)),o===ms.Z_BUF_ERROR&&u===!0&&(o=ms.Z_OK,u=!1),o!==ms.Z_STREAM_END&&o!==ms.Z_OK)return this.onEnd(o),this.ended=!0,!1;t.next_out&&(t.avail_out===0||o===ms.Z_STREAM_END||t.avail_in===0&&(a===ms.Z_FINISH||a===ms.Z_SYNC_FLUSH))&&(this.options.to==="string"?(l=k5.utf8border(t.output,t.next_out),d=t.next_out-l,c=k5.buf2string(t.output,l),t.next_out=d,t.avail_out=r-d,d&&$S.arraySet(t.output,t.output,l,d,0),this.onData(c)):this.onData($S.shrinkBuf(t.output,t.next_out))),t.avail_in===0&&t.avail_out===0&&(u=!0)}while((t.avail_in>0||t.avail_out===0)&&o!==ms.Z_STREAM_END);return o===ms.Z_STREAM_END&&(a=ms.Z_FINISH),a===ms.Z_FINISH?(o=ab.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===ms.Z_OK):(a===ms.Z_SYNC_FLUSH&&(this.onEnd(ms.Z_OK),t.avail_out=0),!0)};j0.prototype.onData=function(n){this.chunks.push(n)};j0.prototype.onEnd=function(n){n===ms.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=$S.flattenChunks(this.chunks)),this.chunks=[],this.err=n,this.msg=this.strm.msg};function s3(n,e){var t=new j0(e);if(t.push(n,!0),t.err)throw t.msg||IB[t.err];return t.result}function Hae(n,e){return e=e||{},e.raw=!0,s3(n,e)}iC.Inflate=j0;iC.inflate=s3;iC.inflateRaw=Hae;iC.ungzip=s3;var qae=Rf.assign,Vae=tC,Gae=iC,Kae=iq,oq={};qae(oq,Vae,Gae,Kae);var Xae=oq;const zF=a7(Xae);var R4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oS=new Uint8Array(256);for(var R2=0;R2>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|d&63;return c},Qae=function(n){for(var e="",t=0;tr)throw new Error(Ms(e)+" must be at least "+t+" and at most "+r+", but was actually "+n)},nc=function(n,e,t,r){Ie(n,e,["number","undefined"]),typeof n=="number"&&Hl(n,e,t,r)},dq=function(n,e,t){if(Ie(n,e,["number"]),n%t!==0)throw new Error(Ms(e)+" must be a multiple of "+t+", but was actually "+n)},jle=function(n,e){if(!Number.isInteger(n))throw new Error(Ms(e)+" must be an integer, but was actually "+n)},LF=function(n,e){if(![1,0].includes(Math.sign(n)))throw new Error(Ms(e)+" must be a positive number or 0, but was actually "+n)},Sn=new Uint16Array(256);for(var M2=0;M2<256;M2++)Sn[M2]=M2;Sn[22]=mn("");Sn[24]=mn("˘");Sn[25]=mn("ˇ");Sn[26]=mn("ˆ");Sn[27]=mn("˙");Sn[28]=mn("˝");Sn[29]=mn("˛");Sn[30]=mn("˚");Sn[31]=mn("˜");Sn[127]=mn("�");Sn[128]=mn("•");Sn[129]=mn("†");Sn[130]=mn("‡");Sn[131]=mn("…");Sn[132]=mn("—");Sn[133]=mn("–");Sn[134]=mn("ƒ");Sn[135]=mn("⁄");Sn[136]=mn("‹");Sn[137]=mn("›");Sn[138]=mn("−");Sn[139]=mn("‰");Sn[140]=mn("„");Sn[141]=mn("“");Sn[142]=mn("”");Sn[143]=mn("‘");Sn[144]=mn("’");Sn[145]=mn("‚");Sn[146]=mn("™");Sn[147]=mn("fi");Sn[148]=mn("fl");Sn[149]=mn("Ł");Sn[150]=mn("Œ");Sn[151]=mn("Š");Sn[152]=mn("Ÿ");Sn[153]=mn("Ž");Sn[154]=mn("ı");Sn[155]=mn("ł");Sn[156]=mn("œ");Sn[157]=mn("š");Sn[158]=mn("ž");Sn[159]=mn("�");Sn[160]=mn("€");Sn[173]=mn("�");var cq=function(n){for(var e=new Array(n.length),t=0,r=n.length;t=le.ExclamationPoint&&n<=le.Tilde&&!d3[n]},N4={},W4=new Map,se=function(n){xt(e,n);function e(t,r){var i=this;if(t!==N4)throw new o3("PDFName");i=n.call(this)||this;for(var o="/",a=0,l=r.length;a=le.Zero&&c<=le.Nine||c>=le.a&&c<=le.f||c>=le.A&&c<=le.F?(r+=d,(r.length===2||!(u>="0"&&u<="9"||u>="a"&&u<="f"||u>="A"&&u<="F"))&&(o(parseInt(r,16)),r="")):o(c):c===le.Hash?i=!0:o(c)}return new Uint8Array(t)},e.prototype.decodeText=function(){var t=this.asBytes();return String.fromCharCode.apply(String,Array.from(t))},e.prototype.asString=function(){return this.encodedName},e.prototype.value=function(){return this.encodedName},e.prototype.clone=function(){return this},e.prototype.toString=function(){return this.encodedName},e.prototype.sizeInBytes=function(){return this.encodedName.length},e.prototype.copyBytesInto=function(t,r){return r+=Ro(this.encodedName,t,r),this.encodedName.length},e.of=function(t){var r=Wle(t),i=W4.get(r);return i||(i=new e(N4,r),W4.set(r,i)),i},e.Length=e.of("Length"),e.FlateDecode=e.of("FlateDecode"),e.Resources=e.of("Resources"),e.Font=e.of("Font"),e.XObject=e.of("XObject"),e.ExtGState=e.of("ExtGState"),e.Contents=e.of("Contents"),e.Type=e.of("Type"),e.Parent=e.of("Parent"),e.MediaBox=e.of("MediaBox"),e.Page=e.of("Page"),e.Annots=e.of("Annots"),e.TrimBox=e.of("TrimBox"),e.ArtBox=e.of("ArtBox"),e.BleedBox=e.of("BleedBox"),e.CropBox=e.of("CropBox"),e.Rotate=e.of("Rotate"),e.Title=e.of("Title"),e.Author=e.of("Author"),e.Subject=e.of("Subject"),e.Creator=e.of("Creator"),e.Keywords=e.of("Keywords"),e.Producer=e.of("Producer"),e.CreationDate=e.of("CreationDate"),e.ModDate=e.of("ModDate"),e}(Ca),Hle=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.asNull=function(){return null},e.prototype.clone=function(){return this},e.prototype.toString=function(){return"null"},e.prototype.sizeInBytes=function(){return 4},e.prototype.copyBytesInto=function(t,r){return t[r++]=le.n,t[r++]=le.u,t[r++]=le.l,t[r++]=le.l,4},e}(Ca);const Ya=new Hle;var _n=function(n){xt(e,n);function e(t,r){var i=n.call(this)||this;return i.dict=t,i.context=r,i}return e.prototype.keys=function(){return Array.from(this.dict.keys())},e.prototype.values=function(){return Array.from(this.dict.values())},e.prototype.entries=function(){return Array.from(this.dict.entries())},e.prototype.set=function(t,r){this.dict.set(t,r)},e.prototype.get=function(t,r){r===void 0&&(r=!1);var i=this.dict.get(t);if(!(i===Ya&&!r))return i},e.prototype.has=function(t){var r=this.dict.get(t);return r!==void 0&&r!==Ya},e.prototype.lookupMaybe=function(t){for(var r,i=[],o=1;othis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},n.prototype.nextRef=function(){return this.largestObjectNumber+=1,Mr.of(this.largestObjectNumber)},n.prototype.register=function(e){var t=this.nextRef();return this.assign(t,e),t},n.prototype.delete=function(e){return this.indirectObjects.delete(e)},n.prototype.lookupMaybe=function(e){for(var t=[],r=1;r1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(t.push(e),this.chunkLength+=1)},n.create=function(){return new n({ref:Mr.of(0,65535),offset:0,deleted:!0})},n.createEmpty=function(){return new n},n}(),u3=function(){function n(e){this.lastXRefOffset=String(e)}return n.prototype.toString=function(){return`startxref `+this.lastXRefOffset+` %%EOF`},n.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},n.prototype.copyBytesInto=function(e,t){var r=t;return e[t++]=le.s,e[t++]=le.t,e[t++]=le.a,e[t++]=le.r,e[t++]=le.t,e[t++]=le.x,e[t++]=le.r,e[t++]=le.e,e[t++]=le.f,e[t++]=le.Newline,t+=Ro(this.lastXRefOffset,e,t),e[t++]=le.Newline,e[t++]=le.Percent,e[t++]=le.Percent,e[t++]=le.E,e[t++]=le.O,e[t++]=le.F,t-r},n.forLastCrossRefSectionOffset=function(e){return new n(e)},n}(),Gle=function(){function n(e){this.dict=e}return n.prototype.toString=function(){return`trailer `+this.dict.toString()},n.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},n.prototype.copyBytesInto=function(e,t){var r=t;return e[t++]=le.t,e[t++]=le.r,e[t++]=le.a,e[t++]=le.i,e[t++]=le.l,e[t++]=le.e,e[t++]=le.r,e[t++]=le.Newline,t+=this.dict.copyBytesInto(e,t),t-r},n.of=function(e){return new n(e)},n}(),fq=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!0);var o=n.call(this,t.obj({}),i)||this;return o.objects=r,o.offsets=o.computeObjectOffsets(),o.offsetsString=o.computeOffsetsString(),o.dict.set(se.of("Type"),se.of("ObjStm")),o.dict.set(se.of("N"),fn.of(o.objects.length)),o.dict.set(se.of("First"),fn.of(o.offsetsString.length)),o}return e.prototype.getObjectsCount=function(){return this.objects.length},e.prototype.clone=function(t){return e.withContextAndObjects(t||this.dict.context,this.objects.slice(),this.encode)},e.prototype.getContentsString=function(){for(var t=this.offsetsString,r=0,i=this.objects.length;r1&&(a.push(l),a.push(u.ref.objectNumber),l=0),l+=1}return a.push(l),a},o.computeEntryTuples=function(){for(var a=new Array(o.entries.length),l=0,d=o.entries.length;ll[0]&&(l[0]=m),y>l[1]&&(l[1]=y),v>l[2]&&(l[2]=v)}return l},o.entries=r||[],o.entryTuplesCache=mf.populatedBy(o.computeEntryTuples),o.maxByteWidthsCache=mf.populatedBy(o.computeMaxEntryByteWidths),o.indexCache=mf.populatedBy(o.computeIndex),t.set(se.of("Type"),se.of("XRef")),o}return e.prototype.addDeletedEntry=function(t,r){var i=np.Deleted;this.entries.push({type:i,ref:t,nextFreeObjectNumber:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addUncompressedEntry=function(t,r){var i=np.Uncompressed;this.entries.push({type:i,ref:t,offset:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addCompressedEntry=function(t,r,i){var o=np.Compressed;this.entries.push({type:o,ref:t,objectStreamRef:r,index:i}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.clone=function(t){var r=this,i=r.dict,o=r.entries,a=r.encode;return e.of(i.clone(t),o.slice(),a)},e.prototype.getContentsString=function(){for(var t=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),i="",o=0,a=t.length;o=0;m--)i+=(f[m]||0).toString(2);for(var m=r[1]-1;m>=0;m--)i+=(p[m]||0).toString(2);for(var m=r[2]-1;m>=0;m--)i+=(g[m]||0).toString(2)}return i},e.prototype.getUnencodedContents=function(){for(var t=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),i=new Uint8Array(this.getUnencodedContentsSize()),o=0,a=0,l=t.length;a=0;y--)i[o++]=p[y]||0;for(var y=r[1]-1;y>=0;y--)i[o++]=g[y]||0;for(var y=r[2]-1;y>=0;y--)i[o++]=m[y]||0}return i},e.prototype.getUnencodedContentsSize=function(){var t=this.maxByteWidthsCache.access(),r=Kse(t);return r*this.entries.length},e.prototype.updateDict=function(){n.prototype.updateDict.call(this);var t=this.maxByteWidthsCache.access(),r=this.indexCache.access(),i=this.dict.context;this.dict.set(se.of("W"),i.obj(t)),this.dict.set(se.of("Index"),i.obj(r))},e.create=function(t,r){r===void 0&&(r=!0);var i=new e(t,[],r);return i.addDeletedEntry(Mr.of(0,65535),0),i},e.of=function(t,r,i){return i===void 0&&(i=!0),new e(t,r,i)},e}(c3),Xle=function(n){xt(e,n);function e(t,r,i,o){var a=n.call(this,t,r)||this;return a.encodeStreams=i,a.objectsPerStream=o,a}return e.prototype.computeBufferSize=function(){return Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c,m,y,u,x,f,p,v,g,m,y,v,x,w,S,_,b;return Rn(this,function(C){switch(C.label){case 0:t=this.context.largestObjectNumber+1,r=NF.forVersion(1,7),i=r.sizeInBytes()+2,o=Kle.create(this.createTrailerDict(),this.encodeStreams),a=[],l=[],d=[],c=this.context.enumerateIndirectObjects(),m=0,y=c.length,C.label=1;case 1:return m"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(t,r){return t[r++]=le.LessThan,r+=Ro(this.value,t,r),t[r++]=le.GreaterThan,this.value.length+2},e.of=function(t){return new e(t)},e.fromText=function(t){for(var r=$se(t),i="",o=0,a=r.length;o> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange `+n.length+` beginbfchar `+n.map(function(e){var t=e[0],r=e[1];return t+" "+r}).join(` `)+` endbfchar endcmap CMapName currentdict /CMap defineresource pop end end`},V4=function(){for(var n=[],e=0;e"},_5=function(n){return Z_(n,4)},$le=function(n){if(Zse(n))return _5(n);if(Jse(n)){var e=pH(n),t=gH(n);return""+_5(e)+_5(t)}var r=RF(n),i="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(i)},Zle=function(n){var e=0,t=function(r){e|=1<=le.Zero&&c<=le.Seven?(r+=d,(r.length===3||!(u>="0"&&u<="7"))&&(o(parseInt(r,8)),r="")):o(c):c===le.BackSlash?i=!0:o(c)}return new Uint8Array(t)},e.prototype.decodeText=function(){var t=this.asBytes();return bH(t)?mH(t):cq(t)},e.prototype.decodeDate=function(){var t=this.decodeText(),r=hH(t);if(!r)throw new uq(t);return r},e.prototype.asString=function(){return this.value},e.prototype.clone=function(){return e.of(this.value)},e.prototype.toString=function(){return"("+this.value+")"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(t,r){return t[r++]=le.LeftParen,r+=Ro(this.value,t,r),t[r++]=le.RightParen,this.value.length+2},e.of=function(t){return new e(t)},e.fromDate=function(t){var r=_c(String(t.getUTCFullYear()),4,"0"),i=_c(String(t.getUTCMonth()+1),2,"0"),o=_c(String(t.getUTCDate()),2,"0"),a=_c(String(t.getUTCHours()),2,"0"),l=_c(String(t.getUTCMinutes()),2,"0"),d=_c(String(t.getUTCSeconds()),2,"0");return new e("D:"+r+i+o+a+l+d+"Z")},e}(Ca),h3=function(){function n(e,t,r,i){var o=this;this.allGlyphsInFontSortedById=function(){for(var a=new Array(o.font.characterSet.length),l=0,d=a.length;l>3)]>>7-((g&7)<<0)&1,P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D>2)]>>6-((g&3)<<1)&3,P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D>1)]>>4-((g&1)<<2)&15,P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D>>3)]>>>7-(M&7)&1),I=W==v*255?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==2)for(var M=0;M>>2)]>>>6-((M&3)<<1)&3),I=W==v*85?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==4)for(var M=0;M>>1)]>>>4-((M&1)<<2)&15),I=W==v*17?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==8)for(var M=0;M>>2<<3));i==0;){if(i=v(e,p,1),o=v(e,p+1,2),p+=3,o==0){p&7&&(p+=8-(p&7));var F=(p>>>3)+4,A=e[F-4]|e[F-3]<<8;T&&(t=n.H.W(t,f+A)),t.set(new r(e.buffer,e.byteOffset+F,A),f),p=F+A<<3,f+=A;continue}if(T&&(t=n.H.W(t,f+(1<<17))),o==1&&(g=C.J,m=C.h,c=511,u=31),o==2){a=x(e,p,5)+257,l=x(e,p+5,5)+1,d=x(e,p+10,4)+4,p+=14;for(var D=1,P=0;P<38;P+=2)C.Q[P]=0,C.Q[P+1]=0;for(var P=0;PD&&(D=L)}p+=3*d,S(C.Q,D),_(C.Q,D,C.u),g=C.w,m=C.d,p=w(C.u,(1<>>4;if(!(M>>>8))t[f++]=M;else{if(M==256)break;var I=f+M-254;if(M>264){var H=C.q[M-257];I=f+(H>>>3)+x(e,p,H&7),p+=H&7}var z=m[b(e,p)&u];p+=z&15;var G=z>>>4,te=C.c[G],re=(te>>>4)+v(e,p,te&15);for(p+=te&15;f>>4;if(f<=15)a[c]=f,c++;else{var p=0,g=0;f==16?(g=3+l(i,o,2),o+=2,p=a[c-1]):f==17?(g=3+l(i,o,3),o+=3):f==18&&(g=11+l(i,o,7),o+=7);for(var m=c+g;c>>1;ao&&(o=d),a++}for(;a>1,c=e[l+1],u=d<<4|c,f=t-c,p=e[l]<>>15-t;r[m]=u,p++}},n.H.l=function(e,t){for(var r=n.H.m.r,i=15-t,o=0;o>>i}},n.H.M=function(e,t,r){r=r<<(t&7);var i=t>>>3;e[i]|=r,e[i+1]|=r>>>8},n.H.I=function(e,t,r){r=r<<(t&7);var i=t>>>3;e[i]|=r,e[i+1]|=r>>>8,e[i+2]|=r>>>16},n.H.e=function(e,t,r){return(e[t>>>3]|e[(t>>>3)+1]<<8)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)},n.H.i=function(e,t){return(e[t>>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16|e[(t>>>3)+3]<<24)>>>(t&7)},n.H.m=function(){var e=Uint16Array,t=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new t(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new t(286),Y:new t(30),a:new t(19),t:new t(15e3),k:new e(65536),g:new e(32768)}}(),function(){for(var e=n.H.m,t=32768,r=0;r>>1|(i&1431655765)<<1,i=(i&3435973836)>>>2|(i&858993459)<<2,i=(i&4042322160)>>>4|(i&252645135)<<4,i=(i&4278255360)>>>8|(i&16711935)<<8,e.r[r]=(i>>>16|i<<16)>>>17}function o(a,l,d){for(;l--!=0;)a.push(0,d)}for(var r=0;r<32;r++)e.q[r]=e.S[r]<<3|e.T[r],e.c[r]=e.p[r]<<4|e.z[r];o(e._,144,8),o(e._,112,9),o(e._,24,7),o(e._,8,8),n.H.n(e._,9),n.H.A(e._,9,e.J),n.H.l(e._,9),o(e.$,32,5),n.H.n(e.$,5),n.H.A(e.$,5,e.h),n.H.l(e.$,5),o(e.Q,19,0),o(e.C,286,0),o(e.D,30,0),o(e.v,320,0)}(),n.H.N}();dt.decode._readInterlace=function(n,e){for(var t=e.width,r=e.height,i=dt.decode._getBPP(e),o=i>>3,a=Math.ceil(t*i/8),l=new Uint8Array(r*a),d=0,c=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],f=[8,8,8,4,4,2,2],p=[8,8,4,4,2,2,1],g=0;g<7;){for(var m=f[g],y=p[g],v=0,x=0,w=c[g];w>3];A=A>>7-(F&7)&1,l[C*a+(T>>3)]|=A<<7-((T&7)<<0)}if(i==2){var A=n[F>>3];A=A>>6-(F&7)&3,l[C*a+(T>>2)]|=A<<6-((T&3)<<1)}if(i==4){var A=n[F>>3];A=A>>4-(F&7)&15,l[C*a+(T>>1)]|=A<<4-((T&1)<<2)}if(i>=8)for(var D=C*a+T*o,P=0;P>3)+P];F+=i,T+=y}b++,C+=m}v*x!=0&&(d+=x*(1+_)),g=g+1}return l};dt.decode._getBPP=function(n){var e=[1,null,3,1,2,null,4][n.ctype];return e*n.depth};dt.decode._filterZero=function(n,e,t,r,i){var o=dt.decode._getBPP(e),a=Math.ceil(r*o/8),l=dt.decode._paeth;o=Math.ceil(o/8);var d=0,c=1,u=n[t],f=0;if(u>1&&(n[t]=[0,0,1][u-2]),u==3)for(f=o;f>>1)&255;for(var p=0;p>>1);for(;f>>1)}else{for(;f>8&255,n[e+1]=t&255},readUint:function(n,e){return n[e]*(256*256*256)+(n[e+1]<<16|n[e+2]<<8|n[e+3])},writeUint:function(n,e,t){n[e]=t>>24&255,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255},readASCII:function(n,e,t){for(var r="",i=0;i=0&&l>=0?(f=g*e+m<<2,p=(l+g)*i+a+m<<2):(f=(-l+g)*e-a+m<<2,p=g*i+m<<2),d==0)r[p]=n[f],r[p+1]=n[f+1],r[p+2]=n[f+2],r[p+3]=n[f+3];else if(d==1){var y=n[f+3]*.00392156862745098,v=n[f]*y,x=n[f+1]*y,w=n[f+2]*y,S=r[p+3]*(1/255),_=r[p]*S,b=r[p+1]*S,C=r[p+2]*S,T=1-y,F=y+S*T,A=F==0?0:1/F;r[p+3]=255*F,r[p+0]=(v+_*T)*A,r[p+1]=(x+b*T)*A,r[p+2]=(w+C*T)*A}else if(d==2){var y=n[f+3],v=n[f],x=n[f+1],w=n[f+2],S=r[p+3],_=r[p],b=r[p+1],C=r[p+2];y==S&&v==_&&x==b&&w==C?(r[p]=0,r[p+1]=0,r[p+2]=0,r[p+3]=0):(r[p]=v,r[p+1]=x,r[p+2]=w,r[p+3]=y)}else if(d==3){var y=n[f+3],v=n[f],x=n[f+1],w=n[f+2],S=r[p+3],_=r[p],b=r[p+1],C=r[p+2];if(y==S&&v==_&&x==b&&w==C)continue;if(y<220&&S>20)return!1}return!0};dt.encode=function(n,e,t,r,i,o,a){r==null&&(r=0),a==null&&(a=!1);var l=dt.encode.compress(n,e,t,r,[!1,!1,!1,0,a]);return dt.encode.compressPNG(l,-1),dt.encode._main(l,e,t,i,o)};dt.encodeLL=function(n,e,t,r,i,o,a,l){for(var d={ctype:0+(r==1?0:2)+(i==0?0:4),depth:o,frames:[]},c=(r+i)*o,u=c*e,f=0;f1,f=!1,p=33+(u?20:0);if(i.sRGB!=null&&(p+=13),i.pHYs!=null&&(p+=21),n.ctype==3){for(var g=n.plte.length,m=0;m>>24!=255&&(f=!0);p+=8+g*3+4+(f?8+g*1+4:0)}for(var y=0;y>>8&255,T=_>>>16&255;x[c+S+0]=b,x[c+S+1]=C,x[c+S+2]=T}if(c+=g*3,a(x,c,o(x,c-g*3-4,g*3+4)),c+=4,f){a(x,c,g),c+=4,d(x,c,"tRNS"),c+=4;for(var m=0;m>>24&255;c+=g,a(x,c,o(x,c-g-4,g+4)),c+=4}}for(var F=0,y=0;y>2,L>>2));for(var g=0;gU&&I==O[v-U])M[v]=M[v-U];else{var H=S[I];if(H==null&&(S[I]=H=_.length,_.push(I),_.length>=300))break;M[v]=H}}}var z=_.length;z<=256&&c==!1&&(z<=2?f=1:z<=4?f=2:z<=16?f=4:f=8,f=Math.max(f,d));for(var g=0;g>1)]|=ne[ke+Ye]<<4-(Ye&1)*4;else if(f==2)for(var Ye=0;Ye>2)]|=ne[ke+Ye]<<6-(Ye&3)*2;else if(f==1)for(var Ye=0;Ye>3)]|=ne[ke+Ye]<<7-(Ye&7)*1}te=J,u=3,me=1}else if(x==!1&&w.length==1){for(var J=new Uint8Array(U*G*3),De=U*G,v=0;vT&&(T=D),AF&&(F=A))}T==-1&&(b=C=T=F=0),i&&((b&1)==1&&b--,(C&1)==1&&C--);var L=(T-b+1)*(F-C+1);Lv&&(v=_),bx&&(x=b))}v==-1&&(m=y=v=x=0),a&&((m&1)==1&&m--,(y&1)==1&&y--),o={x:m,y,width:v-m+1,height:x-y+1};var F=r[i];F.rect=o,F.blend=1,F.img=new Uint8Array(o.width*o.height*4),r[i-1].dispose==0?(dt._copyTile(c,e,t,F.img,o.width,o.height,-o.x,-o.y,0),dt.encode._prepareDiff(p,e,t,F.img,o)):dt._copyTile(p,e,t,F.img,o.width,o.height,-o.x,-o.y,0)};dt.encode._prepareDiff=function(n,e,t,r,i){dt._copyTile(n,e,t,r,i.width,i.height,-i.x,-i.y,2)};dt.encode._filterZero=function(n,e,t,r,i,o,a){var l=[],d=[0,1,2,3,4];o!=-1?d=[o]:(e*r>5e5||t==1)&&(d=[0]);var c;a&&(c={level:0});for(var u=a&&UZIP!=null?UZIP:zF,f=0;f>1)+256&255;if(o==4)for(var c=i;c>1)&255;for(var c=i;c>1)&255}if(o==4){for(var c=0;c>>1:t=t>>>1;n[e]=t}return n}(),update:function(n,e,t,r){for(var i=0;i>>8;return n},crc:function(n,e,t){return dt.crc.update(4294967295,n,e,t)^4294967295}};dt.quantize=function(n,e){var t=new Uint8Array(n),r=t.slice(0),i=new Uint32Array(r.buffer),o=dt.quantize.getKDtree(r,e),a=o[0],l=o[1];dt.quantize.planeDst;for(var d=t,c=i,u=d.length,f=new Uint8Array(t.length>>2),p=0;p>2]=x.ind,c[p>>2]=x.est.rgba}return{abuf:r.buffer,inds:f,plte:l}};dt.quantize.getKDtree=function(n,e,t){t==null&&(t=1e-4);var r=new Uint32Array(n.buffer),i={i0:0,i1:n.length,bst:null,est:null,tdst:0,left:null,right:null};i.bst=dt.quantize.stats(n,i.i0,i.i1),i.est=dt.quantize.estats(i.bst);for(var o=[i];o.lengtha&&(a=o[d].est.L,l=d);if(a=u||c.i1<=u;if(f){c.est.L=0;continue}var p={i0:c.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};p.bst=dt.quantize.stats(n,p.i0,p.i1),p.est=dt.quantize.estats(p.bst);var g={i0:u,i1:c.i1,bst:null,est:null,tdst:0,left:null,right:null};g.bst={R:[],m:[],N:c.bst.N-p.bst.N};for(var d=0;d<16;d++)g.bst.R[d]=c.bst.R[d]-p.bst.R[d];for(var d=0;d<4;d++)g.bst.m[d]=c.bst.m[d]-p.bst.m[d];g.est=dt.quantize.estats(g.bst),c.left=p,c.right=g,o[l]=p,o.push(g)}o.sort(function(m,y){return y.bst.N-m.bst.N});for(var d=0;d0&&(a=n.right,l=n.left);var d=dt.quantize.getNearest(a,e,t,r,i);if(d.tdst<=o*o)return d;var c=dt.quantize.getNearest(l,e,t,r,i);return c.tdsto;)r-=4;if(t>=r)break;var l=e[t>>2];e[t>>2]=e[r>>2],e[r>>2]=l,t+=4,r-=4}for(;a(n,t,i)>o;)t-=4;return t+4};dt.quantize.vecDot=function(n,e,t){return n[e]*t[0]+n[e+1]*t[1]+n[e+2]*t[2]+n[e+3]*t[3]};dt.quantize.stats=function(n,e,t){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i=[0,0,0,0],o=t-e>>2,a=e;a>>0}};dt.M4={multVec:function(n,e){return[n[0]*e[0]+n[1]*e[1]+n[2]*e[2]+n[3]*e[3],n[4]*e[0]+n[5]*e[1]+n[6]*e[2]+n[7]*e[3],n[8]*e[0]+n[9]*e[1]+n[10]*e[2]+n[11]*e[3],n[12]*e[0]+n[13]*e[1]+n[14]*e[2]+n[15]*e[3]]},dot:function(n,e){return n[0]*e[0]+n[1]*e[1]+n[2]*e[2]+n[3]*e[3]},sml:function(n,e){return[n*e[0],n*e[1],n*e[2],n*e[3]]}};dt.encode.concatRGBA=function(n){for(var e=0,t=0;t1)throw new Error("Animated PNGs are not supported");var i=new Uint8Array(r[0]),o=ide(i),a=o.rgbChannel,l=o.alphaChannel;this.rgbChannel=a;var d=l.some(function(c){return c<255});d&&(this.alphaChannel=l),this.type=rde(t.ctype),this.width=t.width,this.height=t.height,this.bitsPerComponent=8}return n.load=function(e){return new n(e)},n}(),yq=function(){function n(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace="DeviceRGB"}return n.for=function(e){return Pn(this,void 0,void 0,function(){var t;return Rn(this,function(r){return t=sde.load(e),[2,new n(t)]})})},n.prototype.embedIntoContext=function(e,t){return Pn(this,void 0,void 0,function(){var r,i;return Rn(this,function(o){return r=this.embedAlphaChannel(e),i=e.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:r}),t?(e.assign(t,i),[2,t]):[2,e.register(i)]})})},n.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var t=e.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return e.register(t)}},n}(),xq=function(){function n(e,t,r){this.bytes=e,this.start=t||0,this.pos=this.start,this.end=t&&r?t+r:this.bytes.length}return Object.defineProperty(n.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),n.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},n.prototype.getUint16=function(){var e=this.getByte(),t=this.getByte();return e===-1||t===-1?-1:(e<<8)+t},n.prototype.getInt32=function(){var e=this.getByte(),t=this.getByte(),r=this.getByte(),i=this.getByte();return(e<<24)+(t<<16)+(r<<8)+i},n.prototype.getBytes=function(e,t){t===void 0&&(t=!1);var r=this.bytes,i=this.pos,o=this.end;if(e){var l=i+e;l>o&&(l=o),this.pos=l;var a=r.subarray(i,l);return t?new Uint8ClampedArray(a):a}else{var a=r.subarray(i,o);return t?new Uint8ClampedArray(a):a}},n.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},n.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var r=this.getBytes(e,t);return this.pos-=r.length,r},n.prototype.skip=function(e){e||(e=1),this.pos+=e},n.prototype.reset=function(){this.pos=this.start},n.prototype.moveStart=function(){this.start=this.pos},n.prototype.makeSubStream=function(e,t){return new n(this.bytes,e,t)},n.prototype.decode=function(){return this.bytes},n}(),ode=new Uint8Array(0),sC=function(){function n(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=ode,this.minBufferLength=512,e)for(;this.minBufferLengtho&&(r=o)}else{for(;!this.eof;)this.readBlock();r=this.bufferLength}this.pos=r;var a=this.buffer.subarray(i,r);return t&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},n.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},n.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var r=this.getBytes(e,t);return this.pos-=r.length,r},n.prototype.skip=function(e){e||(e=1),this.pos+=e},n.prototype.reset=function(){this.pos=0},n.prototype.makeSubStream=function(e,t){for(var r=e+t;this.bufferLength<=r&&!this.eof;)this.readBlock();return new xq(this.buffer,e,t)},n.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},n.prototype.readBlock=function(){throw new Pd(this.constructor.name,"readBlock")},n.prototype.ensureBuffer=function(e){var t=this.buffer;if(e<=t.byteLength)return t;for(var r=this.minBufferLength;r=0;--c)d[l+c]=f&255,f>>=8}},e}(sC),lde=function(n){xt(e,n);function e(t,r){var i=n.call(this,r)||this;return i.stream=t,i.firstDigit=-1,r&&(r=.5*r),i}return e.prototype.readBlock=function(){var t=8e3,r=this.stream.getBytes(t);if(!r.length){this.eof=!0;return}for(var i=r.length+1>>1,o=this.ensureBuffer(this.bufferLength+i),a=this.bufferLength,l=this.firstDigit,d=0,c=r.length;d=48&&u<=57)f=u&15;else if(u>=65&&u<=70||u>=97&&u<=102)f=(u&15)+9;else if(u===62){this.eof=!0;break}else continue;l<0?l=f:(o[a++]=l<<4|f,l=-1)}l>=0&&this.eof&&(o[a++]=l<<4,l=-1),this.firstDigit=l,this.bufferLength=a},e}(sC),X4=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),dde=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),cde=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),ude=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],hde=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],fde=function(n){xt(e,n);function e(t,r){var i=n.call(this,r)||this;i.stream=t;var o=t.getByte(),a=t.getByte();if(o===-1||a===-1)throw new Error("Invalid header in flate stream: "+o+", "+a);if((o&15)!==8)throw new Error("Unknown compression method in flate stream: "+o+", "+a);if(((o<<8)+a)%31!==0)throw new Error("Bad FCHECK in flate stream: "+o+", "+a);if(a&32)throw new Error("FDICT bit set in flate stream: "+o+", "+a);return i.codeSize=0,i.codeBuf=0,i}return e.prototype.readBlock=function(){var t,r,i=this.stream,o=this.getBits(3);if(o&1&&(this.eof=!0),o>>=1,o===0){var a=void 0;if((a=i.getByte())===-1)throw new Error("Bad block header in flate stream");var l=a;if((a=i.getByte())===-1)throw new Error("Bad block header in flate stream");if(l|=a<<8,(a=i.getByte())===-1)throw new Error("Bad block header in flate stream");var d=a;if((a=i.getByte())===-1)throw new Error("Bad block header in flate stream");if(d|=a<<8,d!==(~l&65535)&&(l!==0||d!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var c=this.bufferLength;t=this.ensureBuffer(c+l);var u=c+l;if(this.bufferLength=u,l===0)i.peekByte()===-1&&(this.eof=!0);else for(var f=c;f0;)b[w++]=F}p=this.generateHuffmanTable(b.subarray(0,m)),g=this.generateHuffmanTable(b.subarray(m,_))}else throw new Error("Unknown block type in flate stream");t=this.buffer;for(var P=t?t.length:0,L=this.bufferLength;;){var W=this.getCode(p);if(W<256){L+1>=P&&(t=this.ensureBuffer(L+1),P=t.length),t[L++]=W;continue}if(W===256){this.bufferLength=L;return}W-=257,W=dde[W];var O=W>>16;O>0&&(O=this.getBits(O)),r=(W&65535)+O,W=this.getCode(g),W=cde[W],O=W>>16,O>0&&(O=this.getBits(O));var U=(W&65535)+O;L+r>=P&&(t=this.ensureBuffer(L+r),P=t.length);for(var M=0;M>t,this.codeSize=i-=t,a},e.prototype.getCode=function(t){for(var r=this.stream,i=t[0],o=t[1],a=this.codeSize,l=this.codeBuf,d;a>16,f=c&65535;if(u<1||a>u,this.codeSize=a-u,f},e.prototype.generateHuffmanTable=function(t){var r=t.length,i=0,o;for(o=0;oi&&(i=t[o]);for(var a=1<>=1;for(o=p;o0;if(!b||b<256)v[0]=b,x=1;else if(b>=258)if(b=0;a--)v[a]=f[l],l=g[l];else v[x++]=v[0];else if(b===256){m=9,u=258,x=0;continue}else{this.eof=!0,delete this.lzwState;break}if(C&&(g[u]=y,p[u]=p[y]+1,f[u]=v[0],u++,m=u+c&u+c-1?m:Math.min(Math.log(u+c)/.6931471805599453+1,12)|0),y=b,w+=x,r>>r&(1<0){var a=this.stream.getBytes(o);r.set(a,i),i+=o}}else{o=257-o;var l=t[1];r=this.ensureBuffer(i+o+1);for(var d=0;dr.size())throw new rT(t,0,r.size());r.remove(t)}else{if(t!==0)throw new rT(t,0,0);this.setKids([])}},e.prototype.normalizedEntries=function(){var t=this.Kids();return t||(t=this.dict.context.obj([this.ref]),this.dict.set(se.of("Kids"),t)),{Kids:t}},e.fromDict=function(t,r){return new e(t,r)},e}(wq),f3=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.Opt=function(){return this.dict.lookupMaybe(se.of("Opt"),Ir,dn,Sr)},e.prototype.setOpt=function(t){this.dict.set(se.of("Opt"),this.dict.context.obj(t))},e.prototype.getExportValues=function(){var t=this.Opt();if(t){if(t instanceof Ir||t instanceof dn)return[t];for(var r=[],i=0,o=t.size();ir.size())throw new rT(t,0,r.size());r.remove(t)}},e.prototype.normalizeExportValues=function(){for(var t,r,i,o,a=(t=this.getExportValues())!==null&&t!==void 0?t:[],l=[],d=this.getWidgets(),c=0,u=d.length;c1){if(!this.hasFlag(Br.MultiSelect))throw new Fle;this.dict.set(se.of("V"),this.dict.context.obj(t))}this.updateSelectedIndices(t)},e.prototype.valuesAreValid=function(t){for(var r=this.getOptions(),i=function(d,c){var u=t[d].decodeText();if(!r.find(function(f){return u===(f.display||f.value).decodeText()}))return{value:!1}},o=0,a=t.length;o1){for(var r=new Array(t.length),i=this.getOptions(),o=function(d,c){var u=t[d].decodeText();r[d]=i.findIndex(function(f){return u===(f.display||f.value).decodeText()})},a=0,l=t.length;a0){var l=a.lookup(0,Ir,dn),d=a.lookupMaybe(1,Ir,dn);r.push({value:l,display:d||l})}}return r}return[]},e}(j1),UF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Ch",Ff:Br.Combo,Kids:[]}),i=t.register(r);return new e(r,i)},e}(Sq),oT=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.addField=function(t){var r=this.normalizedEntries().Kids;r==null||r.push(t)},e.prototype.normalizedEntries=function(){var t=this.Kids();return t||(t=this.dict.context.obj([]),this.dict.set(se.of("Kids"),t)),{Kids:t}},e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({}),i=t.register(r);return new e(r,i)},e}(wq),p3=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.fromDict=function(t,r){return new e(t,r)},e}(j1),HF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.MaxLen=function(){var t=this.dict.lookup(se.of("MaxLen"));if(t instanceof fn)return t},e.prototype.Q=function(){var t=this.dict.lookup(se.of("Q"));if(t instanceof fn)return t},e.prototype.setMaxLength=function(t){this.dict.set(se.of("MaxLen"),fn.of(t))},e.prototype.removeMaxLength=function(){this.dict.delete(se.of("MaxLen"))},e.prototype.getMaxLength=function(){var t;return(t=this.MaxLen())===null||t===void 0?void 0:t.asNumber()},e.prototype.setQuadding=function(t){this.dict.set(se.of("Q"),fn.of(t))},e.prototype.getQuadding=function(){var t;return(t=this.Q())===null||t===void 0?void 0:t.asNumber()},e.prototype.setValue=function(t){this.dict.set(se.of("V"),t)},e.prototype.removeValue=function(){this.dict.delete(se.of("V"))},e.prototype.getValue=function(){var t=this.V();if(t instanceof Ir||t instanceof dn)return t},e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Tx",Kids:[]}),i=t.register(r);return new e(r,i)},e}(j1),qF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Btn",Ff:Cd.PushButton,Kids:[]}),i=t.register(r);return new e(r,i)},e}(f3),VF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.setValue=function(t){var r=this.getOnValues();if(!r.includes(t)&&t!==se.of("Off"))throw new l3;this.dict.set(se.of("V"),t);for(var i=this.getWidgets(),o=0,a=i.length;oo)throw new z4(r,o);for(var a=r,l=0,d=i.size();la)return u.insertLeafNode(t,a)||c;a-=u.Count().asNumber()}u instanceof yf&&(a-=1)}if(a===0){this.insertLeafKid(i.size(),t);return}throw new O4(r,"insertLeafNode")},e.prototype.removeLeafNode=function(t,r){r===void 0&&(r=!0);var i=this.Kids(),o=this.Count().asNumber();if(t>=o)throw new z4(t,o);for(var a=t,l=0,d=i.size();la){u.removeLeafNode(a,r),r&&u.Kids().size()===0&&i.remove(l);return}else a-=u.Count().asNumber();if(u instanceof yf)if(a===0){this.removeKid(l);return}else a-=1}throw new O4(t,"removeLeafNode")},e.prototype.ascend=function(t){t(this);var r=this.Parent();r&&r.ascend(t)},e.prototype.traverse=function(t){for(var r=this.Kids(),i=0,o=r.size();iNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var i="Parsed number that is too large for some PDF readers: "+e+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(i),Number.MAX_SAFE_INTEGER}else{var i="Parsed number that is too large for some PDF readers: "+e+", not capping.";console.warn(i)}return r},n.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&Bf[this.bytes.peek()];)this.bytes.next()},n.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===$4||e===Z4)return;this.bytes.next()}},n.prototype.skipComment=function(){if(this.bytes.peek()!==le.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===$4||e===Z4)return!0;this.bytes.next()}return!0},n.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},n.prototype.matchKeyword=function(e){for(var t=this.bytes.offset(),r=0,i=e.length;r=this.length},n.prototype.offset=function(){return this.idx},n.prototype.slice=function(e,t){return this.bytes.slice(e,t)},n.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},n.of=function(e){return new n(e)},n.fromPDFRawStream=function(e){return n.of(bq(e).decode())},n}(),Cde=le.Space,Nw=le.CarriageReturn,Ww=le.Newline,Uw=[le.s,le.t,le.r,le.e,le.a,le.m],O2=[le.e,le.n,le.d,le.s,le.t,le.r,le.e,le.a,le.m],ai={header:[le.Percent,le.P,le.D,le.F,le.Dash],eof:[le.Percent,le.Percent,le.E,le.O,le.F],obj:[le.o,le.b,le.j],endobj:[le.e,le.n,le.d,le.o,le.b,le.j],xref:[le.x,le.r,le.e,le.f],trailer:[le.t,le.r,le.a,le.i,le.l,le.e,le.r],startxref:[le.s,le.t,le.a,le.r,le.t,le.x,le.r,le.e,le.f],true:[le.t,le.r,le.u,le.e],false:[le.f,le.a,le.l,le.s,le.e],null:[le.n,le.u,le.l,le.l],stream:Uw,streamEOF1:fr(Uw,[Cde,Nw,Ww]),streamEOF2:fr(Uw,[Nw,Ww]),streamEOF3:fr(Uw,[Nw]),streamEOF4:fr(Uw,[Ww]),endstream:O2,EOF1endstream:fr([Nw,Ww],O2),EOF2endstream:fr([Nw],O2),EOF3endstream:fr([Ww],O2)},Aq=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!1);var o=n.call(this,t,i)||this;return o.context=r,o}return e.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(ai.true))return Uj.True;if(this.matchKeyword(ai.false))return Uj.False;if(this.matchKeyword(ai.null))return Ya;var t=this.bytes.peek();if(t===le.LessThan&&this.bytes.peekAhead(1)===le.LessThan)return this.parseDictOrStream();if(t===le.LessThan)return this.parseHexString();if(t===le.LeftParen)return this.parseString();if(t===le.ForwardSlash)return this.parseName();if(t===le.LeftSquareBracket)return this.parseArray();if(y3[t])return this.parseNumberOrRef();throw new Rle(this.bytes.position(),t)},e.prototype.parseNumberOrRef=function(){var t=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(oa[this.bytes.peek()]){var i=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===le.R)return this.bytes.assertNext(le.R),Mr.of(t,i)}return this.bytes.moveTo(r),fn.of(t)},e.prototype.parseHexString=function(){var t="";for(this.bytes.assertNext(le.LessThan);!this.bytes.done()&&this.bytes.peek()!==le.GreaterThan;)t+=gf(this.bytes.next());return this.bytes.assertNext(le.GreaterThan),dn.of(t)},e.prototype.parseString=function(){for(var t=0,r=!1,i="";!this.bytes.done();){var o=this.bytes.next();if(i+=gf(o),r||(o===le.LeftParen&&(t+=1),o===le.RightParen&&(t-=1)),o===le.BackSlash?r=!r:r&&(r=!1),t===0)return Ir.of(i.substring(1,i.length-1))}throw new Mle(this.bytes.position())},e.prototype.parseName=function(){this.bytes.assertNext(le.ForwardSlash);for(var t="";!this.bytes.done();){var r=this.bytes.peek();if(Bf[r]||qd[r])break;t+=gf(r),this.bytes.next()}return se.of(t)},e.prototype.parseArray=function(){this.bytes.assertNext(le.LeftSquareBracket),this.skipWhitespaceAndComments();for(var t=Sr.withContext(this.context);this.bytes.peek()!==le.RightSquareBracket;){var r=this.parseObject();t.push(r),this.skipWhitespaceAndComments()}return this.bytes.assertNext(le.RightSquareBracket),t},e.prototype.parseDict=function(){this.bytes.assertNext(le.LessThan),this.bytes.assertNext(le.LessThan),this.skipWhitespaceAndComments();for(var t=new Map;!this.bytes.done()&&this.bytes.peek()!==le.GreaterThan&&this.bytes.peekAhead(1)!==le.GreaterThan;){var r=this.parseName(),i=this.parseObject();t.set(r,i),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(le.GreaterThan),this.bytes.assertNext(le.GreaterThan);var o=t.get(se.of("Type"));return o===se.of("Catalog")?_q.fromMapWithContext(t,this.context):o===se.of("Pages")?Cq.fromMapWithContext(t,this.context):o===se.of("Page")?yf.fromMapWithContext(t,this.context):_n.fromMapWithContext(t,this.context)},e.prototype.parseDictOrStream=function(){var t=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(ai.streamEOF1)&&!this.matchKeyword(ai.streamEOF2)&&!this.matchKeyword(ai.streamEOF3)&&!this.matchKeyword(ai.streamEOF4)&&!this.matchKeyword(ai.stream))return r;var i=this.bytes.offset(),o,a=r.get(se.of("Length"));a instanceof fn?(o=i+a.asNumber(),this.bytes.moveTo(o),this.skipWhitespaceAndComments(),this.matchKeyword(ai.endstream)||(this.bytes.moveTo(i),o=this.findEndOfStreamFallback(t))):o=this.findEndOfStreamFallback(t);var l=this.bytes.slice(i,o);return Hj.of(r,l)},e.prototype.findEndOfStreamFallback=function(t){for(var r=1,i=this.bytes.offset();!this.bytes.done()&&(i=this.bytes.offset(),this.matchKeyword(ai.stream)?r+=1:this.matchKeyword(ai.EOF1endstream)||this.matchKeyword(ai.EOF2endstream)||this.matchKeyword(ai.EOF3endstream)||this.matchKeyword(ai.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new Ile(t);return i},e.forBytes=function(t,r,i){return new e(XF.of(t),r,i)},e.forByteStream=function(t,r,i){return i===void 0&&(i=!1),new e(t,r,i)},e}(_de),Ade=function(n){xt(e,n);function e(t,r){var i=n.call(this,XF.fromPDFRawStream(t),t.dict.context)||this,o=t.dict;return i.alreadyParsed=!1,i.shouldWaitForTick=r||function(){return!1},i.firstOffset=o.lookup(se.of("First"),fn).asNumber(),i.objectCount=o.lookup(se.of("N"),fn).asNumber(),i}return e.prototype.parseIntoContext=function(){return Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c;return Rn(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new a3("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,t=this.parseOffsetsAndObjectNumbers(),r=0,i=t.length,u.label=1;case 1:return r=le.Space&&r<=le.Tilde;if(i&&(this.matchKeyword(ai.xref)||this.matchKeyword(ai.trailer)||this.matchKeyword(ai.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(t);break}this.bytes.next()}},e.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var t=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(t)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},e.forBytesWithOptions=function(t,r,i,o){return new e(t,r,i,o)},e}(Aq),Gc=function(n){return 1<0&&(r[r.length]=+i),t[t.length]={cmd:e,args:r},r=[],i="",o=!1),e=c;else if([" ",","].includes(c)||c==="-"&&i.length>0&&i[i.length-1]!=="e"||c==="."&&o){if(i.length===0)continue;r.length===a?(t[t.length]={cmd:e,args:r},r=[+i],e==="M"&&(e="L"),e==="m"&&(e="l")):r[r.length]=+i,o=c===".",i=["-","."].includes(c)?c:""}else i+=c,c==="."&&(o=!0)}return i.length>0&&(r.length===a?(t[t.length]={cmd:e,args:r},r=[+i],e==="M"&&(e="L"),e==="m"&&(e="l")):r[r.length]=+i),t[t.length]={cmd:e,args:r},t},Ude=function(n){$t=Zt=ir=sr=aS=lS=0;for(var e=[],t=0;t1&&(p=Math.sqrt(p),t*=p,r*=p);var g=f/t,m=u/t,y=-u/r,v=f/r,x=g*l+m*d,w=y*l+v*d,S=g*n+m*e,_=y*n+v*e,b=(S-x)*(S-x)+(_-w)*(_-w),C=1/b-.25;C<0&&(C=0);var T=Math.sqrt(C);o===i&&(T=-T);var F=.5*(x+S)-T*(_-w),A=.5*(w+_)+T*(S-x),D=Math.atan2(w-A,x-F),P=Math.atan2(_-A,S-F),L=P-D;L<0&&o===1?L+=2*Math.PI:L>0&&o===0&&(L-=2*Math.PI);for(var W=Math.ceil(Math.abs(L/(Math.PI*.5+.001))),O=[],U=0;Un.length)return i-1;var v=e.heightAtSize(i),x=v+v*.2,w=x*o;if(w>Math.abs(t.height))return i-1;i+=1}return i},cce=function(n,e,t,r){for(var i=t.width/r,o=t.height,a=Vq,l=Lse(n);ai*.75;if(f)return a-1}var p=e.heightAtSize(a,{descender:!1});if(p>o)return a-1;a+=1}return a},uce=function(n){for(var e=n.length;e>0;e--)if(/\s/.test(n[e]))return e},hce=function(n,e,t,r){for(var i,o=n.length;o>0;){var a=n.substring(0,o),l=t.encodeText(a),d=t.widthOfTextAtSize(a,r);if(dp&&(p=T+b),m+l>g&&(g=m+l),c.push({text:S,encoded:_,width:b,height:l,x:T,y:m}),x=C==null?void 0:C.trim()}return{fontSize:r,lineHeight:d,lines:c,bounds:{x:u,y:f,width:p-u,height:g-f}}},fce=function(n,e){var t=e.fontSize,r=e.font,i=e.bounds,o=e.cellCount,a=cH(J_(n));if(a.length>o)throw new ace(a.length,o);(t===void 0||t===0)&&(t=cce(a,r,i,o));for(var l=i.width/o,d=r.heightAtSize(t,{descender:!1}),c=i.y+(i.height/2-d/2),u=[],f=i.x,p=i.y,g=i.x+i.width,m=i.y+i.height,y=0,v=0;yg&&(g=T+b),c+d>m&&(m=c+d),u.push({text:a,encoded:_,width:b,height:d,x:T,y:c}),y+=1,v+=S}return{fontSize:t,cells:u,bounds:{x:f,y:p,width:g-f,height:m-p}}},hT=function(n,e){var t=e.alignment,r=e.fontSize,i=e.font,o=e.bounds,a=cH(J_(n));(r===void 0||r===0)&&(r=Kq([a],i,o));var l=i.encodeText(a),d=i.widthOfTextAtSize(a,r),c=i.heightAtSize(r,{descender:!1}),u=t===Os.Left?o.x:t===Os.Center?o.x+o.width/2-d/2:t===Os.Right?o.x+o.width-d:o.x,f=o.y+(o.height/2-c/2);return{fontSize:r,line:{text:a,encoded:l,width:d,height:c,x:u,y:f},bounds:{x:u,y:f,width:d,height:c}}},_1=function(n){return"normal"in n?n:{normal:n}},pce=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,Lg=function(n){var e,t,r=(e=n.getDefaultAppearance())!==null&&e!==void 0?e:"",i=(t=Z6(r,pce).match)!==null&&t!==void 0?t:[],o=Number(i[2]);return isFinite(o)?o:void 0},gce=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,Wd=function(n){var e,t=(e=n.getDefaultAppearance())!==null&&e!==void 0?e:"",r=Z6(t,gce).match,i=r??[],o=i[1],a=i[2],l=i[3],d=i[4],c=i[5];if(c==="g"&&o)return Nq(Number(o));if(c==="rg"&&o&&a&&l)return zr(Number(o),Number(a),Number(l));if(c==="k"&&o&&a&&l&&d)return Wq(Number(o),Number(a),Number(l),Number(d))},Ud=function(n,e,t,r){var i;r===void 0&&(r=0);var o=[L0(e).toString(),w3((i=t==null?void 0:t.name)!==null&&i!==void 0?i:"dummy__noop",r).toString()].join(` `);n.setDefaultAppearance(o)},mce=function(n,e){var t,r,i,o=Wd(e),a=Wd(n.acroField),l=e.getRectangle(),d=e.getAppearanceCharacteristics(),c=e.getBorderStyle(),u=(t=c==null?void 0:c.getWidth())!==null&&t!==void 0?t:0,f=If(d==null?void 0:d.getRotation()),p=z0(l,f),g=p.width,m=p.height,y=Kg(wn(wn({},l),{rotation:f})),v=zr(0,0,0),x=(r=Aa(d==null?void 0:d.getBorderColor()))!==null&&r!==void 0?r:v,w=Aa(d==null?void 0:d.getBackgroundColor()),S=Aa(d==null?void 0:d.getBackgroundColor(),.8),_=(i=o??a)!==null&&i!==void 0?i:v;Ud(o?e:n.acroField,_);var b={x:0+u/2,y:0+u/2,width:g-u,height:m-u,thickness:1.5,borderWidth:u,borderColor:x,markColor:_};return{normal:{on:fr(y,W2(wn(wn({},b),{color:w,filled:!0}))),off:fr(y,W2(wn(wn({},b),{color:w,filled:!1})))},down:{on:fr(y,W2(wn(wn({},b),{color:S,filled:!0}))),off:fr(y,W2(wn(wn({},b),{color:S,filled:!1})))}}},yce=function(n,e){var t,r,i,o=Wd(e),a=Wd(n.acroField),l=e.getRectangle(),d=e.getAppearanceCharacteristics(),c=e.getBorderStyle(),u=(t=c==null?void 0:c.getWidth())!==null&&t!==void 0?t:0,f=If(d==null?void 0:d.getRotation()),p=z0(l,f),g=p.width,m=p.height,y=Kg(wn(wn({},l),{rotation:f})),v=zr(0,0,0),x=(r=Aa(d==null?void 0:d.getBorderColor()))!==null&&r!==void 0?r:v,w=Aa(d==null?void 0:d.getBackgroundColor()),S=Aa(d==null?void 0:d.getBackgroundColor(),.8),_=(i=o??a)!==null&&i!==void 0?i:v;Ud(o?e:n.acroField,_);var b={x:g/2,y:m/2,width:g-u,height:m-u,borderWidth:u,borderColor:x,dotColor:_};return{normal:{on:fr(y,U2(wn(wn({},b),{color:w,filled:!0}))),off:fr(y,U2(wn(wn({},b),{color:w,filled:!1})))},down:{on:fr(y,U2(wn(wn({},b),{color:S,filled:!0}))),off:fr(y,U2(wn(wn({},b),{color:S,filled:!1})))}}},xce=function(n,e,t){var r,i,o,a,l,d=Wd(e),c=Wd(n.acroField),u=Lg(e),f=Lg(n.acroField),p=e.getRectangle(),g=e.getAppearanceCharacteristics(),m=e.getBorderStyle(),y=g==null?void 0:g.getCaptions(),v=(r=y==null?void 0:y.normal)!==null&&r!==void 0?r:"",x=(o=(i=y==null?void 0:y.down)!==null&&i!==void 0?i:v)!==null&&o!==void 0?o:"",w=(a=m==null?void 0:m.getWidth())!==null&&a!==void 0?a:0,S=If(g==null?void 0:g.getRotation()),_=z0(p,S),b=_.width,C=_.height,T=Kg(wn(wn({},p),{rotation:S})),F=zr(0,0,0),A=Aa(g==null?void 0:g.getBorderColor()),D=Aa(g==null?void 0:g.getBackgroundColor()),P=Aa(g==null?void 0:g.getBackgroundColor(),.8),L={x:w,y:w,width:b-w*2,height:C-w*2},W=hT(v,{alignment:Os.Center,fontSize:u??f,font:t,bounds:L}),O=hT(x,{alignment:Os.Center,fontSize:u??f,font:t,bounds:L}),U=Math.min(W.fontSize,O.fontSize),M=(l=d??c)!==null&&l!==void 0?l:F;Ud(d||u!==void 0?e:n.acroField,M,t,U);var I={x:0+w/2,y:0+w/2,width:b-w,height:C-w,borderWidth:w,borderColor:A,textColor:M,font:t.name,fontSize:U};return{normal:fr(T,sN(wn(wn({},I),{color:D,textLines:[W.line]}))),down:fr(T,sN(wn(wn({},I),{color:P,textLines:[O.line]})))}},bce=function(n,e,t){var r,i,o,a,l=Wd(e),d=Wd(n.acroField),c=Lg(e),u=Lg(n.acroField),f=e.getRectangle(),p=e.getAppearanceCharacteristics(),g=e.getBorderStyle(),m=(r=n.getText())!==null&&r!==void 0?r:"",y=(i=g==null?void 0:g.getWidth())!==null&&i!==void 0?i:0,v=If(p==null?void 0:p.getRotation()),x=z0(f,v),w=x.width,S=x.height,_=Kg(wn(wn({},f),{rotation:v})),b=zr(0,0,0),C=Aa(p==null?void 0:p.getBorderColor()),T=Aa(p==null?void 0:p.getBackgroundColor()),F,A,D=n.isCombed()?0:1,P={x:y+D,y:y+D,width:w-(y+D)*2,height:S-(y+D)*2};if(n.isMultiline()){var L=Xq(m,{alignment:n.getAlignment(),fontSize:c??u,font:t,bounds:P});F=L.lines,A=L.fontSize}else if(n.isCombed()){var L=fce(m,{fontSize:c??u,font:t,bounds:P,cellCount:(o=n.getMaxLength())!==null&&o!==void 0?o:0});F=L.cells,A=L.fontSize}else{var L=hT(m,{alignment:n.getAlignment(),fontSize:c??u,font:t,bounds:P});F=[L.line],A=L.fontSize}var W=(a=l??d)!==null&&a!==void 0?a:b;Ud(l||c!==void 0?e:n.acroField,W,t,A);var O={x:0+y/2,y:0+y/2,width:w-y,height:S-y,borderWidth:y??0,borderColor:C,textColor:W,font:t.name,fontSize:A,color:T,textLines:F,padding:D};return fr(_,Hq(O))},vce=function(n,e,t){var r,i,o,a=Wd(e),l=Wd(n.acroField),d=Lg(e),c=Lg(n.acroField),u=e.getRectangle(),f=e.getAppearanceCharacteristics(),p=e.getBorderStyle(),g=(r=n.getSelected()[0])!==null&&r!==void 0?r:"",m=(i=p==null?void 0:p.getWidth())!==null&&i!==void 0?i:0,y=If(f==null?void 0:f.getRotation()),v=z0(u,y),x=v.width,w=v.height,S=Kg(wn(wn({},u),{rotation:y})),_=zr(0,0,0),b=Aa(f==null?void 0:f.getBorderColor()),C=Aa(f==null?void 0:f.getBackgroundColor()),T=1,F={x:m+T,y:m+T,width:x-(m+T)*2,height:w-(m+T)*2},A=hT(g,{alignment:Os.Left,fontSize:d??c,font:t,bounds:F}),D=A.line,P=A.fontSize,L=(o=a??l)!==null&&o!==void 0?o:_;Ud(a||d!==void 0?e:n.acroField,L,t,P);var W={x:0+m/2,y:0+m/2,width:x-m,height:w-m,borderWidth:m??0,borderColor:b,textColor:L,font:t.name,fontSize:P,color:C,textLines:[D],padding:T};return fr(S,Hq(W))},wce=function(n,e,t){var r,i,o=Wd(e),a=Wd(n.acroField),l=Lg(e),d=Lg(n.acroField),c=e.getRectangle(),u=e.getAppearanceCharacteristics(),f=e.getBorderStyle(),p=(r=f==null?void 0:f.getWidth())!==null&&r!==void 0?r:0,g=If(u==null?void 0:u.getRotation()),m=z0(c,g),y=m.width,v=m.height,x=Kg(wn(wn({},c),{rotation:g})),w=zr(0,0,0),S=Aa(u==null?void 0:u.getBorderColor()),_=Aa(u==null?void 0:u.getBackgroundColor()),b=n.getOptions(),C=n.getSelected();n.isSorted()&&b.sort();for(var T="",F=0,A=b.length;F1||i.length===1&&r)&&this.enableMultiselect();for(var l=new Array(i.length),d=0,c=i.length;d1||i.length===1&&r)&&this.enableMultiselect();for(var a=new Array(i.length),l=0,d=i.length;lr)throw new lce(t.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),t?this.acroField.setValue(dn.fromText(t)):this.acroField.removeValue()},e.prototype.getAlignment=function(){var t=this.acroField.getQuadding();return t===0?Os.Left:t===1?Os.Center:t===2?Os.Right:Os.Left},e.prototype.setAlignment=function(t){yg(t,"alignment",Os),this.markAsDirty(),this.acroField.setQuadding(t)},e.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},e.prototype.setMaxLength=function(t){if(nc(t,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),t===void 0)this.acroField.removeMaxLength();else{var r=this.getText();if(r&&r.length>t)throw new dce(r.length,t,this.getName());this.acroField.setMaxLength(t)}},e.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},e.prototype.setImage=function(t){for(var r=this.getAlignment(),i=r===Os.Center?Pg.Center:r===Os.Right?Pg.Right:Pg.Left,o=this.acroField.getWidgets(),a=0,l=o.length;anew Promise((e,t)=>{const r=new FileReader;r.addEventListener("load",({target:{result:i}})=>{const o=new DataView(i);let a=0;if(o.getUint16(a)!==65496)return t("not a valid JPEG");for(a+=2;;){const l=o.getUint16(a);if(l===65498)break;const d=o.getUint16(a+2);if(l===65505&&o.getUint32(a+4)===1165519206){const c=a+10;let u;switch(o.getUint16(c)){case 18761:u=!0;break;case 19789:u=!1;break;default:return t("TIFF header contains invalid endian")}if(o.getUint16(c+2,u)!==42)return t("TIFF header contains invalid version");const f=o.getUint32(c+4,u),p=c+f+2+12*o.getUint16(c+f,u);for(let g=c+f+2;g>>24&255,l[a+1]=d>>>16&255,l[a+2]=d>>>8&255,l[a+3]=d>>>0&255,new Uint8Array(l.buffer,0,a+4)},r.deflateRaw=function(i,o){o==null&&(o={level:6});var a=new Uint8Array(50+Math.floor(1.1*i.length)),l=r.F.deflateRaw(i,a,l,o.level);return new Uint8Array(a.buffer,0,l)},r.encode=function(i,o){o==null&&(o=!1);var a=0,l=r.bin.writeUint,d=r.bin.writeUshort,c={};for(var u in i){var f=!r._noNeed(u)&&!o,p=i[u],g=r.crc.crc(p,0,p.length);c[u]={cpr:f,usize:p.length,crc:g,file:f?r.deflateRaw(p):p}}for(var u in c)a+=c[u].file.length+30+46+2*r.bin.sizeUTF8(u);a+=22;var m=new Uint8Array(a),y=0,v=[];for(var u in c){var x=c[u];v.push(y),y=r._writeHeader(m,y,u,x,0)}var w=0,S=y;for(var u in c)x=c[u],v.push(y),y=r._writeHeader(m,y,u,x,1,v[w++]);var _=y-S;return l(m,y,101010256),y+=4,d(m,y+=4,w),d(m,y+=2,w),l(m,y+=2,_),l(m,y+=4,S),y+=4,y+=2,m.buffer},r._noNeed=function(i){var o=i.split(".").pop().toLowerCase();return"png,jpg,jpeg,zip".indexOf(o)!=-1},r._writeHeader=function(i,o,a,l,d,c){var u=r.bin.writeUint,f=r.bin.writeUshort,p=l.file;return u(i,o,d==0?67324752:33639248),o+=4,d==1&&(o+=2),f(i,o,20),f(i,o+=2,0),f(i,o+=2,l.cpr?8:0),u(i,o+=2,0),u(i,o+=4,l.crc),u(i,o+=4,p.length),u(i,o+=4,l.usize),f(i,o+=4,r.bin.sizeUTF8(a)),f(i,o+=2,0),o+=2,d==1&&(o+=2,o+=2,u(i,o+=6,c),o+=4),o+=r.bin.writeUTF8(i,o,a),d==0&&(i.set(p,o),o+=p.length),o},r.crc={table:function(){for(var i=new Uint32Array(256),o=0;o<256;o++){for(var a=o,l=0;l<8;l++)1&a?a=3988292384^a>>>1:a>>>=1;i[o]=a}return i}(),update:function(i,o,a,l){for(var d=0;d>>8;return i},crc:function(i,o,a){return 4294967295^r.crc.update(4294967295,i,o,a)}},r.adler=function(i,o,a){for(var l=1,d=0,c=o,u=o+a;c>8&255},readUint:function(i,o){return 16777216*i[o+3]+(i[o+2]<<16|i[o+1]<<8|i[o])},writeUint:function(i,o,a){i[o]=255&a,i[o+1]=a>>8&255,i[o+2]=a>>16&255,i[o+3]=a>>24&255},readASCII:function(i,o,a){for(var l="",d=0;d>6,i[o+d+1]=128|u>>0&63,d+=2;else if(!(4294901760&u))i[o+d]=224|u>>12,i[o+d+1]=128|u>>6&63,i[o+d+2]=128|u>>0&63,d+=3;else{if(4292870144&u)throw"e";i[o+d]=240|u>>18,i[o+d+1]=128|u>>12&63,i[o+d+2]=128|u>>6&63,i[o+d+3]=128|u>>0&63,d+=4}}return d},sizeUTF8:function(i){for(var o=i.length,a=0,l=0;l>>3}var v=c.lits,x=c.strt,w=c.prev,S=0,_=0,b=0,C=0,T=0,F=0;for(y>2&&(x[F=r.F._hash(i,0)]=0),p=0;p14e3||_>26697)&&y-p>100&&(m>>16,L=65535&D;if(D!=0){L=65535&D;var W=u(P=D>>>16,c.of0);c.lhst[257+W]++;var O=u(L,c.df0);c.dhst[O]++,C+=c.exb[W]+c.dxb[O],v[S]=P<<23|p-m,v[S+1]=L<<16|W<<8|O,S+=2,m=p+P}else c.lhst[i[p]]++;_++}}for(b==p&&i.length!=0||(m>>3},r.F._bestMatch=function(i,o,a,l,d,c){var u=32767&o,f=a[u],p=u-f+32768&32767;if(f==u||l!=r.F._hash(i,o-p))return 0;for(var g=0,m=0,y=Math.min(32767,o);p<=y&&--c!=0&&f!=u;){if(g==0||i[o+g]==i[o+g-p]){var v=r.F._howLong(i,o,p);if(v>g){if(m=p,(g=v)>=d)break;p+2x&&(x=_,f=S)}}}p+=(u=f)-(f=a[u])+32768&32767}return g<<16|m},r.F._howLong=function(i,o,a){if(i[o]!=i[o-a]||i[o+1]!=i[o+1-a]||i[o+2]!=i[o+2-a])return 0;var l=o,d=Math.min(i.length,o+258);for(o+=3;o>>23,te=I+(8388607&z);I>16,J=re>>8&255,ne=255&re;F(f,p=r.F._writeLit(257+J,O,f,p),G-C.of0[J]),p+=C.exb[J],T(f,p=r.F._writeLit(ne,U,f,p),me-C.df0[ne]),p+=C.dxb[ne],I+=G}}p=r.F._writeLit(256,O,f,p)}return p},r.F._copyExact=function(i,o,a,l,d){var c=d>>>3;return l[c]=a,l[c+1]=a>>>8,l[c+2]=255-l[c],l[c+3]=255-l[c+1],c+=4,l.set(new Uint8Array(i.buffer,o,a),c),d+(a+4<<3)},r.F.getTrees=function(){for(var i=r.F.U,o=r.F._hufTree(i.lhst,i.ltree,15),a=r.F._hufTree(i.dhst,i.dtree,15),l=[],d=r.F._lenCodes(i.ltree,l),c=[],u=r.F._lenCodes(i.dtree,c),f=0;f4&&i.itree[1+(i.ordr[g-1]<<1)]==0;)g--;return[o,a,p,d,u,g,l,c]},r.F.getSecond=function(i){for(var o=[],a=0;a>1)+",");return o},r.F.contSize=function(i,o){for(var a=0,l=0;l15&&(r.F._putsE(a,l,u,f),l+=f)}return l},r.F._lenCodes=function(i,o){for(var a=i.length;a!=2&&i[a-1]==0;)a-=2;for(var l=0;l>>1,138))<11?o.push(17,g-3):o.push(18,g-11),l+=2*g-2}else if(d==f&&c==d&&u==d){for(p=l+5;p+2>>1,6);o.push(16,g-3),l+=2*g-2}else o.push(d,0)}return a>>>1},r.F._hufTree=function(i,o,a){var l=[],d=i.length,c=o.length,u=0;for(u=0;ua&&(r.F.restrictDepth(p,a,S),S=a),u=0;uo;l++){var u=i[l].d;i[l].d=o,c+=d-(1<>>=a-o;c>0;)(u=i[l].d)=0;l--)i[l].d==o&&c<0&&(i[l].d--,c++);c!=0&&console.log("debt left")},r.F._goodIndex=function(i,o){var a=0;return o[16|a]<=i&&(a|=16),o[8|a]<=i&&(a|=8),o[4|a]<=i&&(a|=4),o[2|a]<=i&&(a|=2),o[1|a]<=i&&(a|=1),a},r.F._writeLit=function(i,o,a,l){return r.F._putsF(a,l,o[i<<1]),l+o[1+(i<<1)]},r.F.inflate=function(i,o){var a=Uint8Array;if(i[0]==3&&i[1]==0)return o||new a(0);var l=r.F,d=l._bitsF,c=l._bitsE,u=l._decodeTiny,f=l.makeCodes,p=l.codes2map,g=l._get17,m=l.U,y=o==null;y&&(o=new a(i.length>>>2<<3));for(var v,x,w=0,S=0,_=0,b=0,C=0,T=0,F=0,A=0,D=0;w==0;)if(w=d(i,D,1),S=d(i,D+1,2),D+=3,S!=0){if(y&&(o=r.F._check(o,A+(1<<17))),S==1&&(v=m.flmap,x=m.fdmap,T=511,F=31),S==2){_=c(i,D,5)+257,b=c(i,D+5,5)+1,C=c(i,D+10,4)+4,D+=14;for(var P=0;P<38;P+=2)m.itree[P]=0,m.itree[P+1]=0;var L=1;for(P=0;PL&&(L=W)}D+=3*C,f(m.itree,L),p(m.itree,L,m.imap),v=m.lmap,x=m.dmap,D=u(m.imap,(1<>>4;if(!(I>>>8))o[A++]=I;else{if(I==256)break;var H=A+I-254;if(I>264){var z=m.ldef[I-257];H=A+(z>>>3)+c(i,D,7&z),D+=7&z}var G=x[g(i,D)&F];D+=15&G;var te=G>>>4,re=m.ddef[te],me=(re>>>4)+d(i,D,15&re);for(D+=15&re,y&&(o=r.F._check(o,A+(1<<17)));A>>3),ne=i[J-4]|i[J-3]<<8;y&&(o=r.F._check(o,A+ne)),o.set(new a(i.buffer,i.byteOffset+J,ne),A),D=J+ne<<3,A+=ne}return o.length==A?o:o.slice(0,A)},r.F._check=function(i,o){var a=i.length;if(o<=a)return i;var l=new Uint8Array(Math.max(a<<1,o));return l.set(i,0),l},r.F._decodeTiny=function(i,o,a,l,d,c){for(var u=r.F._bitsE,f=r.F._get17,p=0;p>>4;if(m<=15)c[p]=m,p++;else{var y=0,v=0;m==16?(v=3+u(l,d,2),d+=2,y=c[p-1]):m==17?(v=3+u(l,d,3),d+=3):m==18&&(v=11+u(l,d,7),d+=7);for(var x=p+v;p>>1;cd&&(d=f),c++}for(;c>1,f=i[c+1],p=u<<4|f,g=o-f,m=i[c]<>>15-o]=p,m++},r.F.revCodes=function(i,o){for(var a=r.F.U.rev15,l=15-o,d=0;d>>l}},r.F._putsE=function(i,o,a){a<<=7&o;var l=o>>>3;i[l]|=a,i[l+1]|=a>>>8},r.F._putsF=function(i,o,a){a<<=7&o;var l=o>>>3;i[l]|=a,i[l+1]|=a>>>8,i[l+2]|=a>>>16},r.F._bitsE=function(i,o,a){return(i[o>>>3]|i[1+(o>>>3)]<<8)>>>(7&o)&(1<>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16)>>>(7&o)&(1<>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16)>>>(7&o)},r.F._get25=function(i,o){return(i[o>>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16|i[3+(o>>>3)]<<24)>>>(7&o)},r.F.U=(e=Uint16Array,t=Uint32Array,{next_code:new e(16),bl_count:new e(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new e(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new t(32),flmap:new e(512),fltree:[],fdmap:new e(32),fdtree:[],lmap:new e(32768),ltree:[],ttree:[],dmap:new e(32768),dtree:[],imap:new e(512),itree:[],rev15:new e(32768),lhst:new t(286),dhst:new t(30),ihst:new t(19),lits:new t(15e3),strt:new e(65536),prev:new e(32768)}),function(){for(var i=r.F.U,o=0;o<32768;o++){var a=o;a=(4278255360&(a=(4042322160&(a=(3435973836&(a=(2863311530&a)>>>1|(1431655765&a)<<1))>>>2|(858993459&a)<<2))>>>4|(252645135&a)<<4))>>>8|(16711935&a)<<8,i.rev15[o]=(a>>>16|a<<16)>>>17}function l(d,c,u){for(;c--!=0;)d.push(0,u)}for(o=0;o<32;o++)i.ldef[o]=i.of0[o]<<3|i.exb[o],i.ddef[o]=i.df0[o]<<4|i.dxb[o];l(i.fltree,144,8),l(i.fltree,112,9),l(i.fltree,24,7),l(i.fltree,8,8),r.F.makeCodes(i.fltree,9),r.F.codes2map(i.fltree,9,i.flmap),r.F.revCodes(i.fltree,9),l(i.fdtree,32,5),r.F.makeCodes(i.fdtree,5),r.F.codes2map(i.fdtree,5,i.fdmap),r.F.revCodes(i.fdtree,5),l(i.itree,19,0),l(i.ltree,286,0),l(i.dtree,30,0),l(i.ttree,320,0)}()})();var Ece=Tce({__proto__:null,default:pT},[pT]);const rc=function(){var n={nextZero(u,f){for(;u[f]!=0;)f++;return f},readUshort:(u,f)=>u[f]<<8|u[f+1],writeUshort(u,f,p){u[f]=p>>8&255,u[f+1]=255&p},readUint:(u,f)=>16777216*u[f]+(u[f+1]<<16|u[f+2]<<8|u[f+3]),writeUint(u,f,p){u[f]=p>>24&255,u[f+1]=p>>16&255,u[f+2]=p>>8&255,u[f+3]=255&p},readASCII(u,f,p){let g="";for(let m=0;mu.length<2?`0${u}`:u,readUTF8(u,f,p){let g,m="";for(let y=0;y>3)]>>7-((7&C)<<0)&1);x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O>2)]>>6-((3&C)<<1)&3),x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O>1)]>>4-((1&C)<<2)&15),x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O>>3)]>>>7-(7&I)&1))==255*F?0:255;w[G+I]=H<<24|U<<16|U<<8|U}else if(_==2)for(I=0;I>>2)]>>>6-((3&I)<<1)&3))==85*F?0:255,w[G+I]=H<<24|U<<16|U<<8|U;else if(_==4)for(I=0;I>>1)]>>>4-((1&I)<<2)&15))==17*F?0:255,w[G+I]=H<<24|U<<16|U<<8|U;else if(_==8)for(I=0;I>3,F=Math.ceil(_*C/8),A=new Uint8Array(b*F);let D=0;const P=[0,0,4,0,2,0,1],L=[0,4,0,2,0,1,0],W=[8,8,8,4,4,2,2],O=[8,8,4,4,2,2,1];let U=0;for(;U<7;){const I=W[U],H=O[U];let z=0,G=0,te=P[U];for(;te>3])>>7-(7&ke)&1,A[ne*F+(ye>>3)]|=M<<7-((7&ye)<<0)),C==2&&(M=(M=w[ke>>3])>>6-(7&ke)&3,A[ne*F+(ye>>2)]|=M<<6-((3&ye)<<1)),C==4&&(M=(M=w[ke>>3])>>4-(7&ke)&15,A[ne*F+(ye>>1)]|=M<<4-((1&ye)<<2)),C>=8){const Ye=ne*F+ye*T;for(let De=0;De>3)+De]}ke+=C,ye+=H}J++,ne+=I}z*G!=0&&(D+=G*(1+me)),U+=1}return A}(f,u)),f}function r(u,f){return i(new Uint8Array(u.buffer,2,u.length-6),f)}var i=function(){const u={H:{}};return u.H.N=function(f,p){const g=Uint8Array;let m,y,v=0,x=0,w=0,S=0,_=0,b=0,C=0,T=0,F=0;if(f[0]==3&&f[1]==0)return p||new g(0);const A=u.H,D=A.b,P=A.e,L=A.R,W=A.n,O=A.A,U=A.Z,M=A.m,I=p==null;for(I&&(p=new g(f.length>>>2<<5));v==0;)if(v=D(f,F,1),x=D(f,F+1,2),F+=3,x!=0){if(I&&(p=u.H.W(p,T+(1<<17))),x==1&&(m=M.J,y=M.h,b=511,C=31),x==2){w=P(f,F,5)+257,S=P(f,F+5,5)+1,_=P(f,F+10,4)+4,F+=14;let z=1;for(var H=0;H<38;H+=2)M.Q[H]=0,M.Q[H+1]=0;for(H=0;H<_;H++){const re=P(f,F+3*H,3);M.Q[1+(M.X[H]<<1)]=re,re>z&&(z=re)}F+=3*_,W(M.Q,z),O(M.Q,z,M.u),m=M.w,y=M.d,F=L(M.u,(1<>>4;if(!(G>>>8))p[T++]=G;else{if(G==256)break;{let te=T+G-254;if(G>264){const ye=M.q[G-257];te=T+(ye>>>3)+P(f,F,7&ye),F+=7&ye}const re=y[U(f,F)&C];F+=15&re;const me=re>>>4,J=M.c[me],ne=(J>>>4)+D(f,F,15&J);for(F+=15&J;T>>3),G=f[z-4]|f[z-3]<<8;I&&(p=u.H.W(p,T+G)),p.set(new g(f.buffer,f.byteOffset+z,G),T),F=z+G<<3,T+=G}return p.length==T?p:p.slice(0,T)},u.H.W=function(f,p){const g=f.length;if(p<=g)return f;const m=new Uint8Array(g<<1);return m.set(f,0),m},u.H.R=function(f,p,g,m,y,v){const x=u.H.e,w=u.H.Z;let S=0;for(;S>>4;if(b<=15)v[S]=b,S++;else{let C=0,T=0;b==16?(T=3+x(m,y,2),y+=2,C=v[S-1]):b==17?(T=3+x(m,y,3),y+=3):b==18&&(T=11+x(m,y,7),y+=7);const F=S+T;for(;S>>1;for(;vy&&(y=w),v++}for(;v>1,w=f[v+1],S=x<<4|w,_=p-w;let b=f[v]<<_;const C=b+(1<<_);for(;b!=C;)g[y[b]>>>15-p]=S,b++}},u.H.l=function(f,p){const g=u.H.m.r,m=15-p;for(let y=0;y>>m}},u.H.M=function(f,p,g){g<<=7&p;const m=p>>>3;f[m]|=g,f[m+1]|=g>>>8},u.H.I=function(f,p,g){g<<=7&p;const m=p>>>3;f[m]|=g,f[m+1]|=g>>>8,f[m+2]|=g>>>16},u.H.e=function(f,p,g){return(f[p>>>3]|f[1+(p>>>3)]<<8)>>>(7&p)&(1<>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16)>>>(7&p)&(1<>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16)>>>(7&p)},u.H.i=function(f,p){return(f[p>>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16|f[3+(p>>>3)]<<24)>>>(7&p)},u.H.m=function(){const f=Uint16Array,p=Uint32Array;return{K:new f(16),j:new f(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new f(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new p(32),J:new f(512),_:[],h:new f(32),$:[],w:new f(32768),C:[],v:[],d:new f(32768),D:[],u:new f(512),Q:[],r:new f(32768),s:new p(286),Y:new p(30),a:new p(19),t:new p(15e3),k:new f(65536),g:new f(32768)}}(),function(){const f=u.H.m;for(var p=0;p<32768;p++){let m=p;m=(2863311530&m)>>>1|(1431655765&m)<<1,m=(3435973836&m)>>>2|(858993459&m)<<2,m=(4042322160&m)>>>4|(252645135&m)<<4,m=(4278255360&m)>>>8|(16711935&m)<<8,f.r[p]=(m>>>16|m<<16)>>>17}function g(m,y,v){for(;y--!=0;)m.push(0,v)}for(p=0;p<32;p++)f.q[p]=f.S[p]<<3|f.T[p],f.c[p]=f.p[p]<<4|f.z[p];g(f._,144,8),g(f._,112,9),g(f._,24,7),g(f._,8,8),u.H.n(f._,9),u.H.A(f._,9,f.J),u.H.l(f._,9),g(f.$,32,5),u.H.n(f.$,5),u.H.A(f.$,5,f.h),u.H.l(f.$,5),g(f.Q,19,0),g(f.C,286,0),g(f.D,30,0),g(f.v,320,0)}(),u.H.N}();function o(u){return[1,null,3,1,2,null,4][u.ctype]*u.depth}function a(u,f,p,g,m){let y=o(f);const v=Math.ceil(g*y/8);let x,w;y=Math.ceil(y/8);let S=u[p],_=0;if(S>1&&(u[p]=[0,0,1][S-2]),S==3)for(_=y;_>>1)&255;for(let b=0;b>>1);for(;_>>1)}else{for(;_=0&&x>=0?(b=U*f+M<<2,C=(x+U)*m+v+M<<2):(b=(-x+U)*f-v+M<<2,C=U*m+M<<2),w==0)g[C]=u[b],g[C+1]=u[b+1],g[C+2]=u[b+2],g[C+3]=u[b+3];else if(w==1){var T=u[b+3]*.00392156862745098,F=u[b]*T,A=u[b+1]*T,D=u[b+2]*T,P=g[C+3]*(1/255),L=g[C]*P,W=g[C+1]*P,O=g[C+2]*P;const I=1-T,H=T+P*I,z=H==0?0:1/H;g[C+3]=255*H,g[C+0]=(F+L*I)*z,g[C+1]=(A+W*I)*z,g[C+2]=(D+O*I)*z}else if(w==2)T=u[b+3],F=u[b],A=u[b+1],D=u[b+2],P=g[C+3],L=g[C],W=g[C+1],O=g[C+2],T==P&&F==L&&A==W&&D==O?(g[C]=0,g[C+1]=0,g[C+2]=0,g[C+3]=0):(g[C]=F,g[C+1]=A,g[C+2]=D,g[C+3]=T);else if(w==3){if(T=u[b+3],F=u[b],A=u[b+1],D=u[b+2],P=g[C+3],L=g[C],W=g[C+1],O=g[C+2],T==P&&F==L&&A==W&&D==O)continue;if(T<220&&P>20)return!1}return!0}return{decode:function(f){const p=new Uint8Array(f);let g=8;const m=n,y=m.readUshort,v=m.readUint,x={tabs:{},frames:[]},w=new Uint8Array(p.length);let S,_=0,b=0;const C=[137,80,78,71,13,10,26,10];for(var T=0;T<8;T++)if(p[T]!=C[T])throw"The input is not a PNG file!";for(;g>>1:D>>>=1;F[A]=D}return F}(),update(F,A,D,P){for(let L=0;L>>8;return F},crc:(F,A,D)=>4294967295^r.update(4294967295,F,A,D)};function i(F,A,D,P){A[D]+=F[0]*P>>4,A[D+1]+=F[1]*P>>4,A[D+2]+=F[2]*P>>4,A[D+3]+=F[3]*P>>4}function o(F){return Math.max(0,Math.min(255,F))}function a(F,A){const D=F[0]-A[0],P=F[1]-A[1],L=F[2]-A[2],W=F[3]-A[3];return D*D+P*P+L*L+W*W}function l(F,A,D,P,L,W,O){O==null&&(O=1);const U=P.length,M=[];for(var I=0;I>>0&255,ne>>>8&255,ne>>>16&255,ne>>>24&255])}for(I=0;I>2]=H,te[I>>2]=P[H]}}function d(F,A,D,P,L){L==null&&(L={});const{crc:W}=r,O=e.writeUint,U=e.writeUshort,M=e.writeASCII;let I=8;const H=F.frames.length>1;let z,G=!1,te=33+(H?20:0);if(L.sRGB!=null&&(te+=13),L.pHYs!=null&&(te+=21),L.iCCP!=null&&(z=pako.deflate(L.iCCP),te+=21+z.length+4),F.ctype==3){for(var re=F.plte.length,me=0;me>>24!=255&&(G=!0);te+=8+3*re+4+(G?8+1*re+4:0)}for(var J=0;J>>8&255,ee=qe>>>16&255;ne[I+De+0]=ue,ne[I+De+1]=Ze,ne[I+De+2]=ee}if(I+=3*re,O(ne,I,W(ne,I-3*re-4,3*re+4)),I+=4,G){for(O(ne,I,re),I+=4,M(ne,I,"tRNS"),I+=4,me=0;me>>24&255;I+=re,O(ne,I,W(ne,I-re-4,re+4)),I+=4}}let ke=0;for(J=0;JAn&&(An=vt),Rton&&(on=Rt));An==-1&&(ut=Ot=An=on=0),ae&&((1&ut)==1&&ut--,(1&Ot)==1&&Ot--);const Ke=(An-ut+1)*(on-Ot+1);Ke>2,Ge>>2);De.push(qe);const ae=new Uint8Array(he.abuf,He,Ge);H&&l(ue.img,ue.rect.width,ue.rect.height,Ye,ae,qe),ue.img.set(ae),He+=Ge}}else for(re=0;reZe&&Be==Te[J-Ze])qe[J]=qe[J-Ze];else{let he=ke[Be];if(he==null&&(ke[Be]=he=Ye.length,Ye.push(Be),Ye.length>=300))break;qe[J]=he}}}const ee=Ye.length;for(ee<=256&&I==0&&(G=ee<=2?1:ee<=4?2:ee<=16?4:8,G=Math.max(G,M)),re=0;re>1)]|=Ge[K+ge]<<4-4*(1&ge);else if(G==2)for(ge=0;ge>2)]|=Ge[K+ge]<<6-2*(3&ge);else if(G==1)for(ge=0;ge>3)]|=Ge[K+ge]<<7-1*(7&ge)}Be=Z,z=3,He=1}else if(ne==0&&ye.length==1){Z=new Uint8Array(Ze*Te*3);const Ge=Ze*Te;for(J=0;JJ&&(J=De),qene&&(ne=qe))}J==-1&&(re=me=J=ne=0),O&&((1&re)==1&&re--,(1&me)==1&&me--),W={x:re,y:me,width:J-re+1,height:ne-me+1};const ye=P[L];ye.rect=W,ye.blend=1,ye.img=new Uint8Array(W.width*W.height*4),P[L-1].dispose==0?(n(I,A,D,ye.img,W.width,W.height,-W.x,-W.y,0),p(G,A,D,ye.img,W)):n(G,A,D,ye.img,W.width,W.height,-W.x,-W.y,0)}function p(F,A,D,P,L){n(F,A,D,P,L.width,L.height,-L.x,-L.y,2)}function g(F,A,D,P,L,W,O){const U=[];let M,I=[0,1,2,3,4];W!=-1?I=[W]:(A*P>5e5||D==1)&&(I=[0]),O&&(M={level:0});const H=Ece;for(var z=0;z>1)+256&255;if(W==4)for(M=L;M>1)&255;for(M=L;M>1)&255}if(W==4){for(M=0;M>2);let H;if(D.length<2e7)for(var z=0;z>2]=H.ind,L[z>>2]=H.est.rgba;else for(z=0;z>2]=H.ind,L[z>>2]=H.est.rgba}return{abuf:P.buffer,inds:I,plte:U}}function v(F,A,D){D==null&&(D=1e-4);const P=new Uint32Array(F.buffer),L={i0:0,i1:F.length,bst:null,est:null,tdst:0,left:null,right:null};L.bst=b(F,L.i0,L.i1),L.est=C(L.bst);const W=[L];for(;W.lengthU&&(U=W[O].est.L,M=O);if(U=H||I.i1<=H){I.est.L=0;continue}const z={i0:I.i0,i1:H,bst:null,est:null,tdst:0,left:null,right:null};z.bst=b(F,z.i0,z.i1),z.est=C(z.bst);const G={i0:H,i1:I.i1,bst:null,est:null,tdst:0,left:null,right:null};for(G.bst={R:[],m:[],N:I.bst.N-z.bst.N},O=0;O<16;O++)G.bst.R[O]=I.bst.R[O]-z.bst.R[O];for(O=0;O<4;O++)G.bst.m[O]=I.bst.m[O]-z.bst.m[O];G.est=C(G.bst),I.left=z,I.right=G,W[M]=z,W.push(G)}for(W.sort((U,M)=>M.bst.N-U.bst.N),O=0;O0&&(O=F.right,U=F.left);const M=x(O,A,D,P,L);if(M.tdst<=W*W)return M;const I=x(U,A,D,P,L);return I.tdstW;)P-=4;if(D>=P)break;const O=A[D>>2];A[D>>2]=A[P>>2],A[P>>2]=O,D+=4,P-=4}for(;_(F,D,L)>W;)D-=4;return D+4}function _(F,A,D){return F[A]*D[0]+F[A+1]*D[1]+F[A+2]*D[2]+F[A+3]*D[3]}function b(F,A,D){const P=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],L=[0,0,0,0],W=D-A>>2;for(let O=A;O>>0}}var T={multVec:(F,A)=>[F[0]*A[0]+F[1]*A[1]+F[2]*A[2]+F[3]*A[3],F[4]*A[0]+F[5]*A[1]+F[6]*A[2]+F[7]*A[3],F[8]*A[0]+F[9]*A[1]+F[10]*A[2]+F[11]*A[3],F[12]*A[0]+F[13]*A[1]+F[14]*A[2]+F[15]*A[3]],dot:(F,A)=>F[0]*A[0]+F[1]*A[1]+F[2]*A[2]+F[3]*A[3],sml:(F,A)=>[F*A[0],F*A[1],F*A[2],F*A[3]]};rc.encode=function(A,D,P,L,W,O,U){L==null&&(L=0),U==null&&(U=!1);const M=u(A,D,P,L,[!1,!1,!1,0,U,!1]);return c(M,-1),d(M,D,P,W,O)},rc.encodeLL=function(A,D,P,L,W,O,U,M){const I={ctype:0+(L==1?0:2)+(W==0?0:4),depth:O,frames:[]},H=(L+W)*O,z=H*D;for(let G=0;G>>0),b(1),b(32),C(3),C(d),C(2835),C(2835),T(8),C(16711680),C(65280),C(255),C(4278190080),C(1466527264),function F(){for(;w0;){for(v=122+w*l,g=0;g>>24,f.setUint32(v+g,m<<8|y),g+=4;w++}_{e(new Blob([t],{type:"image/bmp"}))})},_dly:9};var $a={CHROME:"CHROME",FIREFOX:"FIREFOX",DESKTOP_SAFARI:"DESKTOP_SAFARI",IE:"IE",IOS:"IOS",ETC:"ETC"},Pce={[$a.CHROME]:16384,[$a.FIREFOX]:11180,[$a.DESKTOP_SAFARI]:16384,[$a.IE]:8192,[$a.IOS]:4096,[$a.ETC]:8192};const A3=typeof window<"u",Zq=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,gT=A3&&window.cordova&&window.cordova.require&&window.cordova.require("cordova/modulemapper"),Rce=(A3||Zq)&&(gT&&gT.getOriginalSymbol(window,"File")||typeof File<"u"&&File),Jq=(A3||Zq)&&(gT&&gT.getOriginalSymbol(window,"FileReader")||typeof FileReader<"u"&&FileReader);function T3(n,e,t=Date.now()){return new Promise(r=>{const i=n.split(","),o=i[0].match(/:(.*?);/)[1],a=globalThis.atob(i[1]);let l=a.length;const d=new Uint8Array(l);for(;l--;)d[l]=a.charCodeAt(l);const c=new Blob([d],{type:o});c.name=e,c.lastModified=t,r(c)})}function eV(n){return new Promise((e,t)=>{const r=new Jq;r.onload=()=>e(r.result),r.onerror=i=>t(i),r.readAsDataURL(n)})}function tV(n){return new Promise((e,t)=>{const r=new Image;r.onload=()=>e(r),r.onerror=i=>t(i),r.src=n})}function km(){if(km.cachedResult!==void 0)return km.cachedResult;let n=$a.ETC;const{userAgent:e}=navigator;return/Chrom(e|ium)/i.test(e)?n=$a.CHROME:/iP(ad|od|hone)/i.test(e)&&/WebKit/i.test(e)?n=$a.IOS:/Safari/i.test(e)?n=$a.DESKTOP_SAFARI:/Firefox/i.test(e)?n=$a.FIREFOX:(/MSIE/i.test(e)||document.documentMode)&&(n=$a.IE),km.cachedResult=n,km.cachedResult}function nV(n,e){const t=km(),r=Pce[t];let i=n,o=e,a=i*o;const l=i>o?o/i:i/o;for(;a>r*r;){const d=(r+i)/2,c=(r+o)/2;d$q.toBlob(n,u)).then((function(u){try{return l=u,l.name=t,l.lastModified=r,c.call(this)}catch(f){return a(f)}}).bind(this),a);{let u=function(){return c.call(this)};if(typeof OffscreenCanvas=="function"&&n instanceof OffscreenCanvas)return n.convertToBlob({type:e,quality:i}).then((function(f){try{return l=f,l.name=t,l.lastModified=r,u.call(this)}catch(p){return a(p)}}).bind(this),a);{let f;return f=n.toDataURL(e,i),T3(f,t,r).then((function(p){try{return l=p,u.call(this)}catch(g){return a(g)}}).bind(this),a)}}}function d(){return o(l)}})}function _u(n){n.width=0,n.height=0}function Xx(){return new Promise(function(n,e){let t,r,i,o;return Xx.cachedResult!==void 0?n(Xx.cachedResult):T3("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAEAAgMBEQACEQEDEQH/xABKAAEAAAAAAAAAAAAAAAAAAAALEAEAAAAAAAAAAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAAAAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/8H//2Q==","test.jpg",Date.now()).then(function(a){try{return t=a,mT(t).then(function(l){try{return r=l[1],yT(r,t.type,t.name,t.lastModified).then(function(d){try{return i=d,_u(r),mT(i).then(function(c){try{return o=c[0],Xx.cachedResult=o.width===1&&o.height===2,n(Xx.cachedResult)}catch(u){return e(u)}},e)}catch(c){return e(c)}},e)}catch(d){return e(d)}},e)}catch(l){return e(l)}},e)})}function iV(n){return new Promise((e,t)=>{const r=new Jq;r.onload=i=>{const o=new DataView(i.target.result);if(o.getUint16(0,!1)!=65496)return e(-2);const a=o.byteLength;let l=2;for(;lt(i),r.readAsArrayBuffer(n)})}function sV(n,e){const{width:t}=n,{height:r}=n,{maxWidthOrHeight:i}=e;let o,a=n;return isFinite(i)&&(t>i||r>i)&&([a,o]=JF(t,r),t>r?(a.width=i,a.height=r/t*i):(a.width=t/r*i,a.height=i),o.drawImage(n,0,0,a.width,a.height),_u(n)),a}function oV(n,e){const{width:t}=n,{height:r}=n,[i,o]=JF(t,r);switch(e>4&&e<9?(i.width=r,i.height=t):(i.width=t,i.height=r),e){case 2:o.transform(-1,0,0,1,t,0);break;case 3:o.transform(-1,0,0,-1,t,r);break;case 4:o.transform(1,0,0,-1,0,r);break;case 5:o.transform(0,1,1,0,0,0);break;case 6:o.transform(0,1,-1,0,r,0);break;case 7:o.transform(0,-1,-1,0,r,t);break;case 8:o.transform(0,-1,1,0,0,t)}return o.drawImage(n,0,0,t,r),_u(n),i}function oN(n,e,t=0){return new Promise(function(r,i){let o,a,l,d,c,u,f,p,g,m,y,v,x,w,S,_,b,C,T,F;function A(P=5){if(e.signal&&e.signal.aborted)throw e.signal.reason;o+=P,e.onProgress(Math.min(o,100))}function D(P){if(e.signal&&e.signal.aborted)throw e.signal.reason;o=Math.min(Math.max(P,o),100),e.onProgress(o)}return o=t,a=e.maxIteration||10,l=1024*e.maxSizeMB*1024,A(),mT(n,e).then((function(P){try{return[,d]=P,A(),c=sV(d,e),A(),new Promise(function(L,W){var O;if(!(O=e.exifOrientation))return iV(n).then((function(M){try{return O=M,U.call(this)}catch(I){return W(I)}}).bind(this),W);function U(){return L(O)}return U.call(this)}).then((function(L){try{return u=L,A(),Xx().then((function(W){try{return f=W?c:oV(c,u),A(),p=e.initialQuality||1,g=e.fileType||n.type,yT(f,g,n.name,n.lastModified,p).then((function(O){try{{let M=function(){if(a--&&(S>l||S>x)){let H,z;return H=F?.95*T.width:T.width,z=F?.95*T.height:T.height,[b,C]=JF(H,z),C.drawImage(T,0,0,H,z),p*=g==="image/png"?.85:.95,yT(b,g,n.name,n.lastModified,p).then(function(G){try{return _=G,_u(T),T=b,S=_.size,D(Math.min(99,Math.floor((w-S)/(w-l)*100))),M}catch(te){return i(te)}},i)}return[1]},I=function(){return _u(T),_u(b),_u(c),_u(f),_u(d),D(100),r(_)};if(m=O,A(),y=m.size>l,v=m.size>n.size,!y&&!v)return D(100),r(m);var U;return x=n.size,w=m.size,S=w,T=f,F=!e.alwaysKeepResolution&&y,(U=(function(H){for(;H;){if(H.then)return void H.then(U,i);try{if(H.pop){if(H.length)return H.pop()?I.call(this):H;H=M}else H=H.call(this)}catch(z){return i(z)}}}).bind(this))(M)}}catch(M){return i(M)}}).bind(this),i)}catch(O){return i(O)}}).bind(this),i)}catch(W){return i(W)}}).bind(this),i)}catch(L){return i(L)}}).bind(this),i)})}const Bce=` let scriptImported = false self.addEventListener('message', async (e) => { const { file, id, imageCompressionLibUrl, options } = e.data options.onProgress = (progress) => self.postMessage({ progress, id }) try { if (!scriptImported) { // console.log('[worker] importScripts', imageCompressionLibUrl) self.importScripts(imageCompressionLibUrl) scriptImported = true } // console.log('[worker] self', self) const compressedFile = await imageCompression(file, options) self.postMessage({ file: compressedFile, id }) } catch (e) { // console.error('[worker] error', e) self.postMessage({ error: e.message + '\\n' + e.stack, id }) } }) `;let zP;function Ice(n,e){return new Promise((t,r)=>{zP||(zP=function(a){const l=[];return l.push(a),URL.createObjectURL(new Blob(l))}(Bce));const i=new Worker(zP);i.addEventListener("message",function(a){if(e.signal&&e.signal.aborted)i.terminate();else if(a.data.progress===void 0){if(a.data.error)return r(new Error(a.data.error)),void i.terminate();t(a.data.file),i.terminate()}else e.onProgress(a.data.progress)}),i.addEventListener("error",r),e.signal&&e.signal.addEventListener("abort",()=>{r(e.signal.reason),i.terminate()}),i.postMessage({file:n,imageCompressionLibUrl:e.libURL,options:{...e,onProgress:void 0,signal:void 0}})})}function bo(n,e){return new Promise(function(t,r){let i,o,a,l,d,c;if(i={...e},a=0,{onProgress:l}=i,i.maxSizeMB=i.maxSizeMB||Number.POSITIVE_INFINITY,d=typeof i.useWebWorker!="boolean"||i.useWebWorker,delete i.useWebWorker,i.onProgress=g=>{a=g,typeof l=="function"&&l(a)},!(n instanceof Blob||n instanceof Rce))return r(new Error("The file given is not an instance of Blob or File"));if(!/^image/.test(n.type))return r(new Error("The file given is not an image"));if(c=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,!d||typeof Worker!="function"||c)return oN(n,i).then((function(g){try{return o=g,p.call(this)}catch(m){return r(m)}}).bind(this),r);var u=(function(){try{return p.call(this)}catch(g){return r(g)}}).bind(this),f=function(g){try{return oN(n,i).then(function(m){try{return o=m,u()}catch(y){return r(y)}},r)}catch(m){return r(m)}};try{return i.libURL=i.libURL||"https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js",Ice(n,i).then(function(g){try{return o=g,u()}catch{return f()}},f)}catch{f()}function p(){try{o.name=n.name,o.lastModified=n.lastModified}catch{}try{i.preserveExif&&n.type==="image/jpeg"&&(!i.fileType||i.fileType&&i.fileType===n.type)&&(o=Qq(n,o))}catch{}return t(o)}})}bo.getDataUrlFromFile=eV,bo.getFilefromDataUrl=T3,bo.loadImage=tV,bo.drawImageInCanvas=rV,bo.drawFileInCanvas=mT,bo.canvasToFile=yT,bo.getExifOrientation=iV,bo.handleMaxWidthOrHeight=sV,bo.followExifOrientation=oV,bo.cleanupCanvasMemory=_u,bo.isAutoOrientationInBrowser=Xx,bo.approximateBelowMaximumCanvasSizeOfBrowser=nV,bo.copyExifWithoutOrientation=Qq,bo.getBrowserName=km,bo.version="2.0.2";function Mce(){const{token:n,user:e,login:t,logout:r}=gn(),i=k.useRef(null),o=k.useRef(null),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState(""),[p,g]=k.useState(!1),[m,y]=k.useState([]),[v,x]=k.useState([]);k.useEffect(()=>{const A=document.querySelector('meta[name="viewport"]'),D=(A==null?void 0:A.getAttribute("content"))||"";return A&&A.setAttribute("content","width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"),()=>{A&&D&&A.setAttribute("content",D)}},[]);const w=async A=>{A.preventDefault(),f(""),g(!0);try{const D=await fetch("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:a,password:d})});if(!D.ok){const L=await D.json();throw new Error(L.detail||"Login failed")}const P=await D.json();t(P.access_token)}catch(D){f(D instanceof Error?D.message:"Login failed")}finally{g(!1)}};if(!n||!e)return s.jsx("div",{style:wr.container,children:s.jsxs("div",{style:wr.loginCard,children:[s.jsx("h1",{style:wr.brand,children:"Invoice Upload"}),s.jsx("p",{style:wr.subtitle,children:"Sign in to upload invoices"}),u&&s.jsx("div",{style:wr.error,children:u}),s.jsxs("form",{onSubmit:w,style:wr.form,children:[s.jsx("input",{type:"email",placeholder:"Email",value:a,onChange:A=>l(A.target.value),style:wr.input,required:!0,autoFocus:!0}),s.jsx("input",{type:"password",placeholder:"Password",value:d,onChange:A=>c(A.target.value),style:wr.input,required:!0}),s.jsx("button",{type:"submit",style:wr.loginBtn,disabled:p,children:p?"Signing in...":"Sign In"})]})]})});const S=()=>Math.random().toString(36).substr(2,9),_=async A=>{if(!A.target.files||A.target.files.length===0)return;const D=Array.from(A.target.files);for(const P of D){if(P.type==="application/pdf"){C(P);continue}if(!P.type.startsWith("image/"))continue;const L=await new Promise(W=>{const O=new FileReader;O.onload=U=>{var M;return W((M=U.target)==null?void 0:M.result)},O.readAsDataURL(P)});x(W=>[...W,{id:S(),file:P,preview:L}])}A.target.value=""},b=A=>{x(D=>D.filter(P=>P.id!==A))},C=async A=>{const D=S();y(P=>[...P,{id:D,status:"uploading"}]);try{const P=new FormData;P.append("file",A),y(W=>W.map(O=>O.id===D?{...O,status:"processing"}:O));const L=await fetch("/api/invoices/upload",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:P});if(!L.ok){const W=await L.json();throw new Error(W.detail||"Upload failed")}y(W=>W.map(O=>O.id===D?{...O,status:"complete"}:O)),setTimeout(()=>{y(W=>W.filter(O=>O.id!==D))},3e3)}catch(P){y(L=>L.map(W=>W.id===D?{...W,status:"error",error:P instanceof Error?P.message:"Upload failed"}:W))}},T=async()=>{var L;if(v.length===0)return;const A=S(),D=(L=v[0])==null?void 0:L.preview,P=v.length;y(W=>[...W,{id:A,status:"compressing",preview:D}]),x([]);try{const W=[];for(const z of v){const G=await bo(z.file,{maxSizeMB:1,maxWidthOrHeight:2e3,useWebWorker:!0,fileType:"image/jpeg",initialQuality:.85}),te=new Image,re=URL.createObjectURL(G);await new Promise(me=>{te.onload=()=>{URL.revokeObjectURL(re),me()},te.src=re}),W.push({data:await G.arrayBuffer(),width:te.width,height:te.height})}y(z=>z.map(G=>G.id===A?{...G,status:"uploading"}:G));const O=await Af.create();for(const{data:z,width:G,height:te}of W){const re=await O.embedJpg(z);O.addPage([G,te]).drawImage(re,{x:0,y:0,width:G,height:te})}const U=await O.save(),M=new File([new Blob([U],{type:"application/pdf"})],`invoice-${P}pages.pdf`,{type:"application/pdf"});y(z=>z.map(G=>G.id===A?{...G,status:"processing"}:G));const I=new FormData;I.append("file",M);const H=await fetch("/api/invoices/upload",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:I});if(!H.ok){const z=await H.json();throw new Error(z.detail||"Upload failed")}y(z=>z.map(G=>G.id===A?{...G,status:"complete"}:G)),setTimeout(()=>{y(z=>z.filter(G=>G.id!==A))},3e3)}catch(W){y(O=>O.map(U=>U.id===A?{...U,status:"error",error:W instanceof Error?W.message:"Failed"}:U))}},F=m.some(A=>A.status==="compressing"||A.status==="uploading"||A.status==="processing");return s.jsx("div",{style:wr.container,children:s.jsxs("div",{style:wr.app,children:[s.jsxs("div",{style:wr.header,children:[s.jsxs("div",{children:[s.jsx("div",{style:wr.brandSmall,children:"Invoice Upload"}),s.jsx("div",{style:wr.kitchenName,children:e.kitchen_name})]}),s.jsx("button",{onClick:r,style:wr.logoutBtn,children:"Sign Out"})]}),m.length>0&&s.jsx("div",{style:wr.queueArea,children:m.map(A=>s.jsxs("div",{style:{...wr.queueItem,borderLeftColor:A.status==="complete"?"#4caf50":A.status==="error"?"#f44336":"#2196f3"},children:[s.jsxs("span",{style:wr.queueText,children:[A.status==="compressing"&&"Compressing...",A.status==="uploading"&&"Uploading...",A.status==="processing"&&"Processing OCR...",A.status==="complete"&&"Uploaded successfully",A.status==="error"&&(A.error||"Upload failed")]}),(A.status==="compressing"||A.status==="uploading"||A.status==="processing")&&s.jsx("div",{style:wr.spinner})]},A.id))}),v.length===0?s.jsxs("div",{style:wr.captureArea,children:[s.jsxs("button",{onClick:()=>{var A;return(A=i.current)==null?void 0:A.click()},style:wr.cameraBtn,disabled:F,children:[s.jsx("span",{style:wr.cameraIcon,children:"📷"}),s.jsx("span",{children:"Take Photo"})]}),s.jsx("button",{onClick:()=>{var A;return(A=o.current)==null?void 0:A.click()},style:wr.fileBtn,disabled:F,children:"Choose File / PDF"}),s.jsx("input",{ref:i,type:"file",accept:"image/*",capture:"environment",onChange:_,style:{display:"none"}}),s.jsx("input",{ref:o,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:_,style:{display:"none"}})]}):s.jsxs("div",{style:wr.reviewArea,children:[s.jsxs("div",{style:wr.previewGrid,children:[v.map((A,D)=>s.jsxs("div",{style:wr.previewCard,children:[s.jsx("img",{src:A.preview,alt:`Page ${D+1}`,style:wr.previewImg}),s.jsx("button",{onClick:()=>b(A.id),style:wr.removeBtn,disabled:F,children:"×"}),s.jsxs("div",{style:wr.pageLabel,children:["Page ",D+1]})]},A.id)),s.jsxs("button",{onClick:()=>{var A;return(A=i.current)==null?void 0:A.click()},style:wr.addPageCard,disabled:F,children:[s.jsx("span",{style:{fontSize:"2.5rem"},children:"📷"}),s.jsx("span",{style:{fontSize:"0.8rem",fontWeight:500},children:"Add Page"})]})]}),s.jsx("div",{style:wr.actionBar,children:s.jsx("button",{onClick:()=>x([]),style:wr.clearBtn,disabled:F,children:"Clear All"})}),s.jsx("button",{onClick:T,style:{...wr.uploadBtn,...F?{opacity:.6,cursor:"wait"}:{}},disabled:F,children:F?"Processing...":`Upload ${v.length} Page${v.length!==1?"s":""}`}),s.jsx("input",{ref:i,type:"file",accept:"image/*",capture:"environment",onChange:_,style:{display:"none"}}),s.jsx("input",{ref:o,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:_,style:{display:"none"}})]})]})})}const wr={container:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"#1a1a2e",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"},app:{width:"100%",maxWidth:"500px",height:"100%",display:"flex",flexDirection:"column",background:"#16213e",overflow:"auto"},loginCard:{background:"white",padding:"2rem",borderRadius:"12px",width:"90%",maxWidth:"360px",textAlign:"center"},brand:{color:"#1a1a2e",marginBottom:"0.25rem",fontSize:"1.4rem"},subtitle:{color:"#666",marginBottom:"1.5rem",fontSize:"0.9rem"},error:{background:"#fee",color:"#c00",padding:"0.6rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.85rem"},form:{display:"flex",flexDirection:"column",gap:"0.75rem"},input:{padding:"0.75rem 1rem",borderRadius:"8px",border:"1px solid #ddd",fontSize:"1rem",outline:"none"},loginBtn:{padding:"0.75rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:"bold",cursor:"pointer"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#1a1a2e",borderBottom:"1px solid rgba(255,255,255,0.1)"},brandSmall:{color:"white",fontWeight:"bold",fontSize:"1rem"},kitchenName:{color:"rgba(255,255,255,0.5)",fontSize:"0.75rem"},logoutBtn:{padding:"0.4rem 0.75rem",background:"rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.7)",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"6px",fontSize:"0.8rem",cursor:"pointer"},queueArea:{padding:"0.5rem 1rem",display:"flex",flexDirection:"column",gap:"0.4rem"},queueItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.6rem 0.75rem",background:"rgba(255,255,255,0.05)",borderRadius:"8px",borderLeft:"3px solid #2196f3"},queueText:{color:"rgba(255,255,255,0.8)",fontSize:"0.85rem"},spinner:{width:"16px",height:"16px",border:"2px solid rgba(255,255,255,0.2)",borderTopColor:"white",borderRadius:"50%",animation:"spin 1s linear infinite"},captureArea:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"1.5rem",padding:"2rem"},cameraBtn:{width:"200px",height:"200px",borderRadius:"50%",background:"#e94560",border:"none",color:"white",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"0.5rem",cursor:"pointer",fontSize:"1.2rem",fontWeight:"bold",boxShadow:"0 8px 32px rgba(233,69,96,0.4)"},cameraIcon:{fontSize:"3rem"},fileBtn:{padding:"0.75rem 2rem",background:"transparent",border:"2px solid rgba(255,255,255,0.3)",borderRadius:"8px",color:"rgba(255,255,255,0.7)",fontSize:"1rem",cursor:"pointer"},reviewArea:{flex:1,display:"flex",flexDirection:"column",padding:"1rem",gap:"1rem",overflow:"auto"},previewGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:"0.75rem",alignContent:"start"},previewCard:{position:"relative",borderRadius:"8px",overflow:"hidden",background:"#0f0f23",height:"180px"},previewImg:{width:"100%",height:"100%",objectFit:"cover",display:"block"},addPageCard:{height:"180px",borderRadius:"8px",border:"2px dashed rgba(255,255,255,0.25)",background:"rgba(255,255,255,0.05)",color:"rgba(255,255,255,0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"0.5rem",cursor:"pointer"},removeBtn:{position:"absolute",top:"4px",right:"4px",width:"28px",height:"28px",borderRadius:"50%",background:"rgba(0,0,0,0.6)",color:"white",border:"none",fontSize:"1.2rem",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},pageLabel:{position:"absolute",bottom:"4px",left:"4px",background:"rgba(0,0,0,0.6)",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"bold"},actionBar:{display:"flex",justifyContent:"flex-end"},clearBtn:{padding:"0.5rem 1rem",background:"transparent",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"8px",color:"rgba(255,255,255,0.5)",fontSize:"0.85rem",cursor:"pointer"},uploadBtn:{padding:"1rem",background:"#e94560",color:"white",border:"none",borderRadius:"10px",fontSize:"1.1rem",fontWeight:"bold",cursor:"pointer",boxShadow:"0 4px 16px rgba(233,69,96,0.3)"}},yx=n=>n.toISOString().split("T")[0],H2=(n,e)=>{const t=r=>{const i=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return`${i[r.getDay()]} ${r.getDate()} ${o[r.getMonth()]}`};return`${t(n)} - ${t(e)}`},zce=()=>{const n=new Date;n.setHours(0,0,0,0);const e=n.getDay(),t=e===0?6:e-1,r=new Date(n);r.setDate(n.getDate()-t);const i=new Date(n),o=new Date(r);o.setDate(r.getDate()-7);const a=new Date(r);a.setDate(r.getDate()-1);const l=new Date(n);l.setDate(n.getDate()-1);const d=new Date(l);return d.setDate(l.getDate()-29),{thisWeek:{start:r,end:i},lastWeek:{start:o,end:a},last30Days:{start:d,end:l}}};function Oce(){var x;const{token:n}=gn(),e=go(),t=zce(),{data:r}=Oe({queryKey:["resos-settings"],queryFn:async()=>{const w=await fetch("/api/resos/settings",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch Resos settings");return w.json()},enabled:!!n}),{data:i,isLoading:o,error:a}=Oe({queryKey:["dashboard"],queryFn:async()=>{const w=await fetch("/api/reports/dashboard",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch dashboard");return w.json()}}),{data:l}=Oe({queryKey:["resos-dashboard-covers"],queryFn:async()=>{const w=await fetch("/api/resos/dashboard/today-tomorrow",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch Resos covers");return await w.json()},staleTime:5*60*1e3}),{data:d}=Oe({queryKey:["newbook-arrival-stats"],queryFn:async()=>{const w=await fetch("/api/newbook/dashboard/arrivals?days=3",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch arrival stats");return w.json()},enabled:!!n,staleTime:5*60*1e3}),{data:c}=Oe({queryKey:["upcoming-events"],queryFn:async()=>{const w=await fetch("/api/calendar-events/dashboard/upcoming",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch upcoming events");return w.json()},enabled:!!n,staleTime:5*60*1e3}),{data:u}=Oe({queryKey:["recipe-dashboard-stats"],queryFn:async()=>{const w=await fetch("/api/recipes/dashboard-stats",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch recipe stats");return w.json()},enabled:!!n,staleTime:5*60*1e3}),{data:f}=Oe({queryKey:["dispute-stats"],queryFn:async()=>{const w=await fetch("/api/disputes/stats/summary",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch dispute stats");return w.json()},enabled:!!n,staleTime:5*60*1e3}),p=w=>{const S=(r==null?void 0:r.resos_flag_icon_mapping)||{},_={allergies:"🦀",large_group:"⚠️",note_keyword_birthday:"🎂",note_keyword_anniversary:"💍"};if(S[w])return S[w];if(w.startsWith("note_keyword_")){const b=w.replace("note_keyword_","");if(S[b])return S[b]}return _[w]?_[w]:"⚠️"},g=w=>{if(!w||w.length===0)return[];const S=new Set;for(const _ of w){const b=p(_);S.add(b)}return Array.from(S)},m=(w,S)=>{const _=()=>{w!=null&&w.date&&e(`/resos?date=${w.date}`)};return s.jsxs("div",{style:{...We.card,cursor:w?"pointer":"default"},onClick:_,title:w?`Click to view bookings for ${w.date}`:void 0,children:[s.jsxs("h3",{style:We.cardTitle,children:[S,(w==null?void 0:w.has_flagged_bookings)&&s.jsx("span",{style:We.flagIcon,children:g(w.unique_flag_types).map((b,C)=>s.jsx("span",{children:b},C))})]}),w&&w.total_covers>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.coverValue,children:[w.total_covers," covers"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:[w.total_bookings," bookings"]}),w.service_breakdown.map(b=>s.jsxs("span",{children:[b.period,": ",b.bookings," : ",b.covers]},b.period))]})]}):s.jsx("p",{style:We.noData,children:"No booking data"})]})};if(o)return s.jsx("div",{style:We.loading,children:"Loading dashboard..."});if(a)return s.jsx("div",{style:We.loading,children:"Error loading dashboard. Please try logging in again."});const y=i==null?void 0:i.current_period,v=i==null?void 0:i.previous_period;return s.jsxs("div",{children:[s.jsx("h2",{style:We.title,children:"Dashboard"}),s.jsx("h3",{style:We.sectionTitle,children:"Gross Profit"}),s.jsxs("div",{style:We.fourGrid,children:[s.jsxs("div",{style:{...We.card,cursor:"pointer"},onClick:()=>e(`/purchases?from=${yx(t.thisWeek.start)}&to=${yx(t.thisWeek.end)}`),title:"Click to view flash report for this period",children:[s.jsx("h3",{style:We.cardTitle,children:"This Week"}),s.jsx("div",{style:We.dateRange,children:H2(t.thisWeek.start,t.thisWeek.end)}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(y.gp_percentage).toFixed(1),"%"]}),y.gp_with_allowances!=null&&s.jsxs("div",{style:We.wastageAdjusted,children:["(",Number(y.gp_with_allowances).toFixed(1),"% with allowances)"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(y.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(y.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"No data for this period"})]}),s.jsxs("div",{style:We.card,children:[s.jsx("h3",{style:We.cardTitle,children:"This Week Forecast"}),s.jsx("div",{style:We.dateRange,children:H2(t.thisWeek.start,t.thisWeek.end)}),i!=null&&i.forecast_period?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(i.forecast_period.gp_percentage).toFixed(1),"%"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(i.forecast_period.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(i.forecast_period.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"Coming soon"})]}),s.jsxs("div",{style:{...We.card,cursor:"pointer"},onClick:()=>e(`/purchases?from=${yx(t.lastWeek.start)}&to=${yx(t.lastWeek.end)}`),title:"Click to view flash report for this period",children:[s.jsx("h3",{style:We.cardTitle,children:"Last Week"}),s.jsx("div",{style:We.dateRange,children:H2(t.lastWeek.start,t.lastWeek.end)}),v?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(v.gp_percentage).toFixed(1),"%"]}),v.gp_with_allowances!=null&&s.jsxs("div",{style:We.wastageAdjusted,children:["(",Number(v.gp_with_allowances).toFixed(1),"% with allowances)"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(v.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(v.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"No data for this period"})]}),s.jsxs("div",{style:{...We.card,cursor:"pointer"},onClick:()=>e(`/purchases?from=${yx(t.last30Days.start)}&to=${yx(t.last30Days.end)}`),title:"Click to view flash report for this period",children:[s.jsx("h3",{style:We.cardTitle,children:"Last 30 Days"}),s.jsx("div",{style:We.dateRange,children:H2(t.last30Days.start,t.last30Days.end)}),i!=null&&i.rolling_30_days?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(i.rolling_30_days.gp_percentage).toFixed(1),"%"]}),i.rolling_30_days.gp_with_allowances!=null&&s.jsxs("div",{style:We.wastageAdjusted,children:["(",Number(i.rolling_30_days.gp_with_allowances).toFixed(1),"% with allowances)"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(i.rolling_30_days.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(i.rolling_30_days.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"No data for this period"})]})]}),s.jsx("h3",{style:We.sectionTitle,children:"Documents"}),s.jsxs("div",{style:We.fourGrid,children:[s.jsxs("a",{href:"/upload",style:{...We.card,...We.uploadCard,...We.cardFlex,textDecoration:"none"},children:[s.jsx("h3",{style:We.cardTitle,children:"Upload New"}),s.jsx("div",{style:We.uploadIcon,children:"+"}),s.jsx("p",{style:We.statLabel,children:"Upload invoice"})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex,...i!=null&&i.pending_review?We.alertCard:{},cursor:((i==null?void 0:i.pending_review)||0)>0?"pointer":"default"},onClick:()=>((i==null?void 0:i.pending_review)||0)>0&&e("/invoices?status=pending_confirmation"),children:[s.jsx("h3",{style:We.cardTitle,children:"Pending Confirmation"}),s.jsx("div",{style:We.statValue,children:(i==null?void 0:i.pending_review)||0}),s.jsx("p",{style:We.statLabel,children:"Awaiting confirmation"}),s.jsx("div",{style:We.cardLinkArea,children:((i==null?void 0:i.pending_review)||0)>0&&s.jsx("span",{style:We.linkText,children:"Review now →"})})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex,...((f==null?void 0:f.open_disputes)||0)>0?We.alertCard:{},cursor:((f==null?void 0:f.open_disputes)||0)>0?"pointer":"default"},onClick:()=>((f==null?void 0:f.open_disputes)||0)>0&&e("/disputes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Disputes"}),s.jsx("div",{style:{...We.statValue,color:((f==null?void 0:f.open_disputes)||0)>0?"#e94560":"#4ade80"},children:(f==null?void 0:f.open_disputes)||0}),s.jsx("p",{style:We.statLabel,children:"Open disputes"}),f&&f.status_counts&&Object.keys(f.status_counts).length>0&&s.jsx("div",{style:We.statusBreakdown,children:Object.entries(f.status_counts).filter(([w])=>w!=="RESOLVED").filter(([,w])=>w.count>0).map(([w,S])=>s.jsxs("span",{style:We.statusBreakdownItem,children:[w.replace(/_/g," ").toLowerCase().replace(/\b\w/g,_=>_.toUpperCase()),": ",S.count]},w))}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View open →"})})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex},children:[s.jsx("h3",{style:We.cardTitle,children:"Recent Invoices"}),s.jsx("div",{style:We.statValue,children:(i==null?void 0:i.recent_invoices)||0}),s.jsx("p",{style:We.statLabel,children:"Uploaded this week"}),s.jsx("div",{style:We.cardLinkArea,children:((i==null?void 0:i.recent_invoices)||0)>0&&s.jsx("a",{href:`/invoices?status=&date_from=${new Date(Date.now()-7*24*60*60*1e3).toISOString().split("T")[0]}&date_to=${new Date().toISOString().split("T")[0]}`,style:We.linkText,children:"View all →"})})]})]}),u&&(u.total_recipes>0||u.unmapped_ingredients>0)&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:We.sectionTitle,children:"Recipes & Dishes"}),s.jsxs("div",{style:We.fourGrid,children:[s.jsxs("div",{style:{...We.card,...We.cardFlex,cursor:"pointer"},onClick:()=>e("/recipes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Recipes"}),s.jsx("div",{style:We.statValue,children:u.component_recipes}),s.jsx("p",{style:We.statLabel,children:"Component recipes"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View recipes →"})})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex,cursor:"pointer"},onClick:()=>e("/dishes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Dishes"}),s.jsx("div",{style:We.statValue,children:u.dish_count}),s.jsx("p",{style:We.statLabel,children:"Plated dishes"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View dishes →"})})]}),u.dishes_missing_allergens>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/allergens"),children:[s.jsx("h3",{style:We.cardTitle,children:"Missing Allergens"}),s.jsx("div",{style:{...We.statValue,color:"#e94560"},children:u.dishes_missing_allergens}),s.jsx("p",{style:We.statLabel,children:"Dishes with unassessed ingredients"}),u.dishes_missing_allergens_list.length>0&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#94a3b8",marginTop:"0.25rem",lineHeight:1.4},children:[u.dishes_missing_allergens_list.slice(0,3).map(w=>w.name).join(", "),u.dishes_missing_allergens_list.length>3&&` +${u.dishes_missing_allergens_list.length-3} more`]}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"Review allergens →"})})]}),u.unmapped_ingredients>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/ingredients?unmapped=true"),children:[s.jsx("h3",{style:We.cardTitle,children:"Unmapped Ingredients"}),s.jsx("div",{style:{...We.statValue,color:"#e94560"},children:u.unmapped_ingredients}),s.jsx("p",{style:We.statLabel,children:"Without supplier source"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"Map now →"})})]}),u.recipes_without_costing>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/recipes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Without Costing"}),s.jsx("div",{style:{...We.statValue,color:"#f59e0b"},children:u.recipes_without_costing}),s.jsx("p",{style:We.statLabel,children:"Recipes with no cost snapshot"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View recipes →"})})]}),u.recipes_with_price_changes>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,cursor:"pointer",borderLeft:"3px solid #f59e0b"},onClick:()=>e("/price-impact"),children:[s.jsx("h3",{style:We.cardTitle,children:"Price Changes"}),s.jsx("div",{style:{...We.statValue,color:"#f59e0b"},children:u.recipes_with_price_changes}),s.jsx("p",{style:We.statLabel,children:"Recipes affected by ingredient price changes (14 days)"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View report →"})})]}),u.stale_menu_items>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/menus"),children:[s.jsx("h3",{style:We.cardTitle,children:"Menus Need Republishing"}),s.jsx("div",{style:{...We.statValue,color:"#92400e"},children:u.stale_menu_items}),s.jsxs("p",{style:We.statLabel,children:["Dish",u.stale_menu_items!==1?"es":""," changed since last publish"]}),u.stale_menu_names.length>0&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#94a3b8",marginTop:"0.25rem",lineHeight:1.4},children:u.stale_menu_names.join(", ")}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View menus →"})})]})]})]}),s.jsx("h3",{style:We.sectionTitle,children:"Covers"}),s.jsxs("div",{style:We.fourGrid,children:[m((l==null?void 0:l.today)||null,"Today"),m((l==null?void 0:l.tomorrow)||null,"Tomorrow"),m((l==null?void 0:l.day_after)||null,((x=l==null?void 0:l.day_after)==null?void 0:x.day_label)||"Day After"),s.jsxs("div",{style:We.card,children:[s.jsx("h3",{style:We.cardTitle,children:"Upcoming Events"}),c&&c.total_count>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{style:We.gpValue,children:c.total_count}),s.jsx("div",{style:We.details,children:c.upcoming_events.map(w=>s.jsxs("span",{style:{fontSize:"0.85rem"},children:[w.event_date,": ",w.title]},w.id))}),s.jsx("a",{href:"/resos",style:We.link,children:"View Calendar →"})]}):s.jsx("p",{style:We.noData,children:"No upcoming events"})]})]}),d&&d.days&&d.days.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:We.sectionTitle,children:d.service_filter_name?`Hotel Arrivals & ${d.service_filter_name} Bookings`:"Hotel Arrivals & Restaurant Bookings"}),s.jsxs("div",{style:We.wideCard,children:[d.service_filter_name&&s.jsxs("span",{style:We.serviceFilterInfo,children:["(showing ",d.service_filter_name," tables only)"]}),s.jsx("div",{style:We.arrivalGrid,children:d.days.map(w=>s.jsxs("div",{style:We.arrivalDay,children:[s.jsx("div",{style:We.dayName,children:w.day_name}),s.jsxs("div",{style:We.arrivalStats,children:[s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:We.arrivalValue,children:w.arrival_count}),s.jsx("div",{style:We.arrivalLabel,children:"arrivals"}),s.jsxs("div",{style:We.arrivalSubtext,children:[w.arrival_guests," guests"]})]}),s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:We.arrivalValue,children:w.table_bookings}),s.jsx("div",{style:We.arrivalLabel,children:"table bookings"}),s.jsxs("div",{style:We.arrivalSubtext,children:[w.table_covers," covers"]})]}),s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:{...We.arrivalValue,color:"#4ade80"},children:w.matched_arrivals}),s.jsx("div",{style:We.arrivalLabel,children:"have booked"})]}),s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:{...We.arrivalValue,color:"#e94560"},children:w.unmatched_arrivals}),s.jsx("div",{style:We.arrivalLabel,children:"no booking yet"}),s.jsxs("div",{style:We.arrivalSubtext,children:[w.opportunity_guests," guests"]})]})]})]},w.date))})]})]})]})}const We={loading:{padding:"2rem",textAlign:"center",color:"#666"},title:{marginBottom:"1.5rem",color:"#1a1a2e"},sectionTitle:{color:"#1a1a2e",fontSize:"1rem",fontWeight:600,marginBottom:"1rem",marginTop:"0.5rem",textTransform:"uppercase",letterSpacing:"0.05em"},fourGrid:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1.5rem",marginBottom:"2rem"},card:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},uploadCard:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"transform 0.2s, box-shadow 0.2s",border:"2px dashed #e94560"},uploadIcon:{fontSize:"3rem",fontWeight:"bold",color:"#e94560",marginBottom:"0.5rem"},alertCard:{borderLeft:"4px solid #e94560"},cardTitle:{color:"#666",fontSize:"0.9rem",marginBottom:"0.25rem",textTransform:"uppercase"},dateRange:{color:"#999",fontSize:"0.75rem",marginBottom:"0.75rem"},serviceFilterInfo:{color:"#999",fontSize:"0.75rem",fontWeight:"normal",textTransform:"none",marginBottom:"1rem",display:"block"},gpValue:{fontSize:"2.5rem",fontWeight:"bold",color:"#1a1a2e"},wastageAdjusted:{fontSize:"0.9rem",color:"#888",marginTop:"-0.25rem",marginBottom:"0.25rem"},statValue:{fontSize:"2.5rem",fontWeight:"bold",color:"#1a1a2e"},coverValue:{fontSize:"2rem",fontWeight:"bold",color:"#1a1a2e"},flagIcon:{fontSize:"1.2rem",marginLeft:"0.5rem"},statLabel:{color:"#666",marginTop:"0.5rem"},details:{marginTop:"1rem",display:"flex",flexDirection:"column",gap:"0.25rem",color:"#666",fontSize:"0.9rem"},noData:{color:"#999",fontStyle:"italic"},link:{display:"inline-block",marginTop:"1rem",color:"#e94560",textDecoration:"none",fontWeight:"bold"},wideCard:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",marginBottom:"2rem"},arrivalGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))",gap:"1.5rem"},arrivalDay:{border:"1px solid #e5e7eb",borderRadius:"8px",padding:"1rem"},dayName:{fontSize:"0.875rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"0.75rem",textTransform:"uppercase"},arrivalStats:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"0.75rem"},arrivalStat:{textAlign:"center"},arrivalValue:{fontSize:"1.75rem",fontWeight:"bold",color:"#1a1a2e"},arrivalLabel:{fontSize:"0.75rem",color:"#666",marginTop:"0.25rem"},arrivalSubtext:{fontSize:"0.75rem",color:"#999",marginTop:"0.125rem"},statusBreakdown:{display:"flex",flexDirection:"column",gap:"0.25rem",marginTop:"0.5rem",marginBottom:"0.75rem"},statusBreakdownItem:{fontSize:"0.75rem",color:"#666"},cardFlex:{display:"flex",flexDirection:"column"},cardLinkArea:{marginTop:"auto",paddingTop:"0.5rem"},linkText:{color:"#e94560",textDecoration:"none",fontSize:"0.9rem",fontWeight:"bold"}};function Lce(){const{token:n}=gn(),e=go(),t=pi(),r=k.useRef(null),i=k.useRef(null),o=k.useRef(null),[a,l]=k.useState([]),[d,c]=k.useState(!1),[u,f]=k.useState(!1),[p,g]=k.useState(""),[m,y]=k.useState(""),[v,x]=k.useState([]),[w,S]=k.useState(null);k.useEffect(()=>{const H=z=>{z.preventDefault(),S(z)};return window.addEventListener("beforeinstallprompt",H),()=>window.removeEventListener("beforeinstallprompt",H)},[]);const _={maxSizeMB:1,maxWidthOrHeight:2e3,useWebWorker:!0,fileType:"image/jpeg",initialQuality:.85},b=()=>Math.random().toString(36).substr(2,9),C=async H=>{const z=Array.from(H),G=[];for(const te of z){const re=te.type.startsWith("image/"),me=te.type==="application/pdf";if(!re&&!me){g("Please upload image or PDF files only");continue}if(me){L(te);continue}const J=await new Promise(ne=>{const ye=new FileReader;ye.onload=ke=>{var Ye;return ne((Ye=ke.target)==null?void 0:Ye.result)},ye.readAsDataURL(te)});G.push({id:b(),file:te,preview:J})}G.length>0&&l(te=>[...te,...G]),g("")},T=H=>{H.preventDefault(),c(!1),H.dataTransfer.files.length>0&&C(H.dataTransfer.files)},F=H=>{H.target.files&&H.target.files.length>0&&C(H.target.files),H.target.value=""},A=H=>{l(z=>z.filter(G=>G.id!==H))},D=(H,z)=>{l(G=>{const te=G.findIndex(J=>J.id===H);if(te===-1||z==="up"&&te===0||z==="down"&&te===G.length-1)return G;const re=[...G],me=z==="up"?te-1:te+1;return[re[te],re[me]]=[re[me],re[te]],re})},P=()=>Math.random().toString(36).substr(2,9),L=async(H,z=!1)=>{const G=P(),te=H.name||"invoice.pdf";x(re=>[...re,{id:G,filename:te,status:"uploading"}]),z&&(l([]),f(!1),y(""));try{const re=new FormData;re.append("file",H),x(ne=>ne.map(ye=>ye.id===G?{...ye,status:"processing"}:ye));const me=await fetch("/api/invoices/upload",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:re});if(!me.ok){const ne=await me.json();throw new Error(ne.detail||"Upload failed")}const J=await me.json();x(ne=>ne.map(ye=>ye.id===G?{...ye,status:"complete",invoiceId:J.id}:ye)),t.invalidateQueries({queryKey:["invoices"]})}catch(re){x(me=>me.map(J=>J.id===G?{...J,status:"error",error:re instanceof Error?re.message:"Upload failed"}:J))}},W=H=>{x(z=>z.filter(G=>G.id!==H))},O=()=>{x(H=>H.filter(z=>z.status!=="complete"&&z.status!=="error"))},U=async()=>{if(a.length===0){g("Please add at least one page");return}f(!0),g("");try{y(`Compressing ${a.length} image(s)...`);const H=[];for(let me=0;me{ne.onload=()=>{URL.revokeObjectURL(ye),Ye()},ne.src=ye});const ke=await J.arrayBuffer();H.push({data:ke,width:ne.width,height:ne.height})}y("Creating PDF...");const z=await Af.create();for(let me=0;me{l([]),g(""),y("")},I=u||v.some(H=>H.status==="uploading"||H.status==="processing");return s.jsxs("div",{children:[s.jsx("h2",{style:an.title,children:"Upload Invoice"}),p&&s.jsx("div",{style:an.error,children:p}),v.length>0&&s.jsxs("div",{style:an.queueSection,children:[s.jsxs("div",{style:an.queueHeader,children:[s.jsx("h3",{style:an.queueTitle,children:"Processing Queue"}),v.some(H=>H.status==="complete"||H.status==="error")&&s.jsx("button",{onClick:O,style:an.clearQueueBtn,children:"Clear Completed"})]}),s.jsx("div",{style:an.queueList,children:v.map(H=>s.jsxs("div",{style:{...an.queueItem,...H.status==="complete"?an.queueItemComplete:{},...H.status==="error"?an.queueItemError:{}},children:[s.jsxs("div",{style:an.queueItemInfo,children:[s.jsx("span",{style:an.queueItemName,children:H.filename}),s.jsxs("span",{style:{...an.queueItemStatus,color:H.status==="complete"?"#28a745":H.status==="error"?"#dc3545":H.status==="processing"?"#0066cc":"#666"},children:[H.status==="uploading"&&"⬆️ Uploading...",H.status==="processing"&&"⏳ Processing OCR...",H.status==="complete"&&"✓ Complete",H.status==="error"&&`✗ ${H.error||"Failed"}`]})]}),s.jsxs("div",{style:an.queueItemActions,children:[H.status==="complete"&&H.invoiceId&&s.jsx("button",{onClick:()=>e(`/invoice/${H.invoiceId}`),style:an.queueViewBtn,children:"View"}),(H.status==="complete"||H.status==="error")&&s.jsx("button",{onClick:()=>W(H.id),style:an.queueRemoveBtn,children:"×"}),(H.status==="uploading"||H.status==="processing")&&s.jsx("div",{style:an.queueSpinner})]})]},H.id))})]}),a.length===0?s.jsxs("div",{style:{...an.dropzone,...d?an.dropzoneActive:{}},onDragOver:H=>{H.preventDefault(),c(!0)},onDragLeave:()=>c(!1),onDrop:T,onClick:()=>{var H;return(H=r.current)==null?void 0:H.click()},children:[s.jsxs("div",{style:an.uploadPrompt,children:[s.jsx("div",{style:an.uploadIcon,children:"📄"}),s.jsx("p",{children:"Drag and drop invoice images"}),s.jsx("p",{style:an.subtext,children:"or click to select files"}),s.jsx("p",{style:an.formats,children:"Supports: JPG, PNG, WebP, HEIC, PDF"}),s.jsx("p",{style:an.multiPageHint,children:"Add multiple images for multi-page invoices"})]}),s.jsx("input",{ref:r,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:F,style:{display:"none"}})]}):s.jsxs("div",{style:an.pagesContainer,children:[s.jsxs("div",{style:an.pagesHeader,children:[s.jsxs("h3",{children:[a.length," Page",a.length!==1?"s":""," Ready"]}),s.jsxs("div",{style:an.headerActions,children:[s.jsx("button",{onClick:()=>{var H;return(H=o.current)==null?void 0:H.click()},style:an.addMoreBtn,disabled:I,children:"+ Add More Pages"}),s.jsx("button",{onClick:M,style:an.clearBtn,disabled:I,children:"Clear All"})]}),s.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,onChange:F,style:{display:"none"}})]}),s.jsx("div",{style:an.pagesGrid,children:a.map((H,z)=>s.jsxs("div",{style:an.pageCard,children:[s.jsxs("div",{style:an.pageNumber,children:["Page ",z+1]}),s.jsx("img",{src:H.preview,alt:`Page ${z+1}`,style:an.pagePreview}),s.jsxs("div",{style:an.pageActions,children:[s.jsx("button",{onClick:()=>D(H.id,"up"),disabled:z===0||I,style:an.moveBtn,title:"Move up",children:"↑"}),s.jsx("button",{onClick:()=>D(H.id,"down"),disabled:z===a.length-1||I,style:an.moveBtn,title:"Move down",children:"↓"}),s.jsx("button",{onClick:()=>A(H.id),disabled:I,style:an.removeBtn,title:"Remove page",children:"×"})]})]},H.id))}),u&&s.jsxs("div",{style:an.processingOverlay,children:[s.jsx("div",{style:an.spinner}),s.jsx("p",{children:m||"Processing..."})]}),s.jsx("button",{onClick:U,disabled:I,style:{...an.uploadBtn,...I?an.uploadBtnDisabled:{}},children:I?m||"Processing...":`Create PDF & Upload (${a.length} page${a.length!==1?"s":""})`})]}),s.jsxs("div",{style:an.cameraSection,children:[s.jsx("p",{children:s.jsx("strong",{children:"Take photos with camera:"})}),s.jsx("p",{style:an.cameraHint,children:'For multi-page invoices, take each page separately then click "Add More Pages"'}),s.jsx("input",{ref:i,type:"file",accept:"image/*",capture:"environment",onChange:F,style:an.cameraInput})]}),s.jsx("div",{style:an.pwaSection,children:s.jsxs("div",{style:an.pwaContent,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Upload App"}),s.jsx("p",{style:an.pwaHint,children:"Install the upload app for quick camera access on mobile"})]}),w?s.jsx("button",{onClick:async()=>{w.prompt();const{outcome:H}=await w.userChoice;H==="accepted"&&S(null)},style:an.installBtn,children:"Install App"}):s.jsx("a",{href:"/upload-app",style:an.openAppLink,children:"Open Upload App"})]})}),s.jsxs("div",{style:an.infoSection,children:[s.jsx("h4",{children:"How it works:"}),s.jsxs("ol",{style:an.infoList,children:[s.jsx("li",{children:"Add one or more invoice page images"}),s.jsx("li",{children:"Reorder pages if needed using the arrows"}),s.jsx("li",{children:'Click "Create PDF & Upload" to combine and process'}),s.jsx("li",{children:"Images are compressed to save space while maintaining OCR quality"})]})]})]})}const an={title:{marginBottom:"1.5rem",color:"#1a1a2e"},error:{background:"#fee",color:"#c00",padding:"1rem",borderRadius:"8px",marginBottom:"1rem"},dropzone:{background:"white",border:"3px dashed #ddd",borderRadius:"12px",padding:"3rem",textAlign:"center",cursor:"pointer",transition:"all 0.2s",minHeight:"300px",display:"flex",alignItems:"center",justifyContent:"center"},dropzoneActive:{borderColor:"#e94560",background:"#fff5f7"},uploadPrompt:{color:"#666"},uploadIcon:{fontSize:"4rem",marginBottom:"1rem"},subtext:{color:"#999",fontSize:"0.9rem",marginTop:"0.5rem"},formats:{marginTop:"1rem",fontSize:"0.8rem",color:"#999"},multiPageHint:{marginTop:"1.5rem",padding:"0.5rem 1rem",background:"#e8f4fd",borderRadius:"6px",fontSize:"0.85rem",color:"#0066cc"},pagesContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",position:"relative"},pagesHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap",gap:"0.5rem"},headerActions:{display:"flex",gap:"0.5rem"},addMoreBtn:{padding:"0.5rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},clearBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",color:"#666",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},pagesGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1.5rem"},pageCard:{background:"#f8f9fa",borderRadius:"8px",padding:"0.5rem",position:"relative"},pageNumber:{position:"absolute",top:"0.75rem",left:"0.75rem",background:"rgba(0,0,0,0.7)",color:"white",padding:"0.25rem 0.5rem",borderRadius:"4px",fontSize:"0.75rem",fontWeight:"bold"},pagePreview:{width:"100%",height:"180px",objectFit:"cover",borderRadius:"6px"},pageActions:{display:"flex",justifyContent:"center",gap:"0.5rem",marginTop:"0.5rem"},moveBtn:{width:"32px",height:"32px",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem"},removeBtn:{width:"32px",height:"32px",background:"#fee",border:"1px solid #fcc",borderRadius:"4px",cursor:"pointer",fontSize:"1.2rem",color:"#c00"},processingOverlay:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"rgba(255,255,255,0.9)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"12px",zIndex:10},spinner:{width:"40px",height:"40px",border:"4px solid #ddd",borderTopColor:"#e94560",borderRadius:"50%",animation:"spin 1s linear infinite",marginBottom:"1rem"},uploadBtn:{width:"100%",padding:"1rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"1rem",fontWeight:"bold"},uploadBtnDisabled:{background:"#999",cursor:"wait"},cameraSection:{marginTop:"2rem",padding:"1.5rem",background:"white",borderRadius:"12px",textAlign:"center"},cameraHint:{fontSize:"0.85rem",color:"#666",marginTop:"0.5rem",marginBottom:"1rem"},cameraInput:{marginTop:"0.5rem"},infoSection:{marginTop:"1.5rem",padding:"1.5rem",background:"#f8f9fa",borderRadius:"12px"},infoList:{margin:"0.5rem 0 0 1.5rem",color:"#666",lineHeight:"1.8"},queueSection:{background:"white",borderRadius:"12px",padding:"1rem 1.5rem",marginBottom:"1.5rem"},queueHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},queueTitle:{margin:0,fontSize:"1rem",color:"#1a1a2e"},clearQueueBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",color:"#666"},queueList:{display:"flex",flexDirection:"column",gap:"0.5rem"},queueItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",borderRadius:"8px",borderLeft:"4px solid #0066cc"},queueItemComplete:{borderLeftColor:"#28a745",background:"#f0fff4"},queueItemError:{borderLeftColor:"#dc3545",background:"#fff5f5"},queueItemInfo:{display:"flex",flexDirection:"column",gap:"0.25rem"},queueItemName:{fontWeight:"500",fontSize:"0.9rem"},queueItemStatus:{fontSize:"0.8rem"},queueItemActions:{display:"flex",alignItems:"center",gap:"0.5rem"},queueViewBtn:{padding:"0.35rem 0.75rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},queueRemoveBtn:{width:"24px",height:"24px",background:"transparent",border:"none",cursor:"pointer",fontSize:"1.2rem",color:"#999",display:"flex",alignItems:"center",justifyContent:"center"},queueSpinner:{width:"20px",height:"20px",border:"2px solid #ddd",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"},pwaSection:{marginTop:"1.5rem",padding:"1.25rem 1.5rem",background:"linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)",borderRadius:"12px"},pwaContent:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem",color:"white"},pwaHint:{fontSize:"0.8rem",color:"rgba(255,255,255,0.6)",marginTop:"0.25rem"},installBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontSize:"0.9rem",fontWeight:"bold",cursor:"pointer",whiteSpace:"nowrap"},openAppLink:{padding:"0.6rem 1.25rem",background:"rgba(255,255,255,0.1)",color:"white",border:"1px solid rgba(255,255,255,0.3)",borderRadius:"8px",fontSize:"0.9rem",textDecoration:"none",whiteSpace:"nowrap"}},aN={upload:{label:"Upload",color:"#6c757d",icon:"📤"},email:{label:"Email",color:"#3498db",icon:"📧"},api:{label:"API",color:"#9b59b6",icon:"🔌"}},lN=({source:n})=>{const{label:e,color:t,icon:r}=aN[n]||aN.upload;return s.jsxs("span",{style:{background:t,color:"white",padding:"0.15rem 0.4rem",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"bold",display:"inline-flex",alignItems:"center",gap:"0.2rem"},children:[r," ",e]})},q2={PENDING:"#f59e0b",PROCESSED:"#3b82f6",REVIEWED:"#8b5cf6",CONFIRMED:"#22c55e",NEW:"#06b6d4"};function Nce(){const{token:n}=gn(),[e,t]=K_(),[r,i]=k.useState(()=>{const b=e.get("status");return b!==null?b:"pending_confirmation"}),[o,a]=k.useState(()=>e.get("supplier_id")||""),[l,d]=k.useState(()=>e.get("date_from")||""),[c,u]=k.useState(()=>e.get("date_to")||"");k.useEffect(()=>{e.toString()&&t({},{replace:!0})},[]);const{data:f}=Oe({queryKey:["suppliers"],queryFn:async()=>{const b=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():[]}}),p=new URLSearchParams;r&&p.append("status",r),o&&p.append("supplier_id",o),l&&p.append("date_from",l),c&&p.append("date_to",c);const g=p.toString(),{data:m,isLoading:y,error:v}=Oe({queryKey:["invoices",r,o,l,c],queryFn:async()=>{const b=g?`/api/invoices/?${g}`:"/api/invoices/",C=await fetch(b,{headers:{Authorization:`Bearer ${n}`}});if(!C.ok)throw new Error("Failed to fetch invoices");return C.json()}}),x=r==="pending_confirmation"&&(m==null?void 0:m.invoices.length)===0,{data:w}=Oe({queryKey:["completed-invoices"],queryFn:async()=>{const b=new URLSearchParams;b.set("status","confirmed"),b.set("limit","20"),b.set("sort","recent");const C=await fetch(`/api/invoices/?${b}`,{headers:{Authorization:`Bearer ${n}`}});if(!C.ok)throw new Error("Failed to fetch completed invoices");return C.json()},enabled:x&&!!n});if(y)return s.jsx("div",{style:Xt.loading,children:"Loading invoices..."});if(v)return s.jsxs("div",{style:Xt.error,children:["Error loading invoices: ",v.message]});const S=(m==null?void 0:m.invoices)||[],_=(w==null?void 0:w.invoices)||[];return s.jsxs("div",{children:[s.jsxs("div",{style:Xt.header,children:[s.jsx("h2",{style:Xt.title,children:"Uploaded Invoices"}),s.jsx("a",{href:"/upload",style:Xt.uploadBtn,children:"+ Upload New"})]}),s.jsxs("div",{style:Xt.filters,children:[s.jsxs("select",{value:r,onChange:b=>i(b.target.value),style:Xt.filterSelect,children:[s.jsx("option",{value:"",children:"All Statuses"}),s.jsx("option",{value:"pending_confirmation",children:"Pending Confirmation"}),s.jsx("option",{value:"pending",children:"Pending"}),s.jsx("option",{value:"processed",children:"Processed"}),s.jsx("option",{value:"reviewed",children:"Reviewed"}),s.jsx("option",{value:"confirmed",children:"Confirmed"})]}),s.jsxs("select",{value:o,onChange:b=>a(b.target.value),style:Xt.filterSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),f==null?void 0:f.map(b=>s.jsx("option",{value:b.id,children:b.name},b.id))]}),s.jsxs("div",{style:Xt.dateFilters,children:[s.jsxs("label",{style:Xt.dateLabel,children:["Upload Date From:",s.jsx("input",{type:"date",value:l,onChange:b=>d(b.target.value),style:Xt.dateInput})]}),s.jsxs("label",{style:Xt.dateLabel,children:["Upload Date To:",s.jsx("input",{type:"date",value:c,onChange:b=>u(b.target.value),style:Xt.dateInput})]})]}),(r!=="pending_confirmation"||o||l||c)&&s.jsx("button",{onClick:()=>{i("pending_confirmation"),a(""),d(""),u("")},style:Xt.clearBtn,children:"Clear Filters"})]}),S.length===0?s.jsxs("div",{style:Xt.empty,children:[s.jsx("p",{children:"No invoices pending confirmation."}),s.jsx("a",{href:"/upload",style:Xt.link,children:"Upload one now"})]}):s.jsx("div",{style:Xt.list,children:S.map(b=>s.jsxs("a",{href:`/invoice/${b.id}`,style:{...Xt.card,borderLeft:`4px solid ${q2[b.status]||"#999"}`},children:[s.jsxs("div",{style:Xt.cardMain,children:[s.jsxs("div",{style:Xt.invoiceNumberRow,children:[s.jsx("span",{style:Xt.invoiceNumber,children:b.invoice_number||(b.status==="PENDING"?"Pending extraction...":b.vendor_name?`(${b.vendor_name})`:"No invoice #")}),b.document_type==="delivery_note"&&s.jsx("span",{style:Xt.dnBadge,children:"DN"}),b.duplicate_status==="firm_duplicate"&&s.jsx("span",{style:Xt.duplicateBadge,children:"DUPLICATE"}),b.duplicate_status==="possible_duplicate"&&s.jsx("span",{style:Xt.possibleDuplicateBadge,children:"POSSIBLE DUPLICATE"})]}),s.jsxs("div",{style:Xt.invoiceMeta,children:[b.supplier_name?s.jsxs("span",{style:{...Xt.supplierName,...b.supplier_match_type==="fuzzy"?Xt.fuzzySupplier:{}},children:[b.supplier_name,b.supplier_match_type==="fuzzy"&&s.jsx("span",{style:Xt.fuzzyBadge,title:"Suggested match - please verify",children:"?"})]}):b.vendor_name?s.jsxs("span",{style:Xt.unmatchedSupplier,title:"No matching supplier found - click to assign",children:[b.vendor_name,s.jsx("span",{style:Xt.unmatchedBadge,children:"!"})]}):null,s.jsx("span",{style:Xt.invoiceDate,children:b.invoice_date?new Date(b.invoice_date).toLocaleDateString():"No date"})]})]}),s.jsxs("div",{style:Xt.cardRight,children:[s.jsx("div",{style:Xt.total,children:b.stock_total!=null&&b.total!=null&&b.stock_total!==b.total?s.jsxs(s.Fragment,{children:["£",Number(b.stock_total).toFixed(2),s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.net_total!=null?s.jsxs(s.Fragment,{children:["£",Number(b.net_total).toFixed(2),b.total!=null&&b.total!==b.net_total&&s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.total!=null?`£${Number(b.total).toFixed(2)}`:"—"}),s.jsxs("div",{style:Xt.badgeRow,children:[b.source&&b.source!=="upload"&&s.jsx(lN,{source:b.source}),s.jsx("div",{style:{...Xt.status,background:q2[b.status]||"#999"},children:b.status})]})]}),b.ocr_confidence!=null&&s.jsxs("div",{style:Xt.confidence,children:[(Number(b.ocr_confidence)*100).toFixed(0),"% confidence"]})]},b.id))}),x&&_.length>0&&s.jsxs("div",{style:{marginTop:"2rem"},children:[s.jsx("h3",{style:{...Xt.title,fontSize:"1.2rem",marginBottom:"1rem"},children:"Recently Completed Invoices"}),s.jsx("div",{style:Xt.list,children:_.map(b=>s.jsxs("a",{href:`/invoice/${b.id}`,style:{...Xt.card,borderLeft:`4px solid ${q2[b.status]||"#999"}`},children:[s.jsxs("div",{style:Xt.cardMain,children:[s.jsxs("div",{style:Xt.invoiceNumberRow,children:[s.jsx("span",{style:Xt.invoiceNumber,children:b.invoice_number||(b.status==="PENDING"?"Pending extraction...":b.vendor_name?`(${b.vendor_name})`:"No invoice #")}),b.document_type==="delivery_note"&&s.jsx("span",{style:Xt.dnBadge,children:"DN"}),b.duplicate_status==="firm_duplicate"&&s.jsx("span",{style:Xt.duplicateBadge,children:"DUPLICATE"}),b.duplicate_status==="possible_duplicate"&&s.jsx("span",{style:Xt.possibleDuplicateBadge,children:"POSSIBLE DUPLICATE"})]}),s.jsxs("div",{style:Xt.invoiceMeta,children:[b.supplier_name?s.jsxs("span",{style:{...Xt.supplierName,...b.supplier_match_type==="fuzzy"?Xt.fuzzySupplier:{}},children:[b.supplier_name,b.supplier_match_type==="fuzzy"&&s.jsx("span",{style:Xt.fuzzyBadge,title:"Suggested match - please verify",children:"?"})]}):b.vendor_name?s.jsxs("span",{style:Xt.unmatchedSupplier,title:"No matching supplier found - click to assign",children:[b.vendor_name,s.jsx("span",{style:Xt.unmatchedBadge,children:"!"})]}):null,s.jsx("span",{style:Xt.invoiceDate,children:b.invoice_date?new Date(b.invoice_date).toLocaleDateString():"No date"})]})]}),s.jsxs("div",{style:Xt.cardRight,children:[s.jsx("div",{style:Xt.total,children:b.stock_total!=null&&b.total!=null&&b.stock_total!==b.total?s.jsxs(s.Fragment,{children:["£",Number(b.stock_total).toFixed(2),s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.net_total!=null?s.jsxs(s.Fragment,{children:["£",Number(b.net_total).toFixed(2),b.total!=null&&b.total!==b.net_total&&s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.total!=null?`£${Number(b.total).toFixed(2)}`:"—"}),s.jsxs("div",{style:Xt.badgeRow,children:[b.source&&b.source!=="upload"&&s.jsx(lN,{source:b.source}),s.jsx("div",{style:{...Xt.status,background:q2[b.status]||"#999"},children:b.status})]})]}),b.ocr_confidence!=null&&s.jsxs("div",{style:Xt.confidence,children:[(Number(b.ocr_confidence)*100).toFixed(0),"% confidence"]})]},b.id))})]})]})}const Xt={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},uploadBtn:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",textDecoration:"none",borderRadius:"8px",fontWeight:"bold"},filters:{display:"flex",gap:"1rem",marginBottom:"1.5rem",alignItems:"center",flexWrap:"wrap",background:"white",padding:"1rem",borderRadius:"8px"},filterSelect:{padding:"0.5rem 1rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.9rem",minWidth:"150px"},dateFilters:{display:"flex",gap:"1rem",alignItems:"center"},dateLabel:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem",color:"#666"},dateInput:{padding:"0.5rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.9rem"},clearBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},empty:{background:"white",padding:"3rem",borderRadius:"12px",textAlign:"center",color:"#666"},link:{color:"#e94560",marginTop:"1rem",display:"inline-block"},list:{display:"flex",flexDirection:"column",gap:"1rem"},card:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"white",padding:"1.25rem 1.5rem",borderRadius:"12px",textDecoration:"none",color:"inherit",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",transition:"transform 0.2s, box-shadow 0.2s",position:"relative"},cardMain:{flex:1},invoiceNumberRow:{display:"flex",alignItems:"center",gap:"0.5rem",flexWrap:"wrap"},invoiceNumber:{fontWeight:"bold",fontSize:"1.1rem",color:"#1a1a2e"},dnBadge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#6c757d",color:"white",fontSize:"0.65rem",fontWeight:"bold",borderRadius:"4px",textTransform:"uppercase"},duplicateBadge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#dc3545",color:"white",fontSize:"0.65rem",fontWeight:"bold",borderRadius:"4px",textTransform:"uppercase"},possibleDuplicateBadge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#fd7e14",color:"white",fontSize:"0.65rem",fontWeight:"bold",borderRadius:"4px",textTransform:"uppercase"},invoiceMeta:{display:"flex",gap:"0.75rem",marginTop:"0.25rem",alignItems:"center"},supplierName:{color:"#1a1a2e",fontSize:"0.9rem",fontWeight:"500"},fuzzySupplier:{color:"#856404",background:"#fff3cd",padding:"0.1rem 0.4rem",borderRadius:"4px",border:"1px solid #ffc107"},fuzzyBadge:{display:"inline-block",marginLeft:"0.3rem",width:"14px",height:"14px",lineHeight:"14px",textAlign:"center",background:"#ffc107",color:"#856404",borderRadius:"50%",fontSize:"0.7rem",fontWeight:"bold"},unmatchedSupplier:{color:"#721c24",background:"#f8d7da",padding:"0.1rem 0.4rem",borderRadius:"4px",border:"1px solid #f5c6cb",fontSize:"0.9rem"},unmatchedBadge:{display:"inline-block",marginLeft:"0.3rem",width:"14px",height:"14px",lineHeight:"14px",textAlign:"center",background:"#dc3545",color:"white",borderRadius:"50%",fontSize:"0.7rem",fontWeight:"bold"},invoiceDate:{color:"#666",fontSize:"0.9rem"},cardRight:{textAlign:"right",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"0.5rem"},badgeRow:{display:"flex",gap:"0.4rem",alignItems:"center",justifyContent:"flex-end"},total:{fontWeight:"bold",fontSize:"1.2rem",color:"#1a1a2e"},fullTotal:{fontSize:"0.85rem",fontWeight:"normal",color:"#666",marginLeft:"0.25rem"},status:{display:"inline-block",padding:"0.25rem 0.75rem",borderRadius:"20px",color:"white",fontSize:"0.75rem",textTransform:"uppercase"},confidence:{position:"absolute",top:"0.5rem",right:"0.75rem",fontSize:"0.7rem",color:"#999"}},zl=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),hf=[1/0,1/0,-1/0,-1/0],_m=new Float32Array(hf),GB=[.001,0,0,.001,0,0],OP=1.35,Rl={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Ru={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Gj="pdfjs_internal_editor_",jn={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},Wn={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},Wce={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Rs={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},E5={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Cs={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},Sx={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},eD={ERRORS:0,WARNINGS:1,INFOS:5},Sh={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Hw={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},Uce={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let tD=eD.WARNINGS;function Hce(n){Number.isInteger(n)&&(tD=n)}function qce(){return tD}function nD(n){tD>=eD.INFOS&&console.info(`Info: ${n}`)}function Bn(n){tD>=eD.WARNINGS&&console.warn(`Warning: ${n}`)}function Hr(n){throw new Error(n)}function Zi(n,e){n||Hr(e)}function Vce(n){switch(n==null?void 0:n.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function aV(n,e=null,t=null){if(!n)return null;if(t&&typeof n=="string"){if(t.addDefaultProtocol&&n.startsWith("www.")){const i=n.match(/\./g);(i==null?void 0:i.length)>=2&&(n=`http://${n}`)}if(t.tryConvertEncoding)try{n=Yce(n)}catch{}}const r=e?URL.parse(n,e):URL.parse(n);return Vce(r)?r:null}function lV(n,e,t=!1){const r=URL.parse(n);return r?(r.hash=e,r.href):t&&aV(n,"http://example.com")?n.split("#",1)[0]+`${e?`#${e}`:""}`:""}function KB(n){return n.substring(n.lastIndexOf("/")+1)}function Cn(n,e,t,r=!1){return Object.defineProperty(n,e,{value:t,enumerable:!r,configurable:!0,writable:!1}),t}const W0=function(){function e(t,r){this.message=t,this.name=r}return e.prototype=new Error,e.constructor=e,e}();class dN extends W0{constructor(e,t){super(e,"PasswordException"),this.code=t}}class LP extends W0{constructor(e,t){super(e,"UnknownErrorException"),this.details=t}}class XB extends W0{constructor(e){super(e,"InvalidPDFException")}}class xT extends W0{constructor(e,t,r){super(e,"ResponseException"),this.status=t,this.missing=r}}class Gce extends W0{constructor(e){super(e,"FormatError")}}class Ng extends W0{constructor(e){super(e,"AbortException")}}function Kce(n){(typeof n!="object"||(n==null?void 0:n.length)===void 0)&&Hr("Invalid argument for bytesToString");const e=n.length,t=8192;if(e{if(typeof document>"u")return!1;const e=document.createElement("input");return e.type="color",e.setAttribute("alpha",""),e.value="#ff000080",e.value!=="#ff0000"})())}}var bf,P5,YB;class yt{static get hexNums(){return Cn(this,"hexNums",Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,"0")))}static makeHexColor(e,t,r){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[r]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,t){let r;e[0]?(e[0]<0&&(r=t[0],t[0]=t[2],t[2]=r),t[0]*=e[0],t[2]*=e[0],e[3]<0&&(r=t[1],t[1]=t[3],t[3]=r),t[1]*=e[3],t[3]*=e[3]):(r=t[0],t[0]=t[1],t[1]=r,r=t[2],t[2]=t[3],t[3]=r,e[1]<0&&(r=t[1],t[1]=t[3],t[3]=r),t[1]*=e[1],t[3]*=e[1],e[2]<0&&(r=t[0],t[0]=t[2],t[2]=r),t[0]*=e[2],t[2]*=e[2]),t[0]+=e[4],t[1]+=e[5],t[2]+=e[4],t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,r=0){const i=e[r],o=e[r+1];e[r]=i*t[0]+o*t[2]+t[4],e[r+1]=i*t[1]+o*t[3]+t[5]}static applyTransformToBezier(e,t,r=0){const i=t[0],o=t[1],a=t[2],l=t[3],d=t[4],c=t[5];for(let u=0;u<6;u+=2){const f=e[r+u],p=e[r+u+1];e[r+u]=f*i+p*a+d,e[r+u+1]=f*o+p*l+c}}static applyInverseTransform(e,t){const r=e[0],i=e[1],o=t[0]*t[3]-t[1]*t[2];e[0]=(r*t[3]-i*t[2]+t[2]*t[5]-t[4]*t[3])/o,e[1]=(-r*t[1]+i*t[0]+t[4]*t[1]-t[5]*t[0])/o}static axialAlignedBoundingBox(e,t,r){const i=t[0],o=t[1],a=t[2],l=t[3],d=t[4],c=t[5],u=e[0],f=e[1],p=e[2],g=e[3];let m=i*u+d,y=m,v=i*p+d,x=v,w=l*f+c,S=w,_=l*g+c,b=_;if(o!==0||a!==0){const C=o*u,T=o*p,F=a*f,A=a*g;m+=F,x+=F,v+=A,y+=A,w+=C,b+=C,_+=T,S+=T}r[0]=Math.min(r[0],m,v,y,x),r[1]=Math.min(r[1],w,_,S,b),r[2]=Math.max(r[2],m,v,y,x),r[3]=Math.max(r[3],w,_,S,b)}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){const r=e[0],i=e[1],o=e[2],a=e[3],l=r**2+i**2,d=r*o+i*a,c=o**2+a**2,u=(l+c)/2,f=Math.sqrt(u**2-(l*c-d**2));t[0]=Math.sqrt(u+f||1),t[1]=Math.sqrt(u-f||1)}static normalizeRect(e){const t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){const r=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),i=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(r>i)return null;const o=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return o>a?null:[r,o,i,a]}static pointBoundingBox(e,t,r){r[0]=Math.min(r[0],e),r[1]=Math.min(r[1],t),r[2]=Math.max(r[2],e),r[3]=Math.max(r[3],t)}static rectBoundingBox(e,t,r,i,o){o[0]=Math.min(o[0],e,r),o[1]=Math.min(o[1],t,i),o[2]=Math.max(o[2],e,r),o[3]=Math.max(o[3],t,i)}static bezierBoundingBox(e,t,r,i,o,a,l,d,c){c[0]=Math.min(c[0],e,l),c[1]=Math.min(c[1],t,d),c[2]=Math.max(c[2],e,l),c[3]=Math.max(c[3],t,d),q(this,bf,YB).call(this,e,r,o,l,t,i,a,d,3*(-e+3*(r-o)+l),6*(e-2*r+o),3*(r-e),c),q(this,bf,YB).call(this,e,r,o,l,t,i,a,d,3*(-t+3*(i-a)+d),6*(t-2*i+a),3*(i-t),c)}}bf=new WeakSet,P5=function(e,t,r,i,o,a,l,d,c,u){if(c<=0||c>=1)return;const f=1-c,p=c*c,g=p*c,m=f*(f*(f*e+3*c*t)+3*p*r)+g*i,y=f*(f*(f*o+3*c*a)+3*p*l)+g*d;u[0]=Math.min(u[0],m),u[1]=Math.min(u[1],y),u[2]=Math.max(u[2],m),u[3]=Math.max(u[3],y)},YB=function(e,t,r,i,o,a,l,d,c,u,f,p){if(Math.abs(c)<1e-12){Math.abs(u)>=1e-12&&q(this,bf,P5).call(this,e,t,r,i,o,a,l,d,-f/u,p);return}const g=u**2-4*f*c;if(g<0)return;const m=Math.sqrt(g),y=2*c;q(this,bf,P5).call(this,e,t,r,i,o,a,l,d,(-u+m)/y,p),q(this,bf,P5).call(this,e,t,r,i,o,a,l,d,(-u-m)/y,p)},N(yt,bf);function Yce(n){return decodeURIComponent(escape(n))}let NP=null,cN=null;function Qce(n){return NP||(NP=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,cN=new Map([["ſt","ſt"]])),n.replaceAll(NP,(e,t,r)=>t?t.normalize("NFKC"):cN.get(r))}function dV(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const n=new Uint8Array(32);return crypto.getRandomValues(n),Kce(n)}const Yx="pdfjs_internal_id_";function $ce(n,e,t){if(!Array.isArray(t)||t.length<2)return!1;const[r,i,...o]=t;if(!n(r)&&!Number.isInteger(r)||!e(i))return!1;const a=o.length;let l=!0;switch(i.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return a===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(a!==4)return!1;l=!1;break;default:return!1}for(const d of o)if(!(typeof d=="number"||l&&d===null))return!1;return!0}const F3=()=>[],D3=()=>new Map,QB=()=>Object.create(null);function Bi(n,e,t){return Math.min(Math.max(n,e),t)}class Kj{static textContent(e){const t=[],r={items:t,styles:Object.create(null)};function i(o){var d;if(!o)return;let a=null;const l=o.name;if(l==="#text")a=o.value;else if(Kj.shouldBuildText(l))(d=o==null?void 0:o.attributes)!=null&&d.textContent?a=o.attributes.textContent:o.value&&(a=o.value);else return;if(a!==null&&t.push({str:a}),!!o.children)for(const c of o.children)i(c)}return i(e),r}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}}class cV{static setupStorage(e,t,r,i,o){const a=i.getValue(t,{value:null});switch(r.name){case"textarea":if(a.value!==null&&(e.textContent=a.value),o==="print")break;e.addEventListener("input",l=>{i.setValue(t,{value:l.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(a.value===r.attributes.xfaOn?e.setAttribute("checked",!0):a.value===r.attributes.xfaOff&&e.removeAttribute("checked"),o==="print")break;e.addEventListener("change",l=>{i.setValue(t,{value:l.target.checked?l.target.getAttribute("xfaOn"):l.target.getAttribute("xfaOff")})})}else{if(a.value!==null&&e.setAttribute("value",a.value),o==="print")break;e.addEventListener("input",l=>{i.setValue(t,{value:l.target.value})})}break;case"select":if(a.value!==null){e.setAttribute("value",a.value);for(const l of r.children)l.attributes.value===a.value?l.attributes.selected=!0:Object.hasOwn(l.attributes,"selected")&&delete l.attributes.selected}e.addEventListener("input",l=>{const d=l.target.options,c=d.selectedIndex===-1?"":d[d.selectedIndex].value;i.setValue(t,{value:c})});break}}static setAttributes({html:e,element:t,storage:r=null,intent:i,linkService:o}){const{attributes:a}=t,l=e instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${i}`);for(const[d,c]of Object.entries(a))if(c!=null)switch(d){case"class":c.length&&e.setAttribute(d,c.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",c);break;case"style":Object.assign(e.style,c);break;case"textContent":e.textContent=c;break;default:(!l||d!=="href"&&d!=="newWindow")&&e.setAttribute(d,c)}l&&o.addLinkAttributes(e,a.href,a.newWindow),r&&a.dataId&&this.setupStorage(e,a.dataId,t,r)}static render(e){var f,p;const t=e.annotationStorage,r=e.linkService,i=e.xfaHtml,o=e.intent||"display",a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:o,linkService:r});const l=o!=="richText",d=e.div;if(d.append(a),e.viewport){const g=`matrix(${e.viewport.transform.join(",")})`;d.style.transform=g}l&&d.setAttribute("class","xfaLayer xfaFont");const c=[];if(i.children.length===0){if(i.value){const g=document.createTextNode(i.value);a.append(g),l&&Kj.shouldBuildText(i.name)&&c.push(g)}return{textDivs:c}}const u=[[i,-1,a]];for(;u.length>0;){const[g,m,y]=u.at(-1);if(m+1===g.children.length){u.pop();continue}const v=g.children[++u.at(-1)[1]];if(v===null)continue;const{name:x}=v;if(x==="#text"){const S=document.createTextNode(v.value);c.push(S),y.append(S);continue}const w=(f=v==null?void 0:v.attributes)!=null&&f.xmlns?document.createElementNS(v.attributes.xmlns,x):document.createElement(x);if(y.append(w),v.attributes&&this.setAttributes({html:w,element:v,storage:t,intent:o,linkService:r}),((p=v.children)==null?void 0:p.length)>0)u.push([v,-1,w]);else if(v.value){const S=document.createTextNode(v.value);l&&Kj.shouldBuildText(x)&&c.push(S),w.append(S)}}for(const g of d.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))g.setAttribute("readOnly",!0);return{textDivs:c}}static update(e){const t=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=t,e.div.hidden=!1}}const hh="http://www.w3.org/2000/svg",hm=class hm{};ve(hm,"CSS",96),ve(hm,"PDF",72),ve(hm,"PDF_TO_CSS_UNITS",hm.CSS/hm.PDF);let Wg=hm;async function E3(n,e="text"){if(rj(n,document.baseURI)){const t=await fetch(n);if(!t.ok)throw new Error(t.statusText);switch(e){case"blob":return t.blob();case"bytes":return t.bytes();case"json":return t.json()}return t.text()}return new Promise((t,r)=>{const i=new XMLHttpRequest;i.open("GET",n,!0),i.responseType=e==="bytes"?"arraybuffer":e,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(e){case"bytes":t(new Uint8Array(i.response));return;case"blob":case"json":t(i.response);return}t(i.responseText);return}r(new Error(i.statusText))}},i.send(null)})}class dC{constructor({viewBox:e,userUnit:t,scale:r,rotation:i,offsetX:o=0,offsetY:a=0,dontFlip:l=!1}){this.viewBox=e,this.userUnit=t,this.scale=r,this.rotation=i,this.offsetX=o,this.offsetY=a,r*=t;const d=(e[2]+e[0])/2,c=(e[3]+e[1])/2;let u,f,p,g;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,f=0,p=0,g=1;break;case 90:u=0,f=1,p=1,g=0;break;case 270:u=0,f=-1,p=-1,g=0;break;case 0:u=1,f=0,p=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(p=-p,g=-g);let m,y,v,x;u===0?(m=Math.abs(c-e[1])*r+o,y=Math.abs(d-e[0])*r+a,v=(e[3]-e[1])*r,x=(e[2]-e[0])*r):(m=Math.abs(d-e[0])*r+o,y=Math.abs(c-e[1])*r+a,v=(e[2]-e[0])*r,x=(e[3]-e[1])*r),this.transform=[u*r,f*r,p*r,g*r,m-u*r*d-p*r*c,y-f*r*d-g*r*c],this.width=v,this.height=x}get rawDims(){const e=this.viewBox;return Cn(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:t=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:o=!1}={}){return new dC({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:t,offsetX:r,offsetY:i,dontFlip:o})}convertToViewportPoint(e,t){const r=[e,t];return yt.applyTransform(r,this.transform),r}convertToViewportRectangle(e){const t=[e[0],e[1]];yt.applyTransform(t,this.transform);const r=[e[2],e[3]];return yt.applyTransform(r,this.transform),[t[0],t[1],r[0],r[1]]}convertToPdfPoint(e,t){const r=[e,t];return yt.applyInverseTransform(r,this.transform),r}}class P3 extends W0{constructor(e,t=0){super(e,"RenderingCancelledException"),this.extraDelay=t}}function iD(n){const e=n.length;let t=0;for(;t{try{return new URL(l)}catch{try{return new URL(decodeURIComponent(l))}catch{try{return new URL(l,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(l),"https://foo.bar")}catch{return null}}}}})(n);if(!r)return e;const i=l=>{try{let d=decodeURIComponent(l);return d.includes("/")&&(d=KB(d),/^\.pdf$/i.test(d))?l:d}catch{return l}},o=/\.pdf$/i,a=KB(r.pathname);if(o.test(a))return i(a);if(r.searchParams.size>0){const l=c=>[...c].findLast(u=>o.test(u)),d=l(r.searchParams.values())??l(r.searchParams.keys());if(d)return i(d)}if(r.hash){const d=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(r.hash);if(d)return i(d[0])}return e}var gp;class uN{constructor(){N(this,gp,new Map);ve(this,"times",[])}time(e){h(this,gp).has(e)&&Bn(`Timer is already running for ${e}`),h(this,gp).set(e,Date.now())}timeEnd(e){h(this,gp).has(e)||Bn(`Timer has not been started for ${e}`),this.times.push({name:e,start:h(this,gp).get(e),end:Date.now()}),h(this,gp).delete(e)}toString(){const e=Math.max(...this.times.map(t=>t.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms `).join("")}}gp=new WeakMap;function rj(n,e){const t=e?URL.parse(n,e):URL.parse(n);return/https?:/.test((t==null?void 0:t.protocol)??"")}function Hd(n){n.preventDefault()}function $i(n){n.preventDefault(),n.stopPropagation()}function eue(n){console.log("Deprecated API usage: "+n)}var rk;class bT{static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!="string")return null;h(this,rk)||R(this,rk,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const t=h(this,rk).exec(e);if(!t)return null;const r=parseInt(t[1],10);let i=parseInt(t[2],10);i=i>=1&&i<=12?i-1:0;let o=parseInt(t[3],10);o=o>=1&&o<=31?o:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let l=parseInt(t[5],10);l=l>=0&&l<=59?l:0;let d=parseInt(t[6],10);d=d>=0&&d<=59?d:0;const c=t[7]||"Z";let u=parseInt(t[8],10);u=u>=0&&u<=23?u:0;let f=parseInt(t[9],10)||0;return f=f>=0&&f<=59?f:0,c==="-"?(a+=u,l+=f):c==="+"&&(a-=u,l-=f),new Date(Date.UTC(r,i,o,a,l,d))}}rk=new WeakMap,N(bT,rk);function tue(n,{scale:e=1,rotation:t=0}){const{width:r,height:i}=n.attributes.style,o=[0,0,parseInt(r,10),parseInt(i,10)];return new dC({viewBox:o,userUnit:1,scale:e,rotation:t})}function B3(n){if(n.startsWith("#")){const t=n.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(n.startsWith("rgb(")){const[t,r,i]=n.slice(4,-1).split(",").map(o=>parseInt(o,10));return[t,r,i,1]}if(n.startsWith("rgba(")){const t=n.slice(5,-1).split(",");return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}const e=n.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(parseFloat(e[1])*255),Math.round(parseFloat(e[2])*255),Math.round(parseFloat(e[3])*255),e[4]!==void 0&&e[4]!=="none"?parseFloat(e[4]):1]:null}function cC(n){const e=B3(n);return e?e.slice(0,3):(Bn(`Not a valid color format: "${n}"`),[0,0,0])}function nue(n){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const t of n.keys()){e.style.color=t;const r=window.getComputedStyle(e).color;n.set(t,cC(r))}e.remove()}function ji(n){const{a:e,b:t,c:r,d:i,e:o,f:a}=n.getTransform();return[e,t,r,i,o,a]}function Kc(n){const{a:e,b:t,c:r,d:i,e:o,f:a}=n.getTransform().invertSelf();return[e,t,r,i,o,a]}function k0(n,e,t=!1,r=!0){if(e instanceof dC){const{pageWidth:i,pageHeight:o}=e.rawDims,{style:a}=n,l=Ds.isCSSRoundSupported,d=`var(--total-scale-factor) * ${i}px`,c=`var(--total-scale-factor) * ${o}px`,u=l?`round(down, ${d}, var(--scale-round-x))`:`calc(${d})`,f=l?`round(down, ${c}, var(--scale-round-y))`:`calc(${c})`;!t||e.rotation%180===0?(a.width=u,a.height=f):(a.width=f,a.height=u)}r&&n.setAttribute("data-main-rotation",e.rotation)}class Lu{constructor(){const{pixelRatio:e}=Lu;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(e,t,r,i,o=-1){let a=1/0,l=1/0,d=1/0;r=Lu.capPixels(r,o),r>0&&(a=Math.sqrt(r/(e*t))),i!==-1&&(l=i/e,d=i/t);const c=Math.min(a,l,d);return this.sx>c||this.sy>c?(this.sx=c,this.sy=c,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){const r=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,r):r}return e}}const $B=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class rue{static get isDarkMode(){var e;return Cn(this,"isDarkMode",!!((e=window==null?void 0:window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches))}}class iue{static get commentForegroundColor(){const e=document.createElement("span");e.classList.add("comment","sidebar");const{style:t}=e;t.width=t.height="0",t.display="none",t.color="var(--comment-fg-color)",document.body.append(e);const{color:r}=window.getComputedStyle(e);return e.remove(),Cn(this,"commentForegroundColor",cC(r))}}function sue(n,e){e=Bi(e??1,0,1);const t=255*(1-e);return n.map(r=>Math.round(r*e+t))}function hN(n,e){const t=n[0]/255,r=n[1]/255,i=n[2]/255,o=Math.max(t,r,i),a=Math.min(t,r,i),l=(o+a)/2;if(o===a)e[0]=e[1]=0;else{const d=o-a;switch(e[1]=l<.5?d/(o+a):d/(2-o-a),o){case t:e[0]=((r-i)/d+(ri?(r+.05)/(i+.05):(i+.05)/(r+.05)}const gN=new Map;function oue(n,e){const t=n[0]+n[1]*256+n[2]*65536+e[0]*16777216+e[1]*4294967296+e[2]*1099511627776;let r=gN.get(t);if(r)return r;const i=new Float32Array(9),o=i.subarray(0,3),a=i.subarray(3,6);hN(n,a);const l=i.subarray(6,9);hN(e,l);const d=l[2]<.5,c=d?12:4.5;if(a[2]=d?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]),pN(a,l,o)p;){const g=a[2]=(u+f)/2;d===pN(a,l,o){t.delete()},{signal:t._signal}),h(this,ud).append(r)}async addAltText(e){const t=await e.render();q(this,Do,jx).call(this,t),h(this,ud).append(t,h(this,Do,uS)),R(this,ik,e)}addComment(e,t=null){if(h(this,xp))return;const r=e.renderForToolbar();if(!r)return;q(this,Do,jx).call(this,r);const i=R(this,jb,h(this,Do,uS));t?(h(this,ud).insertBefore(r,t),h(this,ud).insertBefore(i,t)):h(this,ud).append(r,i),R(this,xp,e),e.toolbar=this}addColorPicker(e){if(h(this,yp))return;R(this,yp,e);const t=e.renderButton();q(this,Do,jx).call(this,t),h(this,ud).append(t,h(this,Do,uS))}async addEditSignatureButton(e){const t=R(this,kb,await e.renderEditButton(h(this,cd)));q(this,Do,jx).call(this,t),h(this,ud).append(t,h(this,Do,uS))}removeButton(e){var t,r;switch(e){case"comment":(t=h(this,xp))==null||t.removeToolbarCommentButton(),R(this,xp,null),(r=h(this,jb))==null||r.remove(),R(this,jb,null);break}}async addButton(e,t){switch(e){case"colorPicker":t&&this.addColorPicker(t);break;case"altText":t&&await this.addAltText(t);break;case"editSignature":t&&await this.addEditSignatureButton(t);break;case"delete":this.addDeleteButton();break;case"comment":t&&this.addComment(t);break}}async addButtonBefore(e,t,r){if(!t&&e==="comment")return;const i=h(this,ud).querySelector(r);i&&e==="comment"&&this.addComment(t,i)}updateEditSignatureButton(e){h(this,kb)&&(h(this,kb).title=e)}remove(){var e;h(this,mp).remove(),(e=h(this,yp))==null||e.destroy(),R(this,yp,null)}};mp=new WeakMap,yp=new WeakMap,cd=new WeakMap,ud=new WeakMap,ik=new WeakMap,xp=new WeakMap,jb=new WeakMap,kb=new WeakMap,sk=new WeakMap,FT=new WeakSet,fV=function(e){e.stopPropagation()},Do=new WeakSet,pV=function(e){h(this,cd)._focusEventsAllowed=!1,$i(e)},gV=function(e){h(this,cd)._focusEventsAllowed=!0,$i(e)},jx=function(e){const t=h(this,cd)._uiManager._signal;return!(t instanceof AbortSignal)||t.aborted?!1:(e.addEventListener("focusin",q(this,Do,pV).bind(this),{capture:!0,signal:t}),e.addEventListener("focusout",q(this,Do,gV).bind(this),{capture:!0,signal:t}),e.addEventListener("contextmenu",Hd,{signal:t}),!0)},uS=function(){const e=document.createElement("div");return e.className="divider",e},N(yh,FT),N(yh,sk,null);let JB=yh;var ok,Mm,Ah,Tf,mV,yV,eI;class aue{constructor(e){N(this,Tf);N(this,ok,null);N(this,Mm,null);N(this,Ah);R(this,Ah,e)}show(e,t,r){const[i,o]=q(this,Tf,yV).call(this,t,r),{style:a}=h(this,Mm)||R(this,Mm,q(this,Tf,mV).call(this));e.append(h(this,Mm)),a.insetInlineEnd=`${100*i}%`,a.top=`calc(${100*o}% + var(--editor-toolbar-vert-offset))`}hide(){h(this,Mm).remove()}}ok=new WeakMap,Mm=new WeakMap,Ah=new WeakMap,Tf=new WeakSet,mV=function(){const e=R(this,Mm,document.createElement("div"));e.className="editToolbar",e.setAttribute("role","toolbar");const t=h(this,Ah)._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener("contextmenu",Hd,{signal:t});const r=R(this,ok,document.createElement("div"));return r.className="buttons",e.append(r),h(this,Ah).hasCommentManager()&&q(this,Tf,eI).call(this,"commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{h(this,Ah).commentSelection("floating_button")}),q(this,Tf,eI).call(this,"highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{h(this,Ah).highlightSelection("floating_button")}),e},yV=function(e,t){let r=0,i=0;for(const o of e){const a=o.y+o.height;if(ar){i=l,r=a;continue}t?l>i&&(i=l):l=1}static clearPointerType(){R(ni,Lm,null)}static clearPointerIds(){R(ni,zm,NaN),R(ni,Om,null)}static clearTimeStamp(){R(ni,_b,NaN)}};zm=new WeakMap,Om=new WeakMap,_b=new WeakMap,Lm=new WeakMap,N(ni,zm,NaN),N(ni,Om,null),N(ni,_b,NaN),N(ni,Lm,null);let Yo=ni;var DT;class lue{constructor(){N(this,DT,0)}get id(){return`${Gj}${Gi(this,DT)._++}`}}DT=new WeakMap;var Cb,ak,$o,Ab,R5;const W3=class W3{constructor(){N(this,Ab);N(this,Cb,dV());N(this,ak,0);N(this,$o,null)}static get _isSVGFittingCanvas(){const e='data:image/svg+xml;charset=UTF-8,',r=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=e;const o=i.decode().then(()=>(r.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(r.getImageData(0,0,1,1).data.buffer)[0]===0));return Cn(this,"_isSVGFittingCanvas",o)}async getFromFile(e){const{lastModified:t,name:r,size:i,type:o}=e;return q(this,Ab,R5).call(this,`${t}_${r}_${i}_${o}`,e)}async getFromUrl(e){return q(this,Ab,R5).call(this,e,e)}async getFromBlob(e,t){const r=await t;return q(this,Ab,R5).call(this,e,r)}async getFromId(e){h(this,$o)||R(this,$o,new Map);const t=h(this,$o).get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){const{blobPromise:r}=t;return delete t.blobPromise,this.getFromBlob(t.id,r)}return this.getFromUrl(t.url)}getFromCanvas(e,t){h(this,$o)||R(this,$o,new Map);let r=h(this,$o).get(e);if(r!=null&&r.bitmap)return r.refCounter+=1,r;const i=new OffscreenCanvas(t.width,t.height);return i.getContext("2d").drawImage(t,0,0),r={bitmap:i.transferToImageBitmap(),id:`image_${h(this,Cb)}_${Gi(this,ak)._++}`,refCounter:1,isSvg:!1},h(this,$o).set(e,r),h(this,$o).set(r.id,r),r}getSvgUrl(e){const t=h(this,$o).get(e);return t!=null&&t.isSvg?t.svgUrl:null}deleteId(e){var i;h(this,$o)||R(this,$o,new Map);const t=h(this,$o).get(e);if(!t||(t.refCounter-=1,t.refCounter!==0))return;const{bitmap:r}=t;if(!t.url&&!t.file){const o=new OffscreenCanvas(r.width,r.height);o.getContext("bitmaprenderer").transferFromImageBitmap(r),t.blobPromise=o.convertToBlob()}(i=r.close)==null||i.call(r),t.bitmap=null}isValidId(e){return e.startsWith(`image_${h(this,Cb)}_`)}};Cb=new WeakMap,ak=new WeakMap,$o=new WeakMap,Ab=new WeakSet,R5=async function(e,t){h(this,$o)||R(this,$o,new Map);let r=h(this,$o).get(e);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${h(this,Cb)}_${Gi(this,ak)._++}`,refCounter:0,isSvg:!1});let i;if(typeof t=="string"?(r.url=t,i=await E3(t,"blob")):t instanceof File?i=r.file=t:t instanceof Blob&&(i=t),i.type==="image/svg+xml"){const o=W3._isSVGFittingCanvas,a=new FileReader,l=new Image,d=new Promise((c,u)=>{l.onload=()=>{r.bitmap=l,r.isSvg=!0,c()},a.onload=async()=>{const f=r.svgUrl=a.result;l.src=await o?`${f}#svgView(preserveAspectRatio(none))`:f},l.onerror=a.onerror=u});a.readAsDataURL(i),await d}else r.bitmap=await createImageBitmap(i);r.refCounter=1}catch(i){Bn(i),r=null}return h(this,$o).set(e,r),r&&h(this,$o).set(r.id,r),r};let tI=W3;var ys,bp,lk,Xi;class due{constructor(e=128){N(this,ys,[]);N(this,bp,!1);N(this,lk);N(this,Xi,-1);R(this,lk,e)}add({cmd:e,undo:t,post:r,mustExec:i,type:o=NaN,overwriteIfSameType:a=!1,keepUndo:l=!1}){if(i&&e(),h(this,bp))return;const d={cmd:e,undo:t,post:r,type:o};if(h(this,Xi)===-1){h(this,ys).length>0&&(h(this,ys).length=0),R(this,Xi,0),h(this,ys).push(d);return}if(a&&h(this,ys)[h(this,Xi)].type===o){l&&(d.undo=h(this,ys)[h(this,Xi)].undo),h(this,ys)[h(this,Xi)]=d;return}const c=h(this,Xi)+1;c===h(this,lk)?h(this,ys).splice(0,1):(R(this,Xi,c),c=0;t--)if(h(this,ys)[t].type!==e){h(this,ys).splice(t+1,h(this,Xi)-t),R(this,Xi,t);return}h(this,ys).length=0,R(this,Xi,-1)}}destroy(){R(this,ys,null)}}ys=new WeakMap,bp=new WeakMap,lk=new WeakMap,Xi=new WeakMap;var ET,bV;class uC{constructor(e){N(this,ET);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:t}=Ds.platform;for(const[r,i,o={}]of e)for(const a of r){const l=a.startsWith("mac+");t&&l?(this.callbacks.set(a.slice(4),{callback:i,options:o}),this.allKeys.add(a.split("+").at(-1))):!t&&!l&&(this.callbacks.set(a,{callback:i,options:o}),this.allKeys.add(a.split("+").at(-1)))}}exec(e,t){if(!this.allKeys.has(t.key))return;const r=this.callbacks.get(q(this,ET,bV).call(this,t));if(!r)return;const{callback:i,options:{bubbles:o=!1,args:a=[],checker:l=null}}=r;l&&!l(e,t)||(i.bind(e,...a,t)(),o||$i(t))}}ET=new WeakSet,bV=function(e){e.altKey&&this.buffer.push("alt"),e.ctrlKey&&this.buffer.push("ctrl"),e.metaKey&&this.buffer.push("meta"),e.shiftKey&&this.buffer.push("shift"),this.buffer.push(e.key);const t=this.buffer.join("+");return this.buffer.length=0,t};const PT=class PT{get _colors(){const e=new Map([["CanvasText",null],["Canvas",null]]);return nue(e),Cn(this,"_colors",e)}convert(e){const t=cC(e);if(!window.matchMedia("(forced-colors: active)").matches)return t;for(const[r,i]of this._colors)if(i.every((o,a)=>o===t[a]))return PT._colorsMapping.get(r);return t}getHexCode(e){const t=this._colors.get(e);return t?yt.makeHexColor(...t):e}};ve(PT,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let nI=PT;var Tb,ml,Fb,as,Yi,Db,Eb,pa,Pb,hd,to,vp,wp,Sp,jp,ru,fd,Nm,dk,ck,Rb,uk,iu,kp,Bb,_p,su,RT,Th,Ib,hk,Cp,Wm,Mb,Ap,fk,As,Kr,Fh,Tp,Fp,pk,zb,gk,Dp,ou,Dh,mk,yk,pd,Tt,B5,rI,vV,wV,SV,hS,jV,kV,_V,iI,CV,AV,TV,FV,ua,fh,DV,EV,sI,PV,fS,oI;const Qx=class Qx{constructor(e,t,r,i,o,a,l,d,c,u,f,p,g,m,y,v){N(this,Tt);N(this,Tb,new AbortController);N(this,ml,null);N(this,Fb,null);N(this,as,new Map);N(this,Yi,new Map);N(this,Db,null);N(this,Eb,null);N(this,pa,null);N(this,Pb,null);N(this,hd,new due);N(this,to,null);N(this,vp,null);N(this,wp,null);N(this,Sp,0);N(this,jp,new Set);N(this,ru,null);N(this,fd,null);N(this,Nm,new Set);ve(this,"_editorUndoBar",null);N(this,dk,!1);N(this,ck,!1);N(this,Rb,!1);N(this,uk,null);N(this,iu,null);N(this,kp,null);N(this,Bb,null);N(this,_p,!1);N(this,su,null);N(this,RT,new lue);N(this,Th,!1);N(this,Ib,!1);N(this,hk,!1);N(this,Cp,null);N(this,Wm,null);N(this,Mb,null);N(this,Ap,null);N(this,fk,null);N(this,As,jn.NONE);N(this,Kr,new Set);N(this,Fh,null);N(this,Tp,null);N(this,Fp,null);N(this,pk,null);N(this,zb,null);N(this,gk,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});N(this,Dp,[0,0]);N(this,ou,null);N(this,Dh,null);N(this,mk,null);N(this,yk,null);N(this,pd,null);const x=this._signal=h(this,Tb).signal;R(this,Dh,e),R(this,mk,t),R(this,yk,r),R(this,Eb,i),R(this,to,o),R(this,Tp,a),R(this,zb,d),this._eventBus=l,l._on("editingaction",this.onEditingAction.bind(this),{signal:x}),l._on("pagechanging",this.onPageChanging.bind(this),{signal:x}),l._on("scalechanging",this.onScaleChanging.bind(this),{signal:x}),l._on("rotationchanging",this.onRotationChanging.bind(this),{signal:x}),l._on("setpreference",this.onSetPreference.bind(this),{signal:x}),l._on("switchannotationeditorparams",w=>this.updateParams(w.type,w.value),{signal:x}),window.addEventListener("pointerdown",()=>{R(this,Ib,!0)},{capture:!0,signal:x}),window.addEventListener("pointerup",()=>{R(this,Ib,!1)},{capture:!0,signal:x}),window.addEventListener("beforeunload",q(this,Tt,vV).bind(this),{capture:!0,signal:x}),q(this,Tt,jV).call(this),q(this,Tt,FV).call(this),q(this,Tt,iI).call(this),R(this,pa,d.annotationStorage),R(this,uk,d.filterFactory),R(this,Fp,c),R(this,Bb,u||null),R(this,dk,f),R(this,ck,p),R(this,Rb,g),R(this,fk,m||null),this.viewParameters={realScale:Wg.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=y||null,this._supportsPinchToZoom=v!==!1,o==null||o.setSidebarUiManager(this)}static get _keyboardManager(){const e=Qx.prototype,t=a=>h(a,Dh).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&a.hasSomethingToControl(),r=(a,{target:l})=>{if(l instanceof HTMLInputElement){const{type:d}=l;return d!=="text"&&d!=="number"}return!0},i=this.TRANSLATE_SMALL,o=this.TRANSLATE_BIG;return Cn(this,"_keyboardManager",new uC([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],e.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],e.delete,{checker:r}],[["Enter","mac+Enter"],e.addNewEditorFromKeyboard,{checker:(a,{target:l})=>!(l instanceof HTMLButtonElement)&&h(a,Dh).contains(l)&&!a.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(a,{target:l})=>!(l instanceof HTMLButtonElement)&&h(a,Dh).contains(document.activeElement)}],[["Escape","mac+Escape"],e.unselectAll],[["ArrowLeft","mac+ArrowLeft"],e.translateSelectedEditors,{args:[-i,0],checker:t}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-o,0],checker:t}],[["ArrowRight","mac+ArrowRight"],e.translateSelectedEditors,{args:[i,0],checker:t}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[o,0],checker:t}],[["ArrowUp","mac+ArrowUp"],e.translateSelectedEditors,{args:[0,-i],checker:t}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-o],checker:t}],[["ArrowDown","mac+ArrowDown"],e.translateSelectedEditors,{args:[0,i],checker:t}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,o],checker:t}]]))}destroy(){var e,t,r,i,o,a,l,d,c;(e=h(this,pd))==null||e.resolve(),R(this,pd,null),(t=h(this,Tb))==null||t.abort(),R(this,Tb,null),this._signal=null;for(const u of h(this,Yi).values())u.destroy();h(this,Yi).clear(),h(this,as).clear(),h(this,Nm).clear(),(r=h(this,Ap))==null||r.clear(),R(this,ml,null),h(this,Kr).clear(),h(this,hd).destroy(),(i=h(this,Eb))==null||i.destroy(),(o=h(this,to))==null||o.destroy(),(a=h(this,Tp))==null||a.destroy(),(l=h(this,su))==null||l.hide(),R(this,su,null),(d=h(this,Mb))==null||d.destroy(),R(this,Mb,null),R(this,Fb,null),h(this,iu)&&(clearTimeout(h(this,iu)),R(this,iu,null)),h(this,ou)&&(clearTimeout(h(this,ou)),R(this,ou,null)),(c=this._editorUndoBar)==null||c.destroy(),R(this,zb,null)}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return h(this,fk)}get useNewAltTextFlow(){return h(this,ck)}get useNewAltTextWhenAddingImage(){return h(this,Rb)}get hcmFilter(){return Cn(this,"hcmFilter",h(this,Fp)?h(this,uk).addHCMFilter(h(this,Fp).foreground,h(this,Fp).background):"none")}get direction(){return Cn(this,"direction",getComputedStyle(h(this,Dh)).direction)}get _highlightColors(){return Cn(this,"_highlightColors",h(this,Bb)?new Map(h(this,Bb).split(",").map(e=>(e=e.split("=").map(t=>t.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){const{_highlightColors:e}=this;if(!e)return Cn(this,"highlightColors",null);const t=new Map,r=!!h(this,Fp);for(const[i,o]of e){const a=i.endsWith("_HCM");if(r&&a){t.set(i.replace("_HCM",""),o);continue}!r&&!a&&t.set(i,o)}return Cn(this,"highlightColors",t)}get highlightColorNames(){return Cn(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;const t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),R(this,wp,e)}setMainHighlightColorPicker(e){R(this,Mb,e)}editAltText(e,t=!1){var r;(r=h(this,Eb))==null||r.editAltText(this,e,t)}hasCommentManager(){return!!h(this,to)}editComment(e,t,r,i){var o;(o=h(this,to))==null||o.showDialog(this,e,t,r,i)}selectComment(e,t){const r=h(this,Yi).get(e),i=r==null?void 0:r.getEditorByUID(t);i==null||i.toggleComment(!0,!0)}updateComment(e){var t;(t=h(this,to))==null||t.updateComment(e.getData())}updatePopupColor(e){var t;(t=h(this,to))==null||t.updatePopupColor(e)}removeComment(e){var t;(t=h(this,to))==null||t.removeComments([e.uid])}deleteComment(e,t){const r=()=>{e.comment=t},i=()=>{var o;(o=this._editorUndoBar)==null||o.show(r,"comment"),this.toggleComment(null),e.comment=null};this.addCommands({cmd:i,undo:r,mustExec:!0})}toggleComment(e,t,r=void 0){var i;(i=h(this,to))==null||i.toggleCommentPopup(e,t,r)}makeCommentColor(e,t){var r;return e&&((r=h(this,to))==null?void 0:r.makeCommentColor(e,t))||null}getCommentDialogElement(){var e;return((e=h(this,to))==null?void 0:e.dialogElement)||null}async waitForEditorsRendered(e){if(h(this,Yi).has(e-1))return;const{resolve:t,promise:r}=Promise.withResolvers(),i=o=>{o.pageNumber===e&&(this._eventBus._off("editorsrendered",i),t())};this._eventBus.on("editorsrendered",i),await r}getSignature(e){var t;(t=h(this,Tp))==null||t.getSignature({uiManager:this,editor:e})}get signatureManager(){return h(this,Tp)}switchToMode(e,t){this._eventBus.on("annotationeditormodechanged",t,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch("setpreference",{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){switch(e){case"enableNewAltTextWhenAddingImage":R(this,Rb,t);break}}onPageChanging({pageNumber:e}){R(this,Sp,e-1)}deletePage(e){for(const t of this.getEditors(e))t.remove();h(this,Yi).delete(e),h(this,Sp)===e&&R(this,Sp,0)}focusMainContainer(){h(this,Dh).focus()}findParent(e,t){for(const r of h(this,Yi).values()){const{x:i,y:o,width:a,height:l}=r.div.getBoundingClientRect();if(e>=i&&e<=i+a&&t>=o&&t<=o+l)return r}return null}disableUserSelect(e=!1){h(this,mk).classList.toggle("noUserSelect",e)}addShouldRescale(e){h(this,Nm).add(e)}removeShouldRescale(e){h(this,Nm).delete(e)}onScaleChanging({scale:e}){var t;this.commitOrRemove(),this.viewParameters.realScale=e*Wg.PDF_TO_CSS_UNITS;for(const r of h(this,Nm))r.onScaleChanging();(t=h(this,wp))==null||t.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}highlightSelection(e="",t=!1){const r=document.getSelection();if(!r||r.isCollapsed)return;const{anchorNode:i,anchorOffset:o,focusNode:a,focusOffset:l}=r,d=r.toString(),u=q(this,Tt,B5).call(this,r).closest(".textLayer"),f=this.getSelectionBoxes(u);if(!f)return;r.empty();const p=q(this,Tt,rI).call(this,u),g=h(this,As)===jn.NONE,m=()=>{const y=p==null?void 0:p.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:f,anchorNode:i,anchorOffset:o,focusNode:a,focusOffset:l,text:d});g&&this.showAllEditors("highlight",!0,!0),t&&(y==null||y.editComment())};if(g){this.switchToMode(jn.HIGHLIGHT,m);return}m()}commentSelection(e=""){this.highlightSelection(e,!0)}getAndRemoveDataFromAnnotationStorage(e){if(!h(this,pa))return null;const t=`${Gj}${e}`,r=h(this,pa).getRawValue(t);return r&&h(this,pa).remove(t),r}addToAnnotationStorage(e){!e.isEmpty()&&h(this,pa)&&!h(this,pa).has(e.id)&&h(this,pa).setValue(e.id,e)}a11yAlert(e,t=null){const r=h(this,yk);r&&(r.setAttribute("data-l10n-id",e),t?r.setAttribute("data-l10n-args",JSON.stringify(t)):r.removeAttribute("data-l10n-args"))}blur(){if(this.isShiftKeyDown=!1,h(this,_p)&&(R(this,_p,!1),q(this,Tt,hS).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:e}=document;for(const t of h(this,Kr))if(t.div.contains(e)){R(this,Wm,[t,e]),t._focusEventsAllowed=!1;break}}focus(){if(!h(this,Wm))return;const[e,t]=h(this,Wm);R(this,Wm,null),t.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}addEditListeners(){q(this,Tt,iI).call(this),this.setEditingState(!0)}removeEditListeners(){q(this,Tt,CV).call(this),this.setEditingState(!1)}dragOver(e){for(const{type:t}of e.dataTransfer.items)for(const r of h(this,fd))if(r.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect="copy",e.preventDefault();return}}drop(e){for(const t of e.dataTransfer.items)for(const r of h(this,fd))if(r.isHandlingMimeForPasting(t.type)){r.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){var r;if(e.preventDefault(),(r=h(this,ml))==null||r.commitOrRemove(),!this.hasSelection)return;const t=[];for(const i of h(this,Kr)){const o=i.serialize(!0);o&&t.push(o)}t.length!==0&&e.clipboardData.setData("application/pdfjs",JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();const{clipboardData:t}=e;for(const o of t.items)for(const a of h(this,fd))if(a.isHandlingMimeForPasting(o.type)){a.paste(o,this.currentLayer);return}let r=t.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(o){Bn(`paste: "${o.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();const i=this.currentLayer;try{const o=[];for(const d of r){const c=await i.deserialize(d);if(!c)return;o.push(c)}const a=()=>{for(const d of o)q(this,Tt,sI).call(this,d);q(this,Tt,oI).call(this,o)},l=()=>{for(const d of o)d.remove()};this.addCommands({cmd:a,undo:l,mustExec:!0})}catch(o){Bn(`paste: "${o.message}".`)}}keydown(e){!this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!0),h(this,As)!==jn.NONE&&!this.isEditorHandlingKeyboard&&Qx._keyboardManager.exec(this,e)}keyup(e){this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!1,h(this,_p)&&(R(this,_p,!1),q(this,Tt,hS).call(this,"main_toolbar")))}onEditingAction({name:e}){switch(e){case"undo":case"redo":case"delete":case"selectAll":this[e]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu");break}}updatePageIndex(e,t){for(const i of this.getEditors(e))i.pageIndex=t;const r=h(this,Db).get(e);r&&(r.pageIndex=t,h(this,Yi).set(t,r),h(this,Th)?r.enable():r.disable())}startUpdatePages(){R(this,Db,new Map(h(this,Yi))),h(this,Yi).clear()}endUpdatePages(){R(this,Db,null)}clonePage(e,t){for(const r of this.getEditors(e)){const i=r.serialize(r.mode!==jn.HIGHLIGHT);i&&(i.pageIndex=t,i.id=this.getId(),i.isClone=!0,delete i.popupRef,h(this,pa).setValue(i.id,i))}}findClonesForPage(e){const t=[],{pageIndex:r}=e;for(const[i,o]of h(this,pa))o.pageIndex===r&&o.isClone&&(h(this,pa).remove(i),t.push(e.deserialize(o).then(a=>{a&&(a.isClone=!0,e.addOrRebuild(a))})));return Promise.all(t)}setEditingState(e){e?(q(this,Tt,kV).call(this),q(this,Tt,AV).call(this),q(this,Tt,ua).call(this,{isEditing:h(this,As)!==jn.NONE,isEmpty:q(this,Tt,fS).call(this),hasSomethingToUndo:h(this,hd).hasSomethingToUndo(),hasSomethingToRedo:h(this,hd).hasSomethingToRedo(),hasSelectedEditor:!1})):(q(this,Tt,_V).call(this),q(this,Tt,TV).call(this),q(this,Tt,ua).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!h(this,fd)){R(this,fd,e);for(const t of h(this,fd))q(this,Tt,fh).call(this,t.defaultPropertiesToUpdate)}}getId(){return h(this,RT).id}get currentLayer(){return h(this,Yi).get(h(this,Sp))}getLayer(e){return h(this,Yi).get(e)}get currentPageIndex(){return h(this,Sp)}addLayer(e){h(this,Yi).set(e.pageIndex,e),h(this,Th)?e.enable():e.disable()}removeLayer(e){h(this,Yi).delete(e.pageIndex)}async updateMode(e,t=null,r=!1,i=!1,o=!1,a=!1){var l,d,c,u,f,p;if(h(this,As)!==e&&!(h(this,pd)&&(await h(this,pd).promise,!h(this,pd)))){if(R(this,pd,Promise.withResolvers()),(l=h(this,wp))==null||l.commitOrRemove(),h(this,As)===jn.POPUP&&((d=h(this,to))==null||d.hideSidebar()),(c=h(this,to))==null||c.destroyPopup(),R(this,As,e),e===jn.NONE){this.setEditingState(!1),q(this,Tt,EV).call(this);for(const g of h(this,as).values())g.hideStandaloneCommentButton();(u=this._editorUndoBar)==null||u.hide(),this.toggleComment(null),h(this,pd).resolve();return}for(const g of h(this,as).values())g.addStandaloneCommentButton();e===jn.SIGNATURE&&await((f=h(this,Tp))==null?void 0:f.loadSignatures()),r&&Yo.clearPointerType(),this.setEditingState(!0),await q(this,Tt,DV).call(this),this.unselectAll();for(const g of h(this,Yi).values())g.updateMode(e);if(e===jn.POPUP){h(this,Fb)||R(this,Fb,await h(this,zb).getAnnotationsByType(new Set(h(this,fd).map(y=>y._editorType))));const g=new Set,m=[];for(const y of h(this,as).values()){const{annotationElementId:v,hasComment:x,deleted:w}=y;v&&g.add(v),x&&!w&&m.push(y.getData())}for(const y of h(this,Fb)){const{id:v,popupRef:x,contentsObj:w}=y;x&&(w!=null&&w.str)&&!g.has(v)&&!h(this,jp).has(v)&&m.push(y)}(p=h(this,to))==null||p.showSidebar(m)}if(!t){i&&this.addNewEditorFromKeyboard(),h(this,pd).resolve();return}for(const g of h(this,as).values())g.uid===t?(this.setSelected(g),a?g.editComment():o?g.enterInEditMode():g.focus()):g.unselect();h(this,pd).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==h(this,As)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...e})}updateParams(e,t){if(h(this,fd)){switch(e){case Wn.CREATE:this.currentLayer.addNewEditor(t);return;case Wn.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(h(this,pk)||R(this,pk,new Map)).set(e,t),this.showAllEditors("highlight",t);break}if(this.hasSelection)for(const r of h(this,Kr))r.updateParams(e,t);else for(const r of h(this,fd))r.updateDefaultParams(e,t)}}showAllEditors(e,t,r=!1){var o;for(const a of h(this,as).values())a.editorType===e&&a.show(t);(((o=h(this,pk))==null?void 0:o.get(Wn.HIGHLIGHT_SHOW_ALL))??!0)!==t&&q(this,Tt,fh).call(this,[[Wn.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(h(this,hk)!==e){R(this,hk,e);for(const t of h(this,Yi).values())e?t.disableClick():t.enableClick(),t.div.classList.toggle("waiting",e)}}*getEditors(e){for(const t of h(this,as).values())t.pageIndex===e&&(yield t)}getEditor(e){return h(this,as).get(e)}addEditor(e){h(this,as).set(e.id,e)}removeEditor(e){var t,r;e.div.contains(document.activeElement)&&(h(this,iu)&&clearTimeout(h(this,iu)),R(this,iu,setTimeout(()=>{this.focusMainContainer(),R(this,iu,null)},0))),h(this,as).delete(e.id),e.annotationElementId&&((t=h(this,Ap))==null||t.delete(e.annotationElementId)),this.unselect(e),(!e.annotationElementId||!h(this,jp).has(e.annotationElementId))&&((r=h(this,pa))==null||r.remove(e.id))}addDeletedAnnotationElement(e){h(this,jp).add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return h(this,jp).has(e)}removeDeletedAnnotationElement(e){h(this,jp).delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}setActiveEditor(e){h(this,ml)!==e&&(R(this,ml,e),e&&q(this,Tt,fh).call(this,e.propertiesToUpdate))}updateUI(e){h(this,Tt,PV)===e&&q(this,Tt,fh).call(this,e.propertiesToUpdate)}updateUIForDefaultProperties(e){q(this,Tt,fh).call(this,e.defaultPropertiesToUpdate)}toggleSelected(e){if(h(this,Kr).has(e)){h(this,Kr).delete(e),e.unselect(),q(this,Tt,ua).call(this,{hasSelectedEditor:this.hasSelection});return}h(this,Kr).add(e),e.select(),q(this,Tt,fh).call(this,e.propertiesToUpdate),q(this,Tt,ua).call(this,{hasSelectedEditor:!0})}setSelected(e){var t,r;this.updateToolbar({mode:e.mode,editId:e.uid}),(t=h(this,wp))==null||t.commitOrRemove();for(const i of h(this,Kr))i!==e&&i.unselect();(r=h(this,to))==null||r.destroyPopup(),h(this,Kr).clear(),h(this,Kr).add(e),e.select(),q(this,Tt,fh).call(this,e.propertiesToUpdate),q(this,Tt,ua).call(this,{hasSelectedEditor:!0})}isSelected(e){return h(this,Kr).has(e)}get firstSelectedEditor(){return h(this,Kr).values().next().value}unselect(e){e.unselect(),h(this,Kr).delete(e),q(this,Tt,ua).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return h(this,Kr).size!==0}get isEnterHandled(){return h(this,Kr).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){var e;h(this,hd).undo(),q(this,Tt,ua).call(this,{hasSomethingToUndo:h(this,hd).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:q(this,Tt,fS).call(this)}),(e=this._editorUndoBar)==null||e.hide()}redo(){h(this,hd).redo(),q(this,Tt,ua).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:h(this,hd).hasSomethingToRedo(),isEmpty:q(this,Tt,fS).call(this)})}addCommands(e){h(this,hd).add(e),q(this,Tt,ua).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:q(this,Tt,fS).call(this)})}cleanUndoStack(e){h(this,hd).cleanType(e)}delete(){var o;this.commitOrRemove();const e=(o=this.currentLayer)==null?void 0:o.endDrawingSession(!0);if(!this.hasSelection&&!e)return;const t=e?[e]:[...h(this,Kr)],r=()=>{var a;(a=this._editorUndoBar)==null||a.show(i,t.length===1?t[0].editorType:t.length);for(const l of t)l.remove()},i=()=>{for(const a of t)q(this,Tt,sI).call(this,a)};this.addCommands({cmd:r,undo:i,mustExec:!0})}commitOrRemove(){var e;(e=h(this,ml))==null||e.commitOrRemove()}hasSomethingToControl(){return h(this,ml)||this.hasSelection}selectAll(){for(const e of h(this,Kr))e.commit();q(this,Tt,oI).call(this,h(this,as).values())}unselectAll(){var e,t;if(!(h(this,ml)&&(h(this,ml).commitOrRemove(),h(this,As)!==jn.NONE))&&!((e=h(this,wp))!=null&&e.commitOrRemove())&&((t=h(this,to))==null||t.destroyPopup(),!!this.hasSelection)){for(const r of h(this,Kr))r.unselect();h(this,Kr).clear(),q(this,Tt,ua).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(e,t,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;h(this,Dp)[0]+=e,h(this,Dp)[1]+=t;const[i,o]=h(this,Dp),a=[...h(this,Kr)],l=1e3;h(this,ou)&&clearTimeout(h(this,ou)),R(this,ou,setTimeout(()=>{R(this,ou,null),h(this,Dp)[0]=h(this,Dp)[1]=0,this.addCommands({cmd:()=>{for(const d of a)h(this,as).has(d.id)&&(d.translateInPage(i,o),d.translationDone())},undo:()=>{for(const d of a)h(this,as).has(d.id)&&(d.translateInPage(-i,-o),d.translationDone())},mustExec:!1})},l));for(const d of a)d.translateInPage(e,t),d.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),R(this,ru,new Map);for(const e of h(this,Kr))h(this,ru).set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!h(this,ru))return!1;this.disableUserSelect(!1);const e=h(this,ru);R(this,ru,null);let t=!1;for(const[{x:i,y:o,pageIndex:a},l]of e)l.newX=i,l.newY=o,l.newPageIndex=a,t||(t=i!==l.savedX||o!==l.savedY||a!==l.savedPageIndex);if(!t)return!1;const r=(i,o,a,l)=>{if(h(this,as).has(i.id)){const d=h(this,Yi).get(l);d?i._setParentAndPosition(d,o,a):(i.pageIndex=l,i.x=o,i.y=a)}};return this.addCommands({cmd:()=>{for(const[i,{newX:o,newY:a,newPageIndex:l}]of e)r(i,o,a,l)},undo:()=>{for(const[i,{savedX:o,savedY:a,savedPageIndex:l}]of e)r(i,o,a,l)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(h(this,ru))for(const r of h(this,ru).keys())r.drag(e,t)}rebuild(e){if(e.parent===null){const t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){var e;return((e=this.getActive())==null?void 0:e.shouldGetKeyboardEvents())||h(this,Kr).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return h(this,ml)===e}getActive(){return h(this,ml)}getMode(){return h(this,As)}isEditingMode(){return h(this,As)!==jn.NONE}get imageManager(){return Cn(this,"imageManager",new tI)}getSelectionBoxes(e){if(!e)return null;const t=document.getSelection();for(let c=0,u=t.rangeCount;c({x:(u-i)/a,y:1-(c+f-r)/o,width:p/a,height:f/o});break;case"180":l=(c,u,f,p)=>({x:1-(c+f-r)/o,y:1-(u+p-i)/a,width:f/o,height:p/a});break;case"270":l=(c,u,f,p)=>({x:1-(u+p-i)/a,y:(c-r)/o,width:p/a,height:f/o});break;default:l=(c,u,f,p)=>({x:(c-r)/o,y:(u-i)/a,width:f/o,height:p/a});break}const d=[];for(let c=0,u=t.rangeCount;c{p.type==="pointerup"&&p.button!==0||(c.abort(),d==null||d.toggleDrawing(!0),p.type==="pointerup"&&q(this,Tt,hS).call(this,"main_toolbar"))};window.addEventListener("pointerup",f,{signal:u}),window.addEventListener("blur",f,{signal:u})}else d==null||d.toggleDrawing(!0),q(this,Tt,hS).call(this,"main_toolbar")}},hS=function(e=""){h(this,As)===jn.HIGHLIGHT?this.highlightSelection(e):h(this,dk)&&q(this,Tt,wV).call(this)},jV=function(){document.addEventListener("selectionchange",q(this,Tt,SV).bind(this),{signal:this._signal})},kV=function(){if(h(this,kp))return;R(this,kp,new AbortController);const e=this.combinedSignal(h(this,kp));window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})},_V=function(){var e;(e=h(this,kp))==null||e.abort(),R(this,kp,null)},iI=function(){if(h(this,Cp))return;R(this,Cp,new AbortController);const e=this.combinedSignal(h(this,Cp));window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})},CV=function(){var e;(e=h(this,Cp))==null||e.abort(),R(this,Cp,null)},AV=function(){if(h(this,vp))return;R(this,vp,new AbortController);const e=this.combinedSignal(h(this,vp));document.addEventListener("copy",this.copy.bind(this),{signal:e}),document.addEventListener("cut",this.cut.bind(this),{signal:e}),document.addEventListener("paste",this.paste.bind(this),{signal:e})},TV=function(){var e;(e=h(this,vp))==null||e.abort(),R(this,vp,null)},FV=function(){const e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})},ua=function(e){Object.entries(e).some(([r,i])=>h(this,gk)[r]!==i)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(h(this,gk),e)}),h(this,As)===jn.HIGHLIGHT&&e.hasSelectedEditor===!1&&q(this,Tt,fh).call(this,[[Wn.HIGHLIGHT_FREE,!0]]))},fh=function(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})},DV=async function(){if(!h(this,Th)){R(this,Th,!0);const e=[];for(const t of h(this,Yi).values())e.push(t.enable());await Promise.all(e);for(const t of h(this,as).values())t.enable()}},EV=function(){if(this.unselectAll(),h(this,Th)){R(this,Th,!1);for(const e of h(this,Yi).values())e.disable();for(const e of h(this,as).values())e.disable()}},sI=function(e){const t=h(this,Yi).get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))},PV=function(){let e=null;for(e of h(this,Kr));return e},fS=function(){if(h(this,as).size===0)return!0;if(h(this,as).size===1)for(const e of h(this,as).values())return e.isEmpty();return!1},oI=function(e){for(const t of h(this,Kr))t.unselect();h(this,Kr).clear();for(const t of e)t.isEmpty()||(h(this,Kr).add(t),t.select());q(this,Tt,ua).call(this,{hasSelectedEditor:this.hasSelection})},ve(Qx,"TRANSLATE_SMALL",1),ve(Qx,"TRANSLATE_BIG",10);let _0=Qx;var no,au,dc,Ob,lu,yl,Lb,du,Ha,Eh,Um,cu,Ep,Cc,pS,I5;const ha=class ha{constructor(e){N(this,Cc);N(this,no,null);N(this,au,!1);N(this,dc,null);N(this,Ob,null);N(this,lu,null);N(this,yl,null);N(this,Lb,!1);N(this,du,null);N(this,Ha,null);N(this,Eh,null);N(this,Um,null);N(this,cu,!1);R(this,Ha,e),R(this,cu,e._uiManager.useNewAltTextFlow),h(ha,Ep)||R(ha,Ep,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(e){ha._l10n??(ha._l10n=e)}async render(){const e=R(this,dc,document.createElement("button"));e.className="altText",e.tabIndex="0";const t=R(this,Ob,document.createElement("span"));e.append(t),h(this,cu)?(e.classList.add("new"),e.setAttribute("data-l10n-id",h(ha,Ep).missing),t.setAttribute("data-l10n-id",h(ha,Ep)["missing-label"])):(e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const r=h(this,Ha)._uiManager._signal;e.addEventListener("contextmenu",Hd,{signal:r}),e.addEventListener("pointerdown",o=>o.stopPropagation(),{signal:r});const i=o=>{o.preventDefault(),h(this,Ha)._uiManager.editAltText(h(this,Ha)),h(this,cu)&&h(this,Ha)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:h(this,Cc,pS)}})};return e.addEventListener("click",i,{capture:!0,signal:r}),e.addEventListener("keydown",o=>{o.target===e&&o.key==="Enter"&&(R(this,Lb,!0),i(o))},{signal:r}),await q(this,Cc,I5).call(this),e}finish(){h(this,dc)&&(h(this,dc).focus({focusVisible:h(this,Lb)}),R(this,Lb,!1))}isEmpty(){return h(this,cu)?h(this,no)===null:!h(this,no)&&!h(this,au)}hasData(){return h(this,cu)?h(this,no)!==null||!!h(this,Eh):this.isEmpty()}get guessedText(){return h(this,Eh)}async setGuessedText(e){h(this,no)===null&&(R(this,Eh,e),R(this,Um,await ha._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e})),q(this,Cc,I5).call(this))}toggleAltTextBadge(e=!1){var t;if(!h(this,cu)||h(this,no)){(t=h(this,du))==null||t.remove(),R(this,du,null);return}if(!h(this,du)){const r=R(this,du,document.createElement("div"));r.className="noAltTextBadge",h(this,Ha).div.append(r)}h(this,du).classList.toggle("hidden",!e)}serialize(e){let t=h(this,no);return!e&&h(this,Eh)===t&&(t=h(this,Um)),{altText:t,decorative:h(this,au),guessedText:h(this,Eh),textWithDisclaimer:h(this,Um)}}get data(){return{altText:h(this,no),decorative:h(this,au)}}set data({altText:e,decorative:t,guessedText:r,textWithDisclaimer:i,cancel:o=!1}){r&&(R(this,Eh,r),R(this,Um,i)),!(h(this,no)===e&&h(this,au)===t)&&(o||(R(this,no,e),R(this,au,t)),q(this,Cc,I5).call(this))}toggle(e=!1){h(this,dc)&&(!e&&h(this,yl)&&(clearTimeout(h(this,yl)),R(this,yl,null)),h(this,dc).disabled=!e)}shown(){h(this,Ha)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:h(this,Cc,pS)}})}destroy(){var e,t;(e=h(this,dc))==null||e.remove(),R(this,dc,null),R(this,Ob,null),R(this,lu,null),(t=h(this,du))==null||t.remove(),R(this,du,null)}};no=new WeakMap,au=new WeakMap,dc=new WeakMap,Ob=new WeakMap,lu=new WeakMap,yl=new WeakMap,Lb=new WeakMap,du=new WeakMap,Ha=new WeakMap,Eh=new WeakMap,Um=new WeakMap,cu=new WeakMap,Ep=new WeakMap,Cc=new WeakSet,pS=function(){return h(this,no)&&"added"||h(this,no)===null&&this.guessedText&&"review"||"missing"},I5=async function(){var i,o,a;const e=h(this,dc);if(!e)return;if(h(this,cu)){if(e.classList.toggle("done",!!h(this,no)),e.setAttribute("data-l10n-id",h(ha,Ep)[h(this,Cc,pS)]),(i=h(this,Ob))==null||i.setAttribute("data-l10n-id",h(ha,Ep)[`${h(this,Cc,pS)}-label`]),!h(this,no)){(o=h(this,lu))==null||o.remove();return}}else{if(!h(this,no)&&!h(this,au)){e.classList.remove("done"),(a=h(this,lu))==null||a.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let t=h(this,lu);if(!t){R(this,lu,t=document.createElement("span")),t.className="tooltip",t.setAttribute("role","tooltip"),t.id=`alt-text-tooltip-${h(this,Ha).id}`;const l=100,d=h(this,Ha)._uiManager._signal;d.addEventListener("abort",()=>{clearTimeout(h(this,yl)),R(this,yl,null)},{once:!0}),e.addEventListener("mouseenter",()=>{R(this,yl,setTimeout(()=>{R(this,yl,null),h(this,lu).classList.add("show"),h(this,Ha)._reportTelemetry({action:"alt_text_tooltip"})},l))},{signal:d}),e.addEventListener("mouseleave",()=>{var c;h(this,yl)&&(clearTimeout(h(this,yl)),R(this,yl,null)),(c=h(this,lu))==null||c.classList.remove("show")},{signal:d})}h(this,au)?t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(t.removeAttribute("data-l10n-id"),t.textContent=h(this,no)),t.parentNode||e.append(t);const r=h(this,Ha).getElementForAltText();r==null||r.setAttribute("aria-describedby",t.id)},N(ha,Ep,null),ve(ha,"_l10n",null);let vT=ha;var wo,gd,Hm,mi,xk,Pp,md,Rp,Bp,qm,bk,aI;class V2{constructor(e){N(this,bk);N(this,wo,null);N(this,gd,null);N(this,Hm,!1);N(this,mi,null);N(this,xk,null);N(this,Pp,null);N(this,md,null);N(this,Rp,null);N(this,Bp,!1);N(this,qm,null);R(this,mi,e)}renderForToolbar(){const e=R(this,gd,document.createElement("button"));return e.className="comment",q(this,bk,aI).call(this,e,!1)}renderForStandalone(){const e=R(this,wo,document.createElement("button"));e.className="annotationCommentButton";const t=h(this,mi).commentButtonPosition;if(t){const{style:r}=e;r.insetInlineEnd=`calc(${100*(h(this,mi)._uiManager.direction==="ltr"?1-t[0]:t[0])}% - var(--comment-button-dim))`,r.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;const i=h(this,mi).commentButtonColor;i&&(r.backgroundColor=i)}return q(this,bk,aI).call(this,e,!0)}focusButton(){setTimeout(()=>{var e;(e=h(this,wo)??h(this,gd))==null||e.focus()},0)}onUpdatedColor(){if(!h(this,wo))return;const e=h(this,mi).commentButtonColor;e&&(h(this,wo).style.backgroundColor=e),h(this,mi)._uiManager.updatePopupColor(h(this,mi))}get commentButtonWidth(){var e;return(((e=h(this,wo))==null?void 0:e.getBoundingClientRect().width)??0)/h(this,mi).parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(h(this,qm))return h(this,qm);if(!h(this,wo))return null;const{x:e,y:t,height:r}=h(this,wo).getBoundingClientRect(),{x:i,y:o,width:a,height:l}=h(this,mi).parent.boundingClientRect;return[(e-i)/a,(t+r-o)/l]}set commentPopupPositionInLayer(e){R(this,qm,e)}hasDefaultPopupPosition(){return h(this,qm)===null}removeStandaloneCommentButton(){var e;(e=h(this,wo))==null||e.remove(),R(this,wo,null)}removeToolbarCommentButton(){var e;(e=h(this,gd))==null||e.remove(),R(this,gd,null)}setCommentButtonStates({selected:e,hasPopup:t}){h(this,wo)&&(h(this,wo).classList.toggle("selected",e),h(this,wo).ariaExpanded=t)}edit(e){const t=this.commentPopupPositionInLayer;let r,i;if(t)[r,i]=t;else{[r,i]=h(this,mi).commentButtonPosition;const{width:u,height:f,x:p,y:g}=h(this,mi);r=p+r*u,i=g+i*f}const o=h(this,mi).parent.boundingClientRect,{x:a,y:l,width:d,height:c}=o;h(this,mi)._uiManager.editComment(h(this,mi),a+r*d,l+i*c,{...e,parentDimensions:o})}finish(){h(this,gd)&&(h(this,gd).focus({focusVisible:h(this,Hm)}),R(this,Hm,!1))}isDeleted(){return h(this,Bp)||h(this,md)===""}isEmpty(){return h(this,md)===null}hasBeenEdited(){return this.isDeleted()||h(this,md)!==h(this,xk)}serialize(){return this.data}get data(){return{text:h(this,md),richText:h(this,Pp),date:h(this,Rp),deleted:this.isDeleted()}}set data(e){if(e!==h(this,md)&&R(this,Pp,null),e===null){R(this,md,""),R(this,Bp,!0);return}R(this,md,e),R(this,Rp,new Date),R(this,Bp,!1)}restoreData({text:e,richText:t,date:r}){R(this,md,e),R(this,Pp,t),R(this,Rp,r),R(this,Bp,!1)}setInitialText(e,t=null){R(this,xk,e),this.data=e,R(this,Rp,null),R(this,Pp,t)}shown(){}destroy(){var e,t;(e=h(this,gd))==null||e.remove(),R(this,gd,null),(t=h(this,wo))==null||t.remove(),R(this,wo,null),R(this,md,""),R(this,Pp,null),R(this,Rp,null),R(this,mi,null),R(this,Hm,!1),R(this,Bp,!1)}}wo=new WeakMap,gd=new WeakMap,Hm=new WeakMap,mi=new WeakMap,xk=new WeakMap,Pp=new WeakMap,md=new WeakMap,Rp=new WeakMap,Bp=new WeakMap,qm=new WeakMap,bk=new WeakSet,aI=function(e,t){if(!h(this,mi)._uiManager.hasCommentManager())return null;e.tabIndex="0",e.ariaHasPopup="dialog",t?(e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(e.ariaControlsElements=[h(this,mi)._uiManager.getCommentDialogElement()],e.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const r=h(this,mi)._uiManager._signal;if(!(r instanceof AbortSignal)||r.aborted)return e;e.addEventListener("contextmenu",Hd,{signal:r}),t&&(e.addEventListener("focusin",o=>{h(this,mi)._focusEventsAllowed=!1,$i(o)},{capture:!0,signal:r}),e.addEventListener("focusout",o=>{h(this,mi)._focusEventsAllowed=!0,$i(o)},{capture:!0,signal:r})),e.addEventListener("pointerdown",o=>o.stopPropagation(),{signal:r});const i=o=>{o.preventDefault(),e===h(this,gd)?this.edit():h(this,mi).toggleComment(!0)};return e.addEventListener("click",i,{capture:!0,signal:r}),e.addEventListener("keydown",o=>{o.target===e&&o.key==="Enter"&&(R(this,Hm,!0),i(o))},{signal:r}),e.addEventListener("pointerenter",()=>{h(this,mi).toggleComment(!1,!0)},{signal:r}),e.addEventListener("pointerleave",()=>{h(this,mi).toggleComment(!1,!1)},{signal:r}),e};var Nb,Vm,vk,wk,Sk,jk,kk,Ph,Gm,Rh,Km,Bh,Ug,RV,BV,IV;const U3=class U3{constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:r=null,onPinchStart:i=null,onPinching:o=null,onPinchEnd:a=null,signal:l}){N(this,Ug);N(this,Nb);N(this,Vm,!1);N(this,vk,null);N(this,wk);N(this,Sk);N(this,jk);N(this,kk);N(this,Ph,null);N(this,Gm);N(this,Rh,null);N(this,Km);N(this,Bh,null);R(this,Nb,e),R(this,vk,r),R(this,wk,t),R(this,Sk,i),R(this,jk,o),R(this,kk,a),R(this,Km,new AbortController),R(this,Gm,AbortSignal.any([l,h(this,Km).signal])),e.addEventListener("touchstart",q(this,Ug,RV).bind(this),{passive:!1,signal:h(this,Gm)})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Lu.pixelRatio}destroy(){var e,t;(e=h(this,Km))==null||e.abort(),R(this,Km,null),(t=h(this,Ph))==null||t.abort(),R(this,Ph,null)}};Nb=new WeakMap,Vm=new WeakMap,vk=new WeakMap,wk=new WeakMap,Sk=new WeakMap,jk=new WeakMap,kk=new WeakMap,Ph=new WeakMap,Gm=new WeakMap,Rh=new WeakMap,Km=new WeakMap,Bh=new WeakMap,Ug=new WeakSet,RV=function(e){var i,o,a;if((i=h(this,wk))!=null&&i.call(this))return;if(e.touches.length===1){if(h(this,Ph))return;const l=R(this,Ph,new AbortController),d=AbortSignal.any([h(this,Gm),l.signal]),c=h(this,Nb),u={capture:!0,signal:d,passive:!1},f=p=>{var g;p.pointerType==="touch"&&((g=h(this,Ph))==null||g.abort(),R(this,Ph,null))};c.addEventListener("pointerdown",p=>{p.pointerType==="touch"&&($i(p),f(p))},u),c.addEventListener("pointerup",f,u),c.addEventListener("pointercancel",f,u);return}if(!h(this,Bh)){R(this,Bh,new AbortController);const l=AbortSignal.any([h(this,Gm),h(this,Bh).signal]),d=h(this,Nb),c={signal:l,capture:!1,passive:!1};d.addEventListener("touchmove",q(this,Ug,BV).bind(this),c);const u=q(this,Ug,IV).bind(this);d.addEventListener("touchend",u,c),d.addEventListener("touchcancel",u,c),c.capture=!0,d.addEventListener("pointerdown",$i,c),d.addEventListener("pointermove",$i,c),d.addEventListener("pointercancel",$i,c),d.addEventListener("pointerup",$i,c),(o=h(this,Sk))==null||o.call(this)}if($i(e),e.touches.length!==2||(a=h(this,vk))!=null&&a.call(this)){R(this,Rh,null);return}let[t,r]=e.touches;t.identifier>r.identifier&&([t,r]=[r,t]),R(this,Rh,{touch0X:t.screenX,touch0Y:t.screenY,touch1X:r.screenX,touch1Y:r.screenY})},BV=function(e){var _;if(!h(this,Rh)||e.touches.length!==2)return;$i(e);let[t,r]=e.touches;t.identifier>r.identifier&&([t,r]=[r,t]);const{screenX:i,screenY:o}=t,{screenX:a,screenY:l}=r,d=h(this,Rh),{touch0X:c,touch0Y:u,touch1X:f,touch1Y:p}=d,g=f-c,m=p-u,y=a-i,v=l-o,x=Math.hypot(y,v)||1,w=Math.hypot(g,m)||1;if(!h(this,Vm)&&Math.abs(w-x)<=U3.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(d.touch0X=i,d.touch0Y=o,d.touch1X=a,d.touch1Y=l,!h(this,Vm)){R(this,Vm,!0);return}const S=[(i+a)/2,(o+l)/2];(_=h(this,jk))==null||_.call(this,S,w,x)},IV=function(e){var t;e.touches.length>=2||(h(this,Bh)&&(h(this,Bh).abort(),R(this,Bh,null),(t=h(this,kk))==null||t.call(this)),h(this,Rh)&&($i(e),R(this,Rh,null),R(this,Vm,!1)))};let wT=U3;var Xm,cc,Pi,Xr,Ih,Wb,Ip,_k,So,Ym,Mh,yd,Mp,Ck,Qm,xl,Ak,$m,zh,uu,Ub,Hb,xd,Zm,Tk,BT,ln,lI,Fk,dI,M5,MV,zV,cI,z5,uI,OV,LV,NV,hI,WV,fI,UV,HV,qV,pI,gS;const En=class En{constructor(e){N(this,ln);N(this,Xm,null);N(this,cc,null);N(this,Pi,null);N(this,Xr,null);N(this,Ih,null);N(this,Wb,!1);N(this,Ip,null);N(this,_k,"");N(this,So,null);N(this,Ym,null);N(this,Mh,null);N(this,yd,null);N(this,Mp,null);N(this,Ck,"");N(this,Qm,!1);N(this,xl,null);N(this,Ak,!1);N(this,$m,!1);N(this,zh,!1);N(this,uu,null);N(this,Ub,0);N(this,Hb,0);N(this,xd,null);N(this,Zm,null);ve(this,"isSelected",!1);ve(this,"_isCopy",!1);ve(this,"_editToolbar",null);ve(this,"_initialOptions",Object.create(null));ve(this,"_initialData",null);ve(this,"_isVisible",!0);ve(this,"_uiManager",null);ve(this,"_focusEventsAllowed",!0);N(this,Tk,!1);N(this,BT,En._zIndex++);this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;const{rotation:t,rawDims:{pageWidth:r,pageHeight:i,pageX:o,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[r,i],this.pageTranslation=[o,a];const[l,d]=this.parentDimensions;this.x=e.x/l,this.y=e.y/d,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const e=En.prototype._resizeWithKeyboard,t=_0.TRANSLATE_SMALL,r=_0.TRANSLATE_BIG;return Cn(this,"_resizerKeyboardManager",new uC([[["ArrowLeft","mac+ArrowLeft"],e,{args:[-t,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-r,0]}],[["ArrowRight","mac+ArrowRight"],e,{args:[t,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[r,0]}],[["ArrowUp","mac+ArrowUp"],e,{args:[0,-t]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-r]}],[["ArrowDown","mac+ArrowDown"],e,{args:[0,t]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,r]}],[["Escape","mac+Escape"],En.prototype._stopResizingWithKeyboard]]))}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Cn(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){const t=new cue({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(e,t){if(En._l10n??(En._l10n=e),En._l10nResizer||(En._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),En._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);En._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){Hr("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return h(this,Tk)}set _isDraggable(e){var t;R(this,Tk,e),(t=this.div)==null||t.classList.toggle("draggable",e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=h(this,BT)}setParent(e){var t;e!==null?(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions):(q(this,ln,gS).call(this),(t=h(this,yd))==null||t.remove(),R(this,yd,null)),this.parent=e}focusin(e){this._focusEventsAllowed&&(h(this,Qm)?R(this,Qm,!1):this.parent.setSelected(this))}focusout(e){var r;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const t=e.relatedTarget;t!=null&&t.closest(`#${this.id}`)||(e.preventDefault(),(r=this.parent)!=null&&r.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,r,i){const[o,a]=this.parentDimensions;[r,i]=this.screenToPageTranslation(r,i),this.x=(e+r)/o,this.y=(t+i)/a,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}const[r,i]=this.parentDimensions;this.setAt(e*r,t*i,this.width*r,this.height*i),this._onTranslated()}translate(e,t){q(this,ln,lI).call(this,this.parentDimensions,e,t)}translateInPage(e,t){h(this,xl)||R(this,xl,[this.x,this.y,this.width,this.height]),q(this,ln,lI).call(this,this.pageDimensions,e,t),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){h(this,xl)||R(this,xl,[this.x,this.y,this.width,this.height]);const{div:r,parentDimensions:[i,o]}=this;if(this.x+=e/i,this.y+=t/o,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:f,y:p}=this.div.getBoundingClientRect();this.parent.findNewParent(this,f,p)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:l}=this;const[d,c]=this.getBaseTranslation();a+=d,l+=c;const{style:u}=r;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*l).toFixed(2)}%`,this._onTranslating(a,l),r.scrollIntoView({block:"nearest"})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!h(this,xl)&&(h(this,xl)[0]!==this.x||h(this,xl)[1]!==this.y)}get _hasBeenResized(){return!!h(this,xl)&&(h(this,xl)[2]!==this.width||h(this,xl)[3]!==this.height)}getBaseTranslation(){const[e,t]=this.parentDimensions,{_borderLineWidth:r}=En,i=r/e,o=r/t;switch(this.rotation){case 90:return[-i,o];case 180:return[i,o];case 270:return[i,-o];default:return[-i,-o]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){const{div:{style:t},pageDimensions:[r,i]}=this;let{x:o,y:a,width:l,height:d}=this;if(l*=r,d*=i,o*=r,a*=i,this._mustFixPosition)switch(e){case 0:o=Bi(o,0,r-l),a=Bi(a,0,i-d);break;case 90:o=Bi(o,0,r-d),a=Bi(a,l,i);break;case 180:o=Bi(o,l,r),a=Bi(a,d,i);break;case 270:o=Bi(o,d,r),a=Bi(a,0,i-l);break}this.x=o/=r,this.y=a/=i;const[c,u]=this.getBaseTranslation();o+=c,a+=u,t.left=`${(100*o).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(e,t){var r;return q(r=En,Fk,dI).call(r,e,t,this.parentRotation)}pageTranslationToScreen(e,t){var r;return q(r=En,Fk,dI).call(r,e,t,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:e,pageDimensions:[t,r]}=this;return[t*e,r*e]}setDims(){const{div:{style:e},width:t,height:r}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*r).toFixed(2)}%`}getInitialTranslation(){return[0,0]}_onResized(){}static _round(e){return Math.round(e*1e4)/1e4}_onResizing(){}altTextFinish(){var e;(e=h(this,Pi))==null||e.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||h(this,$m))return this._editToolbar;this._editToolbar=new JB(this),this.div.append(this._editToolbar.render());const{toolbarButtons:e}=this;if(e)for(const[t,r]of e)await this._editToolbar.addButton(t,r);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){var e;(e=this._editToolbar)==null||e.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){var e;(e=this._editToolbar)==null||e.removeButton("comment")}removeEditToolbar(){var e,t;(e=this._editToolbar)==null||e.remove(),this._editToolbar=null,(t=h(this,Pi))==null||t.destroy()}addContainer(e){var r;const t=(r=this._editToolbar)==null?void 0:r.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return h(this,Pi)||(vT.initialize(En._l10n),R(this,Pi,new vT(this)),h(this,Xm)&&(h(this,Pi).data=h(this,Xm),R(this,Xm,null))),h(this,Pi)}get altTextData(){var e;return(e=h(this,Pi))==null?void 0:e.data}set altTextData(e){h(this,Pi)&&(h(this,Pi).data=e)}get guessedAltText(){var e;return(e=h(this,Pi))==null?void 0:e.guessedText}async setGuessedAltText(e){var t;await((t=h(this,Pi))==null?void 0:t.setGuessedText(e))}serializeAltText(e){var t;return(t=h(this,Pi))==null?void 0:t.serialize(e)}hasAltText(){return!!h(this,Pi)&&!h(this,Pi).isEmpty()}hasAltTextData(){var e;return((e=h(this,Pi))==null?void 0:e.hasData())??!1}focusCommentButton(){var e;(e=h(this,Xr))==null||e.focusButton()}addCommentButton(){return this.canAddComment?h(this,Xr)||R(this,Xr,new V2(this)):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(h(this,Ih)){this._uiManager.isEditingMode()&&h(this,Ih).classList.remove("hidden");return}this.hasComment&&(R(this,Ih,h(this,Xr).renderForStandalone()),this.div.append(h(this,Ih)))}}removeStandaloneCommentButton(){h(this,Xr).removeStandaloneCommentButton(),R(this,Ih,null)}hideStandaloneCommentButton(){var e;(e=h(this,Ih))==null||e.classList.add("hidden")}get comment(){if(!h(this,Xr))return null;const{data:{richText:e,text:t,date:r,deleted:i}}=h(this,Xr);return{text:t,richText:e,date:r,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){h(this,Xr)||R(this,Xr,new V2(this)),typeof e=="object"&&e!==null?h(this,Xr).restoreData(e):h(this,Xr).data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:r}){if(!t||(h(this,Xr)||R(this,Xr,new V2(this)),h(this,Xr).setInitialText(e,r),!this.annotationElementId))return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){var e;return(e=h(this,Xr))==null?void 0:e.hasBeenEdited()}get hasDeletedComment(){var e;return(e=h(this,Xr))==null?void 0:e.isDeleted()}get hasComment(){return!!h(this,Xr)&&!h(this,Xr).isEmpty()&&!h(this,Xr).isDeleted()}async editComment(e){h(this,Xr)||R(this,Xr,new V2(this)),h(this,Xr).edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){h(this,Xr).setSelectedButton(e)}addComment(e){if(this.hasEditedComment){const[,,,i]=e.rect,[o]=this.pageDimensions,[a]=this.pageTranslation,l=a+o+1,d=i-100,c=l+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[l,d,c,i]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){h(this,Xr).data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){var a;const e=this.div=document.createElement("div");e.setAttribute("data-editor-rotation",(360-this.rotation)%360),e.className=this.name,e.setAttribute("id",this.id),e.tabIndex=h(this,Wb)?-1:0,e.setAttribute("role","application"),this.defaultL10nId&&e.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||e.classList.add("hidden"),this.setInForeground(),q(this,ln,fI).call(this);const[t,r]=this.parentDimensions;this.parentRotation%180!==0&&(e.style.maxWidth=`${(100*r/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/r).toFixed(2)}%`);const[i,o]=this.getInitialTranslation();return this.translate(i,o),xV(this,e,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(h(this,Zm)||R(this,Zm,new wT({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:q(this,ln,OV).bind(this),onPinching:q(this,ln,LV).bind(this),onPinchEnd:q(this,ln,NV).bind(this),signal:this._uiManager._signal}))),this.addStandaloneCommentButton(),(a=this._uiManager._editorUndoBar)==null||a.hide(),e}pointerdown(e){const{isMac:t}=Ds.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(R(this,Qm,!0),this._isDraggable){q(this,ln,WV).call(this,e);return}q(this,ln,hI).call(this,e)}_onStartDragging(){}_onStopDragging(){}moveInDOM(){h(this,uu)&&clearTimeout(h(this,uu)),R(this,uu,setTimeout(()=>{var e;R(this,uu,null),(e=this.parent)==null||e.moveEditorInDOM(this)},0))}_setParentAndPosition(e,t,r){e.changeParent(this),this.x=t,this.y=r,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,r=this.rotation){const i=this.parentScale,[o,a]=this.pageDimensions,[l,d]=this.pageTranslation,c=e/i,u=t/i,f=this.x*o,p=this.y*a,g=this.width*o,m=this.height*a;switch(r){case 0:return[f+c+l,a-p-u-m+d,f+c+g+l,a-p-u+d];case 90:return[f+u+l,a-p+c+d,f+u+m+l,a-p+c+g+d];case 180:return[f-c-g+l,a-p+u+d,f-c+l,a-p+u+m+d];case 270:return[f-u-m+l,a-p-c-g+d,f-u+l,a-p-c+d];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(e,t){const[r,i,o,a]=e,l=o-r,d=a-i;switch(this.rotation){case 0:return[r,t-a,l,d];case 90:return[r,t-i,d,l];case 180:return[o,t-i,l,d];case 270:return[o,t-a,d,l];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&En._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){var e;(e=h(this,Xr))==null||e.onUpdatedColor()}getData(){const{comment:{text:e,color:t,date:r,opacity:i,deleted:o,richText:a},uid:l,pageIndex:d,creationDate:c,modificationDate:u}=this;return{id:l,pageIndex:d,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:r||u,popupRef:!o,color:t,opacity:i}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return this.isInEditMode()?!1:(this.parent.setEditingState(!1),R(this,$m,!0),!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),R(this,$m,!1),!0):!1}isInEditMode(){return h(this,$m)}shouldGetKeyboardEvents(){return h(this,zh)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:e,left:t,bottom:r,right:i}=this.getClientDimensions(),{innerHeight:o,innerWidth:a}=window;return t0&&e0}rebuild(){q(this,ln,fI).call(this)}rotate(e){}resize(){}serializeDeleted(){var e;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((e=this._initialData)==null?void 0:e.popupRef)||""}}serialize(e=!1,t=null){var r;return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:((r=this._initialData)==null?void 0:r.popupRef)||""}}static async deserialize(e,t,r){const i=new this.prototype.constructor({parent:t,id:r.getId(),uiManager:r,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});i.rotation=e.rotation,R(i,Xm,e.accessibilityData),i._isCopy=e.isCopy||!1;const[o,a]=i.pageDimensions,[l,d,c,u]=i.getRectInCurrentCoords(e.rect,a);return i.x=l/o,i.y=d/a,i.width=c/o,i.height=u/a,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var e,t,r;if((e=h(this,Mp))==null||e.abort(),R(this,Mp,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),h(this,uu)&&(clearTimeout(h(this,uu)),R(this,uu,null)),q(this,ln,gS).call(this),this.removeEditToolbar(),h(this,xd)){for(const i of h(this,xd).values())clearTimeout(i);R(this,xd,null)}this.parent=null,(t=h(this,Zm))==null||t.destroy(),R(this,Zm,null),(r=h(this,yd))==null||r.remove(),R(this,yd,null)}get isResizable(){return!1}makeResizable(){this.isResizable&&(q(this,ln,MV).call(this),h(this,So).classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction==="ltr"?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[e,t]}=this,[r,i,o,a]=this.getPDFRect();return[En._round(r+(o-r)*e),En._round(i+(a-i)*(1-t))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return h(this,Xr).commentPopupPositionInLayer}set commentPopupPosition(e){h(this,Xr).commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return h(this,Xr).hasDefaultPopupPosition()}get commentButtonWidth(){return h(this,Xr).commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){var t;(t=h(this,Xr))==null||t.setCommentButtonStates(e)}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),R(this,Mh,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const t=h(this,So).children;if(!h(this,cc)){R(this,cc,Array.from(t));const a=q(this,ln,UV).bind(this),l=q(this,ln,HV).bind(this),d=this._uiManager._signal;for(const c of h(this,cc)){const u=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",a,{signal:d}),c.addEventListener("blur",l,{signal:d}),c.addEventListener("focus",q(this,ln,qV).bind(this,u),{signal:d}),c.setAttribute("data-l10n-id",En._l10nResizer[u])}}const r=h(this,cc)[0];let i=0;for(const a of t){if(a===r)break;i++}const o=(360-this.rotation+this.parentRotation)%360/90*(h(this,cc).length/4);if(o!==i){if(oi)for(let l=0;l{var i,o;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((o=this._editToolbar)==null||o.show())});return}(t=this._editToolbar)==null||t.show(),(r=h(this,Pi))==null||r.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>{var e;return(e=this.div)==null?void 0:e.focus({preventScroll:!0})},0)}unselect(){var e,t,r,i,o;this.isSelected&&(this.isSelected=!1,(e=h(this,So))==null||e.classList.add("hidden"),(t=this.div)==null||t.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(o=h(this,Pi))==null||o.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!=="BUTTON"&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return h(this,Ak)}set isEditing(e){R(this,Ak,e),this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,t=!1){if(t){h(this,xd)||R(this,xd,new Map);const{action:r}=e;let i=h(this,xd).get(r);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(e),h(this,xd).delete(r),h(this,xd).size===0&&R(this,xd,null)},En._telemetryTimeout),h(this,xd).set(r,i);return}e.type||(e.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(e=this._isVisible){this.div.classList.toggle("hidden",!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),R(this,Wb,!1)}disable(){this.div&&(this.div.tabIndex=-1),R(this,Wb,!0)}updateFakeAnnotationElement(e){if(!h(this,yd)&&!this.deleted){R(this,yd,e.addFakeAnnotation(this));return}if(this.deleted){h(this,yd).remove(),R(this,yd,null);return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&h(this,yd).updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(".annotationContent");if(!t)t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),e.container.prepend(t);else if(t.nodeName==="CANVAS"){const r=t;t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),r.before(t)}return t}resetAnnotationElement(e){const{firstElementChild:t}=e.container;(t==null?void 0:t.nodeName)==="DIV"&&t.classList.contains("annotationContent")&&t.remove()}};Xm=new WeakMap,cc=new WeakMap,Pi=new WeakMap,Xr=new WeakMap,Ih=new WeakMap,Wb=new WeakMap,Ip=new WeakMap,_k=new WeakMap,So=new WeakMap,Ym=new WeakMap,Mh=new WeakMap,yd=new WeakMap,Mp=new WeakMap,Ck=new WeakMap,Qm=new WeakMap,xl=new WeakMap,Ak=new WeakMap,$m=new WeakMap,zh=new WeakMap,uu=new WeakMap,Ub=new WeakMap,Hb=new WeakMap,xd=new WeakMap,Zm=new WeakMap,Tk=new WeakMap,BT=new WeakMap,ln=new WeakSet,lI=function([e,t],r,i){[r,i]=this.screenToPageTranslation(r,i),this.x+=r/e,this.y+=i/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()},Fk=new WeakSet,dI=function(e,t,r){switch(r){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}},M5=function(e){switch(e){case 90:{const[t,r]=this.pageDimensions;return[0,-t/r,r/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,r]=this.pageDimensions;return[0,t/r,-r/t,0]}default:return[1,0,0,1]}},MV=function(){if(h(this,So))return;R(this,So,document.createElement("div")),h(this,So).classList.add("resizers");const e=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],t=this._uiManager._signal;for(const r of e){const i=document.createElement("div");h(this,So).append(i),i.classList.add("resizer",r),i.setAttribute("data-resizer-name",r),i.addEventListener("pointerdown",q(this,ln,zV).bind(this,r),{signal:t}),i.addEventListener("contextmenu",Hd,{signal:t}),i.tabIndex=-1}this.div.prepend(h(this,So))},zV=function(e,t){var u;t.preventDefault();const{isMac:r}=Ds.platform;if(t.button!==0||t.ctrlKey&&r)return;(u=h(this,Pi))==null||u.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,R(this,Ym,[t.screenX,t.screenY]);const o=new AbortController,a=this._uiManager.combinedSignal(o);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",q(this,ln,uI).bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",$i,{passive:!1,signal:a}),window.addEventListener("contextmenu",Hd,{signal:a}),R(this,Mh,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const l=this.parent.div.style.cursor,d=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;const c=()=>{var f;o.abort(),this.parent.togglePointerEvents(!0),(f=h(this,Pi))==null||f.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=l,this.div.style.cursor=d,q(this,ln,z5).call(this)};window.addEventListener("pointerup",c,{signal:a}),window.addEventListener("blur",c,{signal:a})},cI=function(e,t,r,i){this.width=r,this.height=i,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()},z5=function(){if(!h(this,Mh))return;const{savedX:e,savedY:t,savedWidth:r,savedHeight:i}=h(this,Mh);R(this,Mh,null);const o=this.x,a=this.y,l=this.width,d=this.height;o===e&&a===t&&l===r&&d===i||this.addCommands({cmd:q(this,ln,cI).bind(this,o,a,l,d),undo:q(this,ln,cI).bind(this,e,t,r,i),mustExec:!0})},uI=function(e,t){const[r,i]=this.parentDimensions,o=this.x,a=this.y,l=this.width,d=this.height,c=En.MIN_SIZE/r,u=En.MIN_SIZE/i,f=q(this,ln,M5).call(this,this.rotation),p=(M,I)=>[f[0]*M+f[2]*I,f[1]*M+f[3]*I],g=q(this,ln,M5).call(this,360-this.rotation),m=(M,I)=>[g[0]*M+g[2]*I,g[1]*M+g[3]*I];let y,v,x=!1,w=!1;switch(e){case"topLeft":x=!0,y=(M,I)=>[0,0],v=(M,I)=>[M,I];break;case"topMiddle":y=(M,I)=>[M/2,0],v=(M,I)=>[M/2,I];break;case"topRight":x=!0,y=(M,I)=>[M,0],v=(M,I)=>[0,I];break;case"middleRight":w=!0,y=(M,I)=>[M,I/2],v=(M,I)=>[0,I/2];break;case"bottomRight":x=!0,y=(M,I)=>[M,I],v=(M,I)=>[0,0];break;case"bottomMiddle":y=(M,I)=>[M/2,I],v=(M,I)=>[M/2,0];break;case"bottomLeft":x=!0,y=(M,I)=>[0,I],v=(M,I)=>[M,0];break;case"middleLeft":w=!0,y=(M,I)=>[0,I/2],v=(M,I)=>[M,I/2];break}const S=y(l,d),_=v(l,d);let b=p(..._);const C=En._round(o+b[0]),T=En._round(a+b[1]);let F=1,A=1,D,P;if(t.fromKeyboard)({deltaX:D,deltaY:P}=t);else{const{screenX:M,screenY:I}=t,[H,z]=h(this,Ym);[D,P]=this.screenToPageTranslation(M-H,I-z),h(this,Ym)[0]=M,h(this,Ym)[1]=I}if([D,P]=m(D/r,P/i),x){const M=Math.hypot(l,d);F=A=Math.max(Math.min(Math.hypot(_[0]-S[0]-D,_[1]-S[1]-P)/M,1/l,1/d),c/l,u/d)}else w?F=Bi(Math.abs(_[0]-S[0]-D),c,1)/l:A=Bi(Math.abs(_[1]-S[1]-P),u,1)/d;const L=En._round(l*F),W=En._round(d*A);b=p(...v(L,W));const O=C-b[0],U=T-b[1];h(this,xl)||R(this,xl,[this.x,this.y,this.width,this.height]),this.width=L,this.height=W,this.x=O,this.y=U,this.setDims(),this.fixAndSetPosition(),this._onResizing()},OV=function(){var e;R(this,Mh,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height}),(e=h(this,Pi))==null||e.toggle(!1),this.parent.togglePointerEvents(!1)},LV=function(e,t,r){let o=.7*(r/t)+1-.7;if(o===1)return;const a=q(this,ln,M5).call(this,this.rotation),l=(C,T)=>[a[0]*C+a[2]*T,a[1]*C+a[3]*T],[d,c]=this.parentDimensions,u=this.x,f=this.y,p=this.width,g=this.height,m=En.MIN_SIZE/d,y=En.MIN_SIZE/c;o=Math.max(Math.min(o,1/p,1/g),m/p,y/g);const v=En._round(p*o),x=En._round(g*o);if(v===p&&x===g)return;h(this,xl)||R(this,xl,[u,f,p,g]);const w=l(p/2,g/2),S=En._round(u+w[0]),_=En._round(f+w[1]),b=l(v/2,x/2);this.x=S-b[0],this.y=_-b[1],this.width=v,this.height=x,this.setDims(),this.fixAndSetPosition(),this._onResizing()},NV=function(){var e;(e=h(this,Pi))==null||e.toggle(!0),this.parent.togglePointerEvents(!0),q(this,ln,z5).call(this)},hI=function(e){const{isMac:t}=Ds.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)},WV=function(e){const{isSelected:t}=this;this._uiManager.setUpDragSession();let r=!1;const i=new AbortController,o=this._uiManager.combinedSignal(i),a={capture:!0,passive:!1,signal:o},l=c=>{i.abort(),R(this,Ip,null),R(this,Qm,!1),this._uiManager.endDragSession()||q(this,ln,hI).call(this,c),r&&this._onStopDragging()};t&&(R(this,Ub,e.clientX),R(this,Hb,e.clientY),R(this,Ip,e.pointerId),R(this,_k,e.pointerType),window.addEventListener("pointermove",c=>{r||(r=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:u,clientY:f,pointerId:p}=c;if(p!==h(this,Ip)){$i(c);return}const[g,m]=this.screenToPageTranslation(u-h(this,Ub),f-h(this,Hb));R(this,Ub,u),R(this,Hb,f),this._uiManager.dragSelectedEditors(g,m)},a),window.addEventListener("touchmove",$i,a),window.addEventListener("pointerdown",c=>{c.pointerType===h(this,_k)&&(h(this,Zm)||c.isPrimary)&&l(c),$i(c)},a));const d=c=>{if(!h(this,Ip)||h(this,Ip)===c.pointerId){l(c);return}$i(c)};window.addEventListener("pointerup",d,{signal:o}),window.addEventListener("blur",d,{signal:o})},fI=function(){if(h(this,Mp)||!this.div)return;R(this,Mp,new AbortController);const e=this._uiManager.combinedSignal(h(this,Mp));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})},UV=function(e){En._resizerKeyboardManager.exec(this,e)},HV=function(e){var t;h(this,zh)&&((t=e.relatedTarget)==null?void 0:t.parentNode)!==h(this,So)&&q(this,ln,gS).call(this)},qV=function(e){R(this,Ck,h(this,zh)?e:"")},pI=function(e){if(h(this,cc))for(const t of h(this,cc))t.tabIndex=e},gS=function(){R(this,zh,!1),q(this,ln,pI).call(this,-1),q(this,ln,z5).call(this)},N(En,Fk),ve(En,"_l10n",null),ve(En,"_l10nResizer",null),ve(En,"_borderLineWidth",-1),ve(En,"_colorManager",new nI),ve(En,"_zIndex",1),ve(En,"_telemetryTimeout",1e3);let xi=En;class cue extends xi{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const mN=3285377520,rd=4294901760,Xc=65535;class gI{constructor(e){this.h1=e?e&4294967295:mN,this.h2=e?e&4294967295:mN}update(e){let t,r;if(typeof e=="string"){t=new Uint8Array(e.length*2),r=0;for(let y=0,v=e.length;y>>8,t[r++]=x&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),r=t.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=r>>2,o=r-i*4,a=new Uint32Array(t.buffer,0,i);let l=0,d=0,c=this.h1,u=this.h2;const f=3432918353,p=461845907,g=f&Xc,m=p&Xc;for(let y=0;y>>17,l=l*p&rd|l*m&Xc,c^=l,c=c<<13|c>>>19,c=c*5+3864292196):(d=a[y],d=d*f&rd|d*g&Xc,d=d<<15|d>>>17,d=d*p&rd|d*m&Xc,u^=d,u=u<<13|u>>>19,u=u*5+3864292196);switch(l=0,o){case 3:l^=t[i*4+2]<<16;case 2:l^=t[i*4+1]<<8;case 1:l^=t[i*4],l=l*f&rd|l*g&Xc,l=l<<15|l>>>17,l=l*p&rd|l*m&Xc,i&1?c^=l:u^=l}this.h1=c,this.h2=u}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&rd|e*36045&Xc,t=t*4283543511&rd|((t<<16|e>>>16)*2950163797&rd)>>>16,e^=t>>>1,e=e*444984403&rd|e*60499&Xc,t=t*3301882366&rd|((t<<16|e>>>16)*3120437893&rd)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}const Xj=Object.freeze({map:null,hash:"",transfer:void 0});var Jm,ey,Oh,jo,IT,VV;class I3{constructor(){N(this,IT);N(this,Jm,!1);N(this,ey,null);N(this,Oh,null);N(this,jo,new Map);ve(this,"onSetModified",null);ve(this,"onResetModified",null);ve(this,"onAnnotationEditor",null)}getValue(e,t){const r=h(this,jo).get(e);return r===void 0?t:Object.assign(t,r)}getRawValue(e){return h(this,jo).get(e)}remove(e){var r;const t=h(this,jo).get(e);t!==void 0&&(t instanceof xi&&h(this,Oh).delete(t.annotationElementId),h(this,jo).delete(e),h(this,jo).size===0&&this.resetModified(),!h(this,jo).values().some(i=>i instanceof xi)&&((r=this.onAnnotationEditor)==null||r.call(this,null)))}setValue(e,t){var o;const r=h(this,jo).get(e);let i=!1;if(r!==void 0)for(const[a,l]of Object.entries(t))r[a]!==l&&(i=!0,r[a]=l);else i=!0,h(this,jo).set(e,t);i&&q(this,IT,VV).call(this),t instanceof xi&&((h(this,Oh)||R(this,Oh,new Map)).set(t.annotationElementId,t),(o=this.onAnnotationEditor)==null||o.call(this,t.constructor._type))}has(e){return h(this,jo).has(e)}get size(){return h(this,jo).size}resetModified(){var e;h(this,Jm)&&(R(this,Jm,!1),(e=this.onResetModified)==null||e.call(this))}get print(){return new GV(this)}get serializable(){if(h(this,jo).size===0)return Xj;const e=new Map,t=new gI,r=[],i=Object.create(null);let o=!1;for(const[a,l]of h(this,jo)){const d=l instanceof xi?l.serialize(!1,i):l;l.page&&(l.pageIndex=l.page._pageIndex,delete l.page),d&&(e.set(a,d),t.update(`${a}:${JSON.stringify(d)}`),o||(o=!!d.bitmap))}if(o)for(const a of e.values())a.bitmap&&r.push(a.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:r}:Xj}get editorStats(){let e=null;const t=new Map;let r=0,i=0;for(const o of h(this,jo).values()){if(!(o instanceof xi)){o.popup&&(o.popup.deleted?i+=1:r+=1);continue}o.isCommentDeleted?i+=1:o.hasEditedComment&&(r+=1);const a=o.telemetryFinalData;if(!a)continue;const{type:l}=a;t.has(l)||t.set(l,Object.getPrototypeOf(o).constructor),e||(e=Object.create(null));const d=e[l]||(e[l]=new Map);for(const[c,u]of Object.entries(a)){if(c==="type")continue;const f=d.getOrInsertComputed(c,D3);f.set(u,(f.get(u)??0)+1)}}if((i>0||r>0)&&(e||(e=Object.create(null)),e.comments={deleted:i,edited:r}),!e)return null;for(const[o,a]of t)e[o]=a.computeTelemetryFinalData(e[o]);return e}resetModifiedIds(){R(this,ey,null)}updateEditor(e,t){var i;const r=(i=h(this,Oh))==null?void 0:i.get(e);return r?(r.updateFromAnnotationLayer(t),!0):!1}getEditor(e){var t;return((t=h(this,Oh))==null?void 0:t.get(e))||null}get modifiedIds(){if(h(this,ey))return h(this,ey);const e=[];if(h(this,Oh))for(const r of h(this,Oh).values())r.serialize()&&e.push(r.annotationElementId);let t="";if(e.length){const r=new gI;r.update(e.join(",")),t=r.hexdigest()}return R(this,ey,{ids:new Set(e),hash:t})}[Symbol.iterator](){return h(this,jo).entries()}}Jm=new WeakMap,ey=new WeakMap,Oh=new WeakMap,jo=new WeakMap,IT=new WeakSet,VV=function(){var e;h(this,Jm)||(R(this,Jm,!0),(e=this.onSetModified)==null||e.call(this))};var Dk;class GV extends I3{constructor(t){super();N(this,Dk,Xj);const{serializable:r}=t;if(r===Xj)return;const{map:i,hash:o,transfer:a}=r,l=structuredClone(i,a?{transfer:a}:null);R(this,Dk,{map:l,hash:o,transfer:[]})}get print(){Hr("Should not call PrintAnnotationStorage.print")}get serializable(){return h(this,Dk)}get modifiedIds(){return Cn(this,"modifiedIds",{ids:new Set,hash:""})}}Dk=new WeakMap;const xx="__forcedDependency",{floor:yN,ceil:xN}=Math;function bN(n,e,t,r,i,o){n[e*4+0]=Math.min(n[e*4+0],t),n[e*4+1]=Math.min(n[e*4+1],r),n[e*4+2]=Math.max(n[e*4+2],i),n[e*4+3]=Math.max(n[e*4+3],o)}const mI=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];var qb,zp;class uue{constructor(e,t){N(this,qb);N(this,zp);R(this,qb,e),R(this,zp,t)}get length(){return h(this,qb).length}isEmpty(e){return h(this,qb)[e]===mI}minX(e){return h(this,zp)[e*4+0]/256}minY(e){return h(this,zp)[e*4+1]/256}maxX(e){return(h(this,zp)[e*4+2]+1)/256}maxY(e){return(h(this,zp)[e*4+3]+1)/256}}qb=new WeakMap,zp=new WeakMap;const vN=(n,e)=>n==null?void 0:n.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));var Lh,Wr,Si,ty,ny,ry,Zo,Ek,yI;class hue{constructor(e,t){N(this,Ek);N(this,Lh,[[1,0,0,1,0,0]]);N(this,Wr,[-1/0,-1/0,1/0,1/0]);N(this,Si,new Float64Array(hf));ve(this,"_pendingBBoxIdx",-1);N(this,ty);N(this,ny);N(this,ry);N(this,Zo);ve(this,"_savesStack",[]);ve(this,"_markedContentStack",[]);R(this,ty,e.width),R(this,ny,e.height),q(this,Ek,yI).call(this,t)}growOperationsCount(e){e>=h(this,Zo).length&&q(this,Ek,yI).call(this,e,h(this,Zo))}get clipBox(){return h(this,Wr)}save(e){return R(this,Wr,{__proto__:h(this,Wr)}),this._savesStack.push(e),this}restore(e,t){const r=Object.getPrototypeOf(h(this,Wr));if(r===null)return this;R(this,Wr,r);const i=this._savesStack.pop();return i!==void 0&&(t==null||t(i,e),h(this,Zo)[e]=h(this,Zo)[i]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){const r=this._savesStack.pop();return r!==void 0&&(t==null||t(r,e),h(this,Zo)[e]=h(this,Zo)[r]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){const r=this._markedContentStack.pop();return r!==void 0&&(t==null||t(r,e),h(this,Zo)[e]=h(this,Zo)[r]),this}pushBaseTransform(e){return h(this,Lh).push(yt.multiplyByDOMMatrix(h(this,Lh).at(-1),e.getTransform())),this}popBaseTransform(){return h(this,Lh).length>1&&h(this,Lh).pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,h(this,Si).set(hf,0)),this}recordClipBox(e,t,r,i,o,a){const l=yt.multiplyByDOMMatrix(h(this,Lh).at(-1),t.getTransform()),d=hf.slice();yt.axialAlignedBoundingBox([r,o,i,a],l,d);const c=yt.intersect(h(this,Wr),d);return c?(h(this,Wr)[0]=c[0],h(this,Wr)[1]=c[1],h(this,Wr)[2]=c[2],h(this,Wr)[3]=c[3]):(h(this,Wr)[0]=h(this,Wr)[1]=1/0,h(this,Wr)[2]=h(this,Wr)[3]=-1/0),this}recordBBox(e,t,r,i,o,a){const l=h(this,Wr);if(l[0]===1/0)return this;const d=yt.multiplyByDOMMatrix(h(this,Lh).at(-1),t.getTransform());if(l[0]===-1/0)return yt.axialAlignedBoundingBox([r,o,i,a],d,h(this,Si)),this;const c=hf.slice();return yt.axialAlignedBoundingBox([r,o,i,a],d,c),h(this,Si)[0]=Bi(c[0],l[0],h(this,Si)[0]),h(this,Si)[1]=Bi(c[1],l[1],h(this,Si)[1]),h(this,Si)[2]=Bi(c[2],h(this,Si)[2],l[2]),h(this,Si)[3]=Bi(c[3],h(this,Si)[3],l[3]),this}recordFullPageBBox(e){return h(this,Si)[0]=Math.max(0,h(this,Wr)[0]),h(this,Si)[1]=Math.max(0,h(this,Wr)[1]),h(this,Si)[2]=Math.min(h(this,ty),h(this,Wr)[2]),h(this,Si)[3]=Math.min(h(this,ny),h(this,Wr)[3]),this}recordOperation(e,t=!1,r){if(this._pendingBBoxIdx!==e)return this;const i=yN(h(this,Si)[0]*256/h(this,ty)),o=yN(h(this,Si)[1]*256/h(this,ny)),a=xN(h(this,Si)[2]*256/h(this,ty)),l=xN(h(this,Si)[3]*256/h(this,ny));if(bN(h(this,ry),e,i,o,a,l),r)for(const d of r)for(const c of d)c!==e&&bN(h(this,ry),c,i,o,a,l);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,h(this,Wr)[0]=Math.max(h(this,Wr)[0],h(this,Si)[0]),h(this,Wr)[1]=Math.max(h(this,Wr)[1],h(this,Si)[1]),h(this,Wr)[2]=Math.min(h(this,Wr)[2],h(this,Si)[2]),h(this,Wr)[3]=Math.min(h(this,Wr)[3],h(this,Si)[3])),this}take(){return new uue(h(this,Zo),h(this,ry))}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,r){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,r,i=1,o=0,a=0,l){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}}Lh=new WeakMap,Wr=new WeakMap,Si=new WeakMap,ty=new WeakMap,ny=new WeakMap,ry=new WeakMap,Zo=new WeakMap,Ek=new WeakSet,yI=function(e,t){const r=new ArrayBuffer(e*4);R(this,ry,new Uint8ClampedArray(r)),R(this,Zo,new Uint32Array(r)),t&&t.length>0?(h(this,Zo).set(t),h(this,Zo).fill(mI,t.length)):h(this,Zo).fill(mI)};var qa,Va,iy,uc,Vb,Op,Lp,ri;class fue{constructor(e,t=!1){N(this,qa,{__proto__:null});N(this,Va,{__proto__:null,transform:[],moveText:[],sameLineText:[],[xx]:[]});N(this,iy,new Map);N(this,uc,new Set);N(this,Vb,new Map);N(this,Op);N(this,Lp);N(this,ri);R(this,ri,e),t&&(R(this,Op,new Map),R(this,Lp,(r,i)=>{vN(h(this,Op),i).dependencies.add(r)}))}get clipBox(){return h(this,ri).clipBox}growOperationsCount(e){h(this,ri).growOperationsCount(e)}save(e){return R(this,qa,{__proto__:h(this,qa)}),R(this,Va,{__proto__:h(this,Va),transform:{__proto__:h(this,Va).transform},moveText:{__proto__:h(this,Va).moveText},sameLineText:{__proto__:h(this,Va).sameLineText},[xx]:{__proto__:h(this,Va)[xx]}}),h(this,ri).save(e),this}restore(e){h(this,ri).restore(e,h(this,Lp));const t=Object.getPrototypeOf(h(this,qa));return t===null?this:(R(this,qa,t),R(this,Va,Object.getPrototypeOf(h(this,Va))),this)}recordOpenMarker(e){return h(this,ri).recordOpenMarker(e,h(this,Lp)),this}getOpenMarker(){return h(this,ri).getOpenMarker()}recordCloseMarker(e){return h(this,ri).recordCloseMarker(e,h(this,Lp)),this}beginMarkedContent(e){return h(this,ri).beginMarkedContent(e),this}endMarkedContent(e){return h(this,ri).endMarkedContent(e,h(this,Lp)),this}pushBaseTransform(e){return h(this,ri).pushBaseTransform(e),this}popBaseTransform(){return h(this,ri).popBaseTransform(),this}recordSimpleData(e,t){return h(this,qa)[e]=t,this}recordIncrementalData(e,t){return h(this,Va)[e].push(t),this}resetIncrementalData(e,t){return h(this,Va)[e].length=0,this}recordNamedData(e,t){return h(this,iy).set(e,t),this}recordSimpleDataFromNamed(e,t,r){h(this,qa)[e]=h(this,iy).get(t)??r}recordFutureForcedDependency(e,t){return this.recordIncrementalData(xx,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(const t of e)t in h(this,qa)&&this.recordFutureForcedDependency(t,h(this,qa)[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const e of h(this,uc))this.recordFutureForcedDependency(xx,e);return this}resetBBox(e){return h(this,ri).resetBBox(e),this}recordClipBox(e,t,r,i,o,a){return h(this,ri).recordClipBox(e,t,r,i,o,a),this}recordBBox(e,t,r,i,o,a){return h(this,ri).recordBBox(e,t,r,i,o,a),this}recordCharacterBBox(e,t,r,i=1,o=0,a=0,l){const d=r.bbox;let c,u;if(d&&(c=d[2]!==d[0]&&d[3]!==d[1]&&h(this,Vb).get(r),c!==!1&&(u=[0,0,0,0],yt.axialAlignedBoundingBox(d,r.fontMatrix,u),(i!==1||o!==0||a!==0)&&yt.scaleMinMax([i,0,0,-i,o,a],u),c)))return this.recordBBox(e,t,u[0],u[2],u[1],u[3]);if(!l)return this.recordFullPageBBox(e);const f=l();return d&&u&&c===void 0&&(c=u[0]<=o-f.actualBoundingBoxLeft&&u[2]>=o+f.actualBoundingBoxRight&&u[1]<=a-f.actualBoundingBoxAscent&&u[3]>=a+f.actualBoundingBoxDescent,h(this,Vb).set(r,c),c)?this.recordBBox(e,t,u[0],u[2],u[1],u[3]):this.recordBBox(e,t,o-f.actualBoundingBoxLeft,o+f.actualBoundingBoxRight,a-f.actualBoundingBoxAscent,a+f.actualBoundingBoxDescent)}recordFullPageBBox(e){return h(this,ri).recordFullPageBBox(e),this}getSimpleIndex(e){return h(this,qa)[e]}recordDependencies(e,t){const r=h(this,uc),i=h(this,qa),o=h(this,Va);for(const a of t)a in h(this,qa)?r.add(i[a]):a in o&&o[a].forEach(r.add,r);return this}recordNamedDependency(e,t){return h(this,iy).has(t)&&h(this,uc).add(h(this,iy).get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[xx]),h(this,Op)){const i=vN(h(this,Op),e),{dependencies:o}=i;h(this,uc).forEach(o.add,o),h(this,ri)._savesStack.forEach(o.add,o),h(this,ri)._markedContentStack.forEach(o.add,o),o.delete(e),i.isRenderingOperation=!0}const r=!t&&e===h(this,ri)._pendingBBoxIdx;return h(this,ri).recordOperation(e,t,[h(this,uc),h(this,ri)._savesStack,h(this,ri)._markedContentStack]),r&&h(this,uc).clear(),this}recordShowTextOperation(e,t=!1){const r=Array.from(h(this,uc));this.recordOperation(e,t),this.recordIncrementalData("sameLineText",e);for(const i of r)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(e,t=!1){const r=!t&&e===h(this,ri)._pendingBBoxIdx;return h(this,ri).bboxToClipBoxDropOperation(e),r&&h(this,uc).clear(),this}take(){return h(this,Vb).clear(),h(this,ri).take()}takeDebugMetadata(){return h(this,Op)}}qa=new WeakMap,Va=new WeakMap,iy=new WeakMap,uc=new WeakMap,Vb=new WeakMap,Op=new WeakMap,Lp=new WeakMap,ri=new WeakMap;var ii,ls,hc,Gb,Kb;const H3=class H3{constructor(e,t,r){N(this,ii);N(this,ls);N(this,hc);N(this,Gb,0);N(this,Kb,0);if(e instanceof H3&&h(e,hc)===!!r)return e;R(this,ii,e),R(this,ls,t),R(this,hc,!!r)}get clipBox(){return h(this,ii).clipBox}growOperationsCount(){throw new Error("Unreachable")}save(e){return Gi(this,Kb)._++,h(this,ii).save(h(this,ls)),this}restore(e){return h(this,Kb)>0&&(h(this,ii).restore(h(this,ls)),Gi(this,Kb)._--),this}recordOpenMarker(e){return Gi(this,Gb)._++,this}getOpenMarker(){return h(this,Gb)>0?h(this,ls):h(this,ii).getOpenMarker()}recordCloseMarker(e){return Gi(this,Gb)._--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return h(this,ii).pushBaseTransform(e),this}popBaseTransform(){return h(this,ii).popBaseTransform(),this}recordSimpleData(e,t){return h(this,ii).recordSimpleData(e,h(this,ls)),this}recordIncrementalData(e,t){return h(this,ii).recordIncrementalData(e,h(this,ls)),this}resetIncrementalData(e,t){return h(this,ii).resetIncrementalData(e,h(this,ls)),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,r){return h(this,ii).recordSimpleDataFromNamed(e,t,h(this,ls)),this}recordFutureForcedDependency(e,t){return h(this,ii).recordFutureForcedDependency(e,h(this,ls)),this}inheritSimpleDataAsFutureForcedDependencies(e){return h(this,ii).inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return h(this,ii).inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return h(this,hc)||h(this,ii).resetBBox(h(this,ls)),this}recordClipBox(e,t,r,i,o,a){return h(this,hc)||h(this,ii).recordClipBox(h(this,ls),t,r,i,o,a),this}recordBBox(e,t,r,i,o,a){return h(this,hc)||h(this,ii).recordBBox(h(this,ls),t,r,i,o,a),this}recordCharacterBBox(e,t,r,i,o,a,l){return h(this,hc)||h(this,ii).recordCharacterBBox(h(this,ls),t,r,i,o,a,l),this}recordFullPageBBox(e){return h(this,hc)||h(this,ii).recordFullPageBBox(h(this,ls)),this}getSimpleIndex(e){return h(this,ii).getSimpleIndex(e)}recordDependencies(e,t){return h(this,ii).recordDependencies(h(this,ls),t),this}recordNamedDependency(e,t){return h(this,ii).recordNamedDependency(h(this,ls),t),this}recordOperation(e){return h(this,ii).recordOperation(h(this,ls),!0),this}recordShowTextOperation(e){return h(this,ii).recordShowTextOperation(h(this,ls),!0),this}bboxToClipBoxDropOperation(e){return h(this,hc)||h(this,ii).bboxToClipBoxDropOperation(h(this,ls),!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}};ii=new WeakMap,ls=new WeakMap,hc=new WeakMap,Gb=new WeakMap,Kb=new WeakMap;let Yj=H3;const id={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],transform:["transform"],transformAndFill:["transform","fillColor"]};var sy,oy,ay,ly,dy,Pk;const sj=class sj{constructor(e){N(this,sy);N(this,oy);N(this,ay,4);N(this,ly,0);N(this,dy,new(h(sj,Pk))(h(this,ay)*6));R(this,sy,e.width),R(this,oy,e.height)}record(e,t,r,i){if(h(this,ly)===h(this,ay)){R(this,ay,h(this,ay)*2);const l=new(h(sj,Pk))(h(this,ay)*6);l.set(h(this,dy)),R(this,dy,l)}const o=yt.domMatrixToTransform(e.getTransform());let a;if(i[0]!==1/0){const l=hf.slice();yt.axialAlignedBoundingBox([0,-r,t,0],o,l);const d=yt.intersect(i,l);if(!d)return;const[c,u,f,p]=d;if(c!==l[0]||u!==l[1]||f!==l[2]||p!==l[3]){const g=Math.atan2(o[1],o[0]),m=Math.abs(Math.sin(g)),y=Math.abs(Math.cos(g));if(m<1e-6||y<1e-6||Math.abs(m-y)<1e-6)a=[c,u,c,p,f,u];else{const v=f-c,x=p-u,w=m*m,S=y*y,_=y*m,b=S-w,C=(x*S-v*_)/b,T=(x*_-v*w)/b;a=[c+T,u,c,u+C,f,p-C]}}}a||(a=[0,-r,0,0,t,-r],yt.applyTransform(a,o,0),yt.applyTransform(a,o,2),yt.applyTransform(a,o,4)),a[0]/=h(this,sy),a[1]/=h(this,oy),a[2]/=h(this,sy),a[3]/=h(this,oy),a[4]/=h(this,sy),a[5]/=h(this,oy),h(this,dy).set(a,h(this,ly)*6),Gi(this,ly)._++}take(){return h(this,dy).subarray(0,h(this,ly)*6)}};sy=new WeakMap,oy=new WeakMap,ay=new WeakMap,ly=new WeakMap,dy=new WeakMap,Pk=new WeakMap,N(sj,Pk,Ds.isFloat16ArraySupported?Float16Array:Float32Array);let xI=sj;var Xb;class pue{constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){N(this,Xb,new Set);this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(const e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),h(this,Xb).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:r}){if(!(!e||h(this,Xb).has(e.loadedName))){if(Zi(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:o,style:a}=e,l=new FontFace(i,o,a);this.addNativeFontFace(l);try{await l.load(),h(this,Xb).add(i),r==null||r(e)}catch{Bn(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}Hr("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){const r=e.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(i){throw Bn(`Failed to load font '${r.family}': '${i}'.`),e.disableFontFace=!0,i}}return}const t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(r=>{const i=this._queueLoadingCallback(r);this._prepareFontLoadEvent(e,i)})}}get isFontLoadingAPISupported(){var t;const e=!!((t=this._document)!=null&&t.fonts);return Cn(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){return Cn(this,"isSyncFontLoadingSupported",zl||Ds.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(Zi(!i.done,"completeRequest() cannot be called twice."),i.done=!0;r.length>0&&r[0].done;){const o=r.shift();setTimeout(o.callback,0)}}const{loadingRequests:r}=this,i={done:!1,complete:t,callback:e};return r.push(i),i}get _loadTestFont(){const e=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Cn(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,t){function r(b,C){return b.charCodeAt(C)<<24|b.charCodeAt(C+1)<<16|b.charCodeAt(C+2)<<8|b.charCodeAt(C+3)&255}function i(b){return String.fromCharCode(b>>24&255,b>>16&255,b>>8&255,b&255)}function o(b,C,T,F){const A=b.substring(0,C),D=b.substring(C+T);return A+F+D}let a,l;const d=this._document.createElement("canvas");d.width=1,d.height=1;const c=d.getContext("2d");let u=0;function f(b,C){if(++u>30){Bn("Load test font never loaded."),C();return}if(c.font="30px "+b,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(f.bind(null,b,C))}const p=`lt${Date.now()}${this.loadTestFontId++}`;let g=this._loadTestFont;g=o(g,976,p.length,p);const y=16,v=1482184792;let x=r(g,y);for(a=0,l=p.length-3;a{_.remove(),t.complete()})}}Xb=new WeakMap;var si;class gue{constructor(e,t=null,r,i){ve(this,"compiledGlyphs",Object.create(null));N(this,si);R(this,si,e),this._inspectFont=t,r&&(this.charProcOperatorList=r),i&&Object.assign(this,i)}createNativeFontFace(){var t;if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{const r={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(r.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,r)}return(t=this._inspectFont)==null||t.call(this,this),e}createFontFaceRule(){var r;if(!this.data||this.disableFontFace)return null;const e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${e}}`}return(r=this._inspectFont)==null||r.call(this,this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];const r=this.loadedName+"_path_"+t;let i;try{i=e.get(r)}catch(a){Bn(`getPathGenerator - ignoring character: "${a}".`)}const o=hV(i==null?void 0:i.path);return this.fontExtraProperties||e.delete(r),this.compiledGlyphs[t]=o}get black(){return h(this,si).black}get bold(){return h(this,si).bold}get disableFontFace(){return h(this,si).disableFontFace}set disableFontFace(e){Cn(this,"disableFontFace",!!e)}get fontExtraProperties(){return h(this,si).fontExtraProperties}get isInvalidPDFjsFont(){return h(this,si).isInvalidPDFjsFont}get isType3Font(){return h(this,si).isType3Font}get italic(){return h(this,si).italic}get missingFile(){return h(this,si).missingFile}get remeasure(){return h(this,si).remeasure}get vertical(){return h(this,si).vertical}get ascent(){return h(this,si).ascent}get defaultWidth(){return h(this,si).defaultWidth}get descent(){return h(this,si).descent}get bbox(){return h(this,si).bbox}get fontMatrix(){return h(this,si).fontMatrix}get fallbackName(){return h(this,si).fallbackName}get loadedName(){return h(this,si).loadedName}get mimetype(){return h(this,si).mimetype}get name(){return h(this,si).name}get data(){return h(this,si).data}clearData(){h(this,si).clearData()}get cssFontInfo(){return h(this,si).cssFontInfo}get systemFontInfo(){return h(this,si).systemFontInfo}get defaultVMetrics(){return h(this,si).defaultVMetrics}}si=new WeakMap;class KV{}ve(KV,"strings",["fontFamily","fontWeight","italicAngle"]);class XV{}ve(XV,"strings",["css","loadedName","baseFontName","src"]);const Xo=class Xo{};ve(Xo,"bools",["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"]),ve(Xo,"numbers",["ascent","defaultWidth","descent"]),ve(Xo,"strings",["fallbackName","loadedName","mimetype","name"]),ve(Xo,"OFFSET_NUMBERS",Math.ceil(Xo.bools.length*2/8)),ve(Xo,"OFFSET_BBOX",Xo.OFFSET_NUMBERS+Xo.numbers.length*8),ve(Xo,"OFFSET_FONT_MATRIX",Xo.OFFSET_BBOX+1+2*4),ve(Xo,"OFFSET_DEFAULT_VMETRICS",Xo.OFFSET_FONT_MATRIX+1+8*6),ve(Xo,"OFFSET_STRINGS",Xo.OFFSET_DEFAULT_VMETRICS+1+2*3);let pl=Xo;class Sa{}ve(Sa,"KIND",0),ve(Sa,"HAS_BBOX",1),ve(Sa,"HAS_BACKGROUND",2),ve(Sa,"SHADING_TYPE",3),ve(Sa,"N_COORD",4),ve(Sa,"N_COLOR",8),ve(Sa,"N_STOP",12),ve(Sa,"N_FIGURES",16);var Rk,MT,Yb,Qb,O5;class mue{constructor(e){N(this,Qb);N(this,Rk);N(this,MT,new TextDecoder);N(this,Yb);R(this,Rk,e),R(this,Yb,new DataView(e))}get fontFamily(){return q(this,Qb,O5).call(this,0)}get fontWeight(){return q(this,Qb,O5).call(this,1)}get italicAngle(){return q(this,Qb,O5).call(this,2)}}Rk=new WeakMap,MT=new WeakMap,Yb=new WeakMap,Qb=new WeakSet,O5=function(e){Zi(e>r&3;return i===0?void 0:i===2},L5=function(e){return Zi(e0){y=hf.slice();for(let v=0,x=c.length;vtypeof n=="object"&&Number.isInteger(n==null?void 0:n.num)&&n.num>=0&&Number.isInteger(n==null?void 0:n.gen)&&n.gen>=0,jue=n=>typeof n=="object"&&typeof(n==null?void 0:n.name)=="string",kue=$ce.bind(null,vI,jue);var Nh,OT;class _ue{constructor(){N(this,Nh,new Map);N(this,OT,Promise.resolve())}postMessage(e,t){const r={data:structuredClone(e,t?{transfer:t}:null)};h(this,OT).then(()=>{for(const[i]of h(this,Nh))i.call(this,r)})}addEventListener(e,t,r=null){let i=null;if((r==null?void 0:r.signal)instanceof AbortSignal){const{signal:o}=r;if(o.aborted){Bn("LoopbackPort - cannot use an `aborted` signal.");return}const a=()=>this.removeEventListener(e,t);i=()=>o.removeEventListener("abort",a),o.addEventListener("abort",a)}h(this,Nh).set(t,i)}removeEventListener(e,t){const r=h(this,Nh).get(t);r==null||r(),h(this,Nh).delete(t)}terminate(){for(const[,e]of h(this,Nh))e==null||e();h(this,Nh).clear()}}Nh=new WeakMap,OT=new WeakMap;const K2={DATA:1,ERROR:2},_s={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function wN(){}function La(n){if(n instanceof Ng||n instanceof XB||n instanceof dN||n instanceof xT||n instanceof LP)return n;switch(n instanceof Error||typeof n=="object"&&n!==null||Hr('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),n.name){case"AbortException":return new Ng(n.message);case"InvalidPDFException":return new XB(n.message);case"PasswordException":return new dN(n.message,n.code);case"ResponseException":return new xT(n.message,n.status,n.missing);case"UnknownErrorException":return new LP(n.message,n.details)}return new LP(n.message,n.toString())}var Jb,zd,YV,QV,$V,W5;class xS{constructor(e,t,r){N(this,zd);N(this,Jb,new AbortController);this.sourceName=e,this.targetName=t,this.comObj=r,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),r.addEventListener("message",q(this,zd,YV).bind(this),{signal:h(this,Jb).signal})}on(e,t){const r=this.actionHandler;if(r[e])throw new Error(`There is already an actionName called "${e}"`);r[e]=t}send(e,t,r){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},r)}sendWithPromise(e,t,r){const i=this.callbackId++,o=Promise.withResolvers();this.callbackCapabilities[i]=o;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:i,data:t},r)}catch(a){o.reject(a)}return o.promise}sendWithStream(e,t,r,i){const o=this.streamId++,a=this.sourceName,l=this.targetName,d=this.comObj;return new ReadableStream({start:c=>{const u=Promise.withResolvers();return this.streamControllers[o]={controller:c,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},d.postMessage({sourceName:a,targetName:l,action:e,streamId:o,data:t,desiredSize:c.desiredSize},i),u.promise},pull:c=>{const u=Promise.withResolvers();return this.streamControllers[o].pullCall=u,d.postMessage({sourceName:a,targetName:l,stream:_s.PULL,streamId:o,desiredSize:c.desiredSize}),u.promise},cancel:c=>{Zi(c instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[o].cancelCall=u,this.streamControllers[o].isClosed=!0,d.postMessage({sourceName:a,targetName:l,stream:_s.CANCEL,streamId:o,reason:La(c)}),u.promise}},r)}destroy(){var e;(e=h(this,Jb))==null||e.abort(),R(this,Jb,null)}}Jb=new WeakMap,zd=new WeakSet,YV=function({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){q(this,zd,$V).call(this,e);return}if(e.callback){const r=e.callbackId,i=this.callbackCapabilities[r];if(!i)throw new Error(`Cannot resolve callback ${r}`);if(delete this.callbackCapabilities[r],e.callback===K2.DATA)i.resolve(e.data);else if(e.callback===K2.ERROR)i.reject(La(e.reason));else throw new Error("Unexpected callback case");return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const r=this.sourceName,i=e.sourceName,o=this.comObj;Promise.try(t,e.data).then(function(a){o.postMessage({sourceName:r,targetName:i,callback:K2.DATA,callbackId:e.callbackId,data:a})},function(a){o.postMessage({sourceName:r,targetName:i,callback:K2.ERROR,callbackId:e.callbackId,reason:La(a)})});return}if(e.streamId){q(this,zd,QV).call(this,e);return}t(e.data)},QV=function(e){const t=e.streamId,r=this.sourceName,i=e.sourceName,o=this.comObj,a=this,l=this.actionHandler[e.action],d={enqueue(c,u=1,f){if(this.isCancelled)return;const p=this.desiredSize;this.desiredSize-=u,p>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),o.postMessage({sourceName:r,targetName:i,stream:_s.ENQUEUE,streamId:t,chunk:c},f)},close(){this.isCancelled||(this.isCancelled=!0,o.postMessage({sourceName:r,targetName:i,stream:_s.CLOSE,streamId:t}),delete a.streamSinks[t])},error(c){Zi(c instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,o.postMessage({sourceName:r,targetName:i,stream:_s.ERROR,streamId:t,reason:La(c)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};d.sinkCapability.resolve(),d.ready=d.sinkCapability.promise,this.streamSinks[t]=d,Promise.try(l,e.data,d).then(function(){o.postMessage({sourceName:r,targetName:i,stream:_s.START_COMPLETE,streamId:t,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:_s.START_COMPLETE,streamId:t,reason:La(c)})})},$V=function(e){const t=e.streamId,r=this.sourceName,i=e.sourceName,o=this.comObj,a=this.streamControllers[t],l=this.streamSinks[t];switch(e.stream){case _s.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(La(e.reason));break;case _s.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(La(e.reason));break;case _s.PULL:if(!l){o.postMessage({sourceName:r,targetName:i,stream:_s.PULL_COMPLETE,streamId:t,success:!0});break}l.desiredSize<=0&&e.desiredSize>0&&l.sinkCapability.resolve(),l.desiredSize=e.desiredSize,Promise.try(l.onPull||wN).then(function(){o.postMessage({sourceName:r,targetName:i,stream:_s.PULL_COMPLETE,streamId:t,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:_s.PULL_COMPLETE,streamId:t,reason:La(c)})});break;case _s.ENQUEUE:if(Zi(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(e.chunk);break;case _s.CLOSE:if(Zi(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),q(this,zd,W5).call(this,a,t);break;case _s.ERROR:Zi(a,"error should have stream controller"),a.controller.error(La(e.reason)),q(this,zd,W5).call(this,a,t);break;case _s.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(La(e.reason)),q(this,zd,W5).call(this,a,t);break;case _s.CANCEL:if(!l)break;const d=La(e.reason);Promise.try(l.onCancel||wN,d).then(function(){o.postMessage({sourceName:r,targetName:i,stream:_s.CANCEL_COMPLETE,streamId:t,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:_s.CANCEL_COMPLETE,streamId:t,reason:La(c)})}),l.sinkCapability.reject(d),l.isCancelled=!0,delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}},W5=async function(e,t){var r,i,o;await Promise.allSettled([(r=e.startCall)==null?void 0:r.promise,(i=e.pullCall)==null?void 0:i.promise,(o=e.cancelCall)==null?void 0:o.promise]),delete this.streamControllers[t]};var LT;class ZV{constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:r=null}){N(this,LT,Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"}));this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=r}async fetch({kind:e,filename:t}){switch(e){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:Hr(`Not implemented: ${e}`)}const r=this[e];if(!r)throw new Error(`Ensure that the \`${e}\` API parameter is provided.`);const i=`${r}${t}`;return this._fetch(i,e).catch(o=>{throw new Error(`Unable to load ${h(this,LT)[e]} data at: ${i}`)})}async _fetch(e,t){Hr("Abstract method `_fetch` called.")}}LT=new WeakMap;class SN extends ZV{async _fetch(e,t){const r=t==="cMapUrl"&&!e.endsWith(".bcmap")?"text":"bytes",i=await E3(e,r);return i instanceof Uint8Array?i:rD(i)}}var Bk;class JV{constructor({enableHWA:e=!1}){N(this,Bk,!1);R(this,Bk,e)}create(e,t){if(e<=0||t<=0)throw new Error("Invalid canvas size");const r=this._createCanvas(e,t);return{canvas:r,context:r.getContext("2d",{willReadFrequently:!h(this,Bk)})}}reset({canvas:e},t,r){if(!e)throw new Error("Canvas is not specified");if(t<=0||r<=0)throw new Error("Invalid canvas size");e.width=t,e.height=r}destroy(e){const{canvas:t}=e;if(!t)throw new Error("Canvas is not specified");t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){Hr("Abstract method `_createCanvas` called.")}}Bk=new WeakMap;class Cue extends JV{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){const r=this._document.createElement("canvas");return r.width=e,r.height=t,r}}class eG{addFilter(e){return"none"}addHCMFilter(e,t){return"none"}addAlphaFilter(e){return"none"}addLuminosityFilter(e){return"none"}addHighlightHCMFilter(e,t,r,i,o){return"none"}destroy(e=!1){}}var hy,ev,Wh,Uh,Jo,fy,py,zt,Ko,bS,kx,U5,_x,tG,wI,Cx,vS,wS,SI,SS;class Aue extends eG{constructor({docId:t,ownerDocument:r=globalThis.document}){super();N(this,zt);N(this,hy);N(this,ev);N(this,Wh);N(this,Uh);N(this,Jo);N(this,fy);N(this,py,0);R(this,Uh,t),R(this,Jo,r)}addFilter(t){if(!t)return"none";let r=h(this,zt,Ko).get(t);if(r)return r;const[i,o,a]=q(this,zt,U5).call(this,t),l=t.length===1?i:`${i}${o}${a}`;if(r=h(this,zt,Ko).get(l),r)return h(this,zt,Ko).set(t,r),r;const d=`g_${h(this,Uh)}_transfer_map_${Gi(this,py)._++}`,c=q(this,zt,_x).call(this,d);h(this,zt,Ko).set(t,c),h(this,zt,Ko).set(l,c);const u=q(this,zt,Cx).call(this,d);return q(this,zt,wS).call(this,i,o,a,u),c}addHCMFilter(t,r){var m;const i=`${t}-${r}`,o="base";let a=h(this,zt,bS).get(o);if((a==null?void 0:a.key)===i||(a?((m=a.filter)==null||m.remove(),a.key=i,a.url="none",a.filter=null):(a={key:i,url:"none",filter:null},h(this,zt,bS).set(o,a)),!t||!r))return a.url;const l=q(this,zt,SS).call(this,t);t=yt.makeHexColor(...l);const d=q(this,zt,SS).call(this,r);if(r=yt.makeHexColor(...d),h(this,zt,kx).style.color="",t==="#000000"&&r==="#ffffff"||t===r)return a.url;const c=new Array(256);for(let y=0;y<=255;y++){const v=y/255;c[y]=v<=.03928?v/12.92:((v+.055)/1.055)**2.4}const u=c.join(","),f=`g_${h(this,Uh)}_hcm_filter`,p=a.filter=q(this,zt,Cx).call(this,f);q(this,zt,wS).call(this,u,u,u,p),q(this,zt,wI).call(this,p);const g=(y,v)=>{const x=l[y]/255,w=d[y]/255,S=new Array(v+1);for(let _=0;_<=v;_++)S[_]=x+_/v*(w-x);return S.join(",")};return q(this,zt,wS).call(this,g(0,5),g(1,5),g(2,5),p),a.url=q(this,zt,_x).call(this,f),a.url}addAlphaFilter(t){let r=h(this,zt,Ko).get(t);if(r)return r;const[i]=q(this,zt,U5).call(this,[t]),o=`alpha_${i}`;if(r=h(this,zt,Ko).get(o),r)return h(this,zt,Ko).set(t,r),r;const a=`g_${h(this,Uh)}_alpha_map_${Gi(this,py)._++}`,l=q(this,zt,_x).call(this,a);h(this,zt,Ko).set(t,l),h(this,zt,Ko).set(o,l);const d=q(this,zt,Cx).call(this,a);return q(this,zt,SI).call(this,i,d),l}addLuminosityFilter(t){let r=h(this,zt,Ko).get(t||"luminosity");if(r)return r;let i,o;if(t?([i]=q(this,zt,U5).call(this,[t]),o=`luminosity_${i}`):o="luminosity",r=h(this,zt,Ko).get(o),r)return h(this,zt,Ko).set(t,r),r;const a=`g_${h(this,Uh)}_luminosity_map_${Gi(this,py)._++}`,l=q(this,zt,_x).call(this,a);h(this,zt,Ko).set(t,l),h(this,zt,Ko).set(o,l);const d=q(this,zt,Cx).call(this,a);return q(this,zt,tG).call(this,d),t&&q(this,zt,SI).call(this,i,d),l}addHighlightHCMFilter(t,r,i,o,a){var w;const l=`${r}-${i}-${o}-${a}`;let d=h(this,zt,bS).get(t);if((d==null?void 0:d.key)===l||(d?((w=d.filter)==null||w.remove(),d.key=l,d.url="none",d.filter=null):(d={key:l,url:"none",filter:null},h(this,zt,bS).set(t,d)),!r||!i))return d.url;const[c,u]=[r,i].map(q(this,zt,SS).bind(this));let f=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),p=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[g,m]=[o,a].map(q(this,zt,SS).bind(this));p{const C=new Array(256),T=(p-f)/b,F=S/255,A=(_-S)/(255*b);let D=0;for(let P=0;P<=b;P++){const L=Math.round(f+P*T),W=F+P*A;for(let O=D;O<=L;O++)C[O]=W;D=L+1}for(let P=D;P<256;P++)C[P]=C[D-1];return C.join(",")},v=`g_${h(this,Uh)}_hcm_${t}_filter`,x=d.filter=q(this,zt,Cx).call(this,v);return q(this,zt,wI).call(this,x),q(this,zt,wS).call(this,y(g[0],m[0],5),y(g[1],m[1],5),y(g[2],m[2],5),x),d.url=q(this,zt,_x).call(this,v),d.url}destroy(t=!1){var r,i,o,a;t&&((r=h(this,fy))!=null&&r.size)||((i=h(this,Wh))==null||i.parentNode.parentNode.remove(),R(this,Wh,null),(o=h(this,ev))==null||o.clear(),R(this,ev,null),(a=h(this,fy))==null||a.clear(),R(this,fy,null),R(this,py,0))}}hy=new WeakMap,ev=new WeakMap,Wh=new WeakMap,Uh=new WeakMap,Jo=new WeakMap,fy=new WeakMap,py=new WeakMap,zt=new WeakSet,Ko=function(){return h(this,ev)||R(this,ev,new Map)},bS=function(){return h(this,fy)||R(this,fy,new Map)},kx=function(){if(!h(this,Wh)){const t=h(this,Jo).createElement("div"),{style:r}=t;r.visibility="hidden",r.contain="strict",r.width=r.height=0,r.position="absolute",r.top=r.left=0,r.zIndex=-1;const i=h(this,Jo).createElementNS(hh,"svg");i.setAttribute("width",0),i.setAttribute("height",0),R(this,Wh,h(this,Jo).createElementNS(hh,"defs")),t.append(i),i.append(h(this,Wh)),h(this,Jo).body.append(t)}return h(this,Wh)},U5=function(t){if(t.length===1){const c=t[0],u=new Array(256);for(let p=0;p<256;p++)u[p]=c[p]/255;const f=u.join(",");return[f,f,f]}const[r,i,o]=t,a=new Array(256),l=new Array(256),d=new Array(256);for(let c=0;c<256;c++)a[c]=r[c]/255,l[c]=i[c]/255,d[c]=o[c]/255;return[a.join(","),l.join(","),d.join(",")]},_x=function(t){if(h(this,hy)===void 0){R(this,hy,"");const r=h(this,Jo).URL;r!==h(this,Jo).baseURI&&(iD(r)?Bn('#createUrl: ignore "data:"-URL for performance reasons.'):R(this,hy,lV(r,"")))}return`url(${h(this,hy)}#${t})`},tG=function(t){const r=h(this,Jo).createElementNS(hh,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(r)},wI=function(t){const r=h(this,Jo).createElementNS(hh,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(r)},Cx=function(t){const r=h(this,Jo).createElementNS(hh,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",t),h(this,zt,kx).append(r),r},vS=function(t,r,i){const o=h(this,Jo).createElementNS(hh,r);o.setAttribute("type","discrete"),o.setAttribute("tableValues",i),t.append(o)},wS=function(t,r,i,o){const a=h(this,Jo).createElementNS(hh,"feComponentTransfer");o.append(a),q(this,zt,vS).call(this,a,"feFuncR",t),q(this,zt,vS).call(this,a,"feFuncG",r),q(this,zt,vS).call(this,a,"feFuncB",i)},SI=function(t,r){const i=h(this,Jo).createElementNS(hh,"feComponentTransfer");r.append(i),q(this,zt,vS).call(this,i,"feFuncA",t)},SS=function(t){return h(this,zt,kx).style.color=t,cC(getComputedStyle(h(this,zt,kx)).getPropertyValue("color"))};zl&&Bn("Please use the `legacy` build in Node.js environments.");async function Tue(n){const t=await process.getBuiltinModule("fs/promises").readFile(n);return new Uint8Array(t)}class Fue extends eG{}class Due extends JV{_createCanvas(e,t){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(e,t)}}class Eue extends ZV{async _fetch(e,t){return Tue(e)}}const Pue=` struct Uniforms { offsetX : f32, offsetY : f32, scaleX : f32, scaleY : f32, paddedWidth : f32, paddedHeight : f32, borderSize : f32, _pad : f32, }; @group(0) @binding(0) var u : Uniforms; struct VertexInput { @location(0) position : vec2, @location(1) color : vec4, }; struct VertexOutput { @builtin(position) position : vec4, @location(0) color : vec3, }; @vertex fn vs_main(in : VertexInput) -> VertexOutput { var out : VertexOutput; let cx = (in.position.x + u.offsetX) * u.scaleX; let cy = (in.position.y + u.offsetY) * u.scaleY; out.position = vec4( ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0, 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0, 0.0, 1.0 ); out.color = in.color.rgb; return out; } @fragment fn fs_main(in : VertexOutput) -> @location(0) vec4 { return vec4(in.color, 1.0); } `;var NT,Hh,gy,tv,WT,nG;class Rue{constructor(){N(this,WT);N(this,NT,null);N(this,Hh,null);N(this,gy,null);N(this,tv,null)}init(){return h(this,NT)||R(this,NT,q(this,WT,nG).call(this))}get isReady(){return h(this,Hh)!==null}loadMeshShader(){if(!h(this,Hh)||h(this,gy))return;const e=h(this,Hh).createShaderModule({code:Pue});R(this,gy,h(this,Hh).createRenderPipeline({layout:"auto",vertex:{module:e,entryPoint:"vs_main",buffers:[{arrayStride:2*4,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:e,entryPoint:"fs_main",targets:[{format:h(this,tv)}]},primitive:{topology:"triangle-list"}}))}draw(e,t,r,i,o,a,l,d){this.loadMeshShader();const c=h(this,Hh),{offsetX:u,offsetY:f,scaleX:p,scaleY:g}=i,m=c.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&c.queue.writeBuffer(m,0,e);const y=c.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&c.queue.writeBuffer(y,0,t);const v=c.createBuffer({size:8*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});c.queue.writeBuffer(v,0,new Float32Array([u,f,p,g,a,l,d,0]));const x=c.createBindGroup({layout:h(this,gy).getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:v}}]}),w=new OffscreenCanvas(a,l),S=w.getContext("webgpu");S.configure({device:c,format:h(this,tv),alphaMode:o?"opaque":"premultiplied"});const _=o?{r:o[0]/255,g:o[1]/255,b:o[2]/255,a:1}:{r:0,g:0,b:0,a:0},b=c.createCommandEncoder(),C=b.beginRenderPass({colorAttachments:[{view:S.getCurrentTexture().createView(),clearValue:_,loadOp:"clear",storeOp:"store"}]});return r>0&&(C.setPipeline(h(this,gy)),C.setBindGroup(0,x),C.setVertexBuffer(0,m),C.setVertexBuffer(1,y),C.draw(r)),C.end(),c.queue.submit([b.finish()]),m.destroy(),y.destroy(),v.destroy(),w.transferToImageBitmap()}}NT=new WeakMap,Hh=new WeakMap,gy=new WeakMap,tv=new WeakMap,WT=new WeakSet,nG=async function(){var e;if(!((e=globalThis.navigator)!=null&&e.gpu))return!1;try{const t=await navigator.gpu.requestAdapter();return t?(R(this,tv,navigator.gpu.getPreferredCanvasFormat()),R(this,Hh,await t.requestDevice()),!0):!1}catch{return!1}};const sD=new Rue;function Bue(){return sD.init()}function Iue(){return sD.isReady}function Mue(){sD.loadMeshShader()}function zue(n,e,t,r,i,o,a,l){return sD.draw(n,e,t,r,i,o,a,l)}const To={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function H5(n,e){if(!e)return;const t=e[2]-e[0],r=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],t,r),n.clip(i)}class M3{isModifyingCurrentTransform(){return!1}getPattern(){Hr("Abstract method `getPattern` called.")}}class Oue extends M3{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type==="radial"}areConic(){if(!this.isRadial())return!1;const e=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return e+this._r1>this._r0&&e+this._r0>this._r1}_createGradient(e,t=null){let r,i=this._p0,o=this._p1;if(t&&(i=i.slice(),o=o.slice(),yt.applyTransform(i,t),yt.applyTransform(o,t)),this._type==="axial")r=e.createLinearGradient(i[0],i[1],o[0],o[1]);else if(this._type==="radial"){let a=this._r0,l=this._r1;if(t){const d=new Float32Array(2);yt.singularValueDecompose2dScale(t,d),a*=d[0],l*=d[0]}r=e.createRadialGradient(i[0],i[1],a,o[0],o[1],l)}for(const a of this._colorStops)r.addColorStop(a[0],a[1]);return r}_createReversedGradient(e,t=null){let r=this._p1,i=this._p0;t&&(r=r.slice(),i=i.slice(),yt.applyTransform(r,t),yt.applyTransform(i,t));let o=this._r1,a=this._r0;if(t){const c=new Float32Array(2);yt.singularValueDecompose2dScale(t,c),o*=c[0],a*=c[0]}const l=e.createRadialGradient(r[0],r[1],o,i[0],i[1],a),d=this._colorStops.map(([c,u])=>[1-c,u]).reverse();for(const[c,u]of d)l.addColorStop(c,u);return l}getPattern(e,t,r,i){let o;if(i===To.STROKE||i===To.FILL){if(this.isOriginBased()){let p=yt.transform(r,t.baseTransform);this.matrix&&(p=yt.transform(p,this.matrix));const g=.001,m=Math.hypot(p[0],p[1]),y=Math.hypot(p[2],p[3]),v=(p[0]*p[2]+p[1]*p[3])/(m*y);if(Math.abs(v)d[r*2+1]&&(p=t,t=r,r=p,p=o,o=a,a=p),d[r*2+1]>d[i*2+1]&&(p=r,r=i,i=p,p=a,a=l,l=p),d[t*2+1]>d[r*2+1]&&(p=t,t=r,r=p,p=o,o=a,a=p);const g=(d[t*2]+e.offsetX)*e.scaleX,m=(d[t*2+1]+e.offsetY)*e.scaleY,y=(d[r*2]+e.offsetX)*e.scaleX,v=(d[r*2+1]+e.offsetY)*e.scaleY,x=(d[i*2]+e.offsetX)*e.scaleX,w=(d[i*2+1]+e.offsetY)*e.scaleY;if(m>=w)return;const S=c[o*4],_=c[o*4+1],b=c[o*4+2],C=c[a*4],T=c[a*4+1],F=c[a*4+2],A=c[l*4],D=c[l*4+1],P=c[l*4+2],L=Math.round(m),W=Math.round(w);let O,U,M,I,H,z,G,te;for(let re=L;re<=W;re++){if(rew?ke=1:v===w?ke=0:ke=(v-re)/(v-w),O=y-(y-x)*ke,U=C-(C-A)*ke,M=T-(T-D)*ke,I=F-(F-P)*ke}let me;rew?me=1:me=(m-re)/(m-w),H=g-(g-x)*me,z=S-(S-A)*me,G=_-(_-D)*me,te=b-(b-P)*me;const J=Math.round(Math.min(O,H)),ne=Math.round(Math.max(O,H));let ye=f*re+J*4;for(let ke=J;ke<=ne;ke++)me=(O-ke)/(O-H),me<0?me=0:me>1&&(me=1),u[ye++]=U-(U-z)*me|0,u[ye++]=M-(M-G)*me|0,u[ye++]=I-(I-te)*me|0,u[ye++]=255}}class Nue extends M3{constructor(e){super(),this._posData=e[2],this._colData=e[3],this._vertexCount=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],this.matrix=null,Mue()}_createMeshCanvas(e,t,r){const l=Math.floor(this._bounds[0]),d=Math.floor(this._bounds[1]),c=Math.ceil(this._bounds[2])-l,u=Math.ceil(this._bounds[3])-d,f=Math.min(Math.ceil(Math.abs(c*e[0]*1.1)),3e3)||1,p=Math.min(Math.ceil(Math.abs(u*e[1]*1.1)),3e3)||1,g=c?c/f:1,m=u?u/p:1,y={coords:this._posData,colors:this._colData,offsetX:-l,offsetY:-d,scaleX:1/g,scaleY:1/m},v=f+2*2,x=p+2*2,w=r.create(v,x);if(Iue()&&this._vertexCount>48)w.context.drawImage(zue(this._posData,this._colData,this._vertexCount,y,t,v,x,2),0,0);else{const S=w.context.createImageData(f,p);if(t){const _=S.data;for(let b=0,C=_.length;bc+1e-6||t>u+1e-6)return null;const f=Math.floor((r-l)/c)+1,p=Math.ceil((r+e-o)/c)-1,g=Math.floor((i-d)/u)+1,m=Math.ceil((i+t-a)/u)-1;return p<=f&&m<=g?[f,g]:null}updatePatternDims(e,t){const r=yt.inverseTransform(this.patternBaseMatrix),i=[e[0],e[1]],o=[e[2],e[3]];yt.applyTransform(i,r),yt.applyTransform(o,r),t[0]=Math.abs(o[0]-i[0]),t[1]=Math.abs(o[1]-i[1]),t[2]=Math.min(i[0],o[0]),t[3]=Math.min(i[1],o[1])}_renderTileCanvas(e,t,r,i){var p,g;const[o,a,l,d]=this.bbox,c=e.canvasFactory.create(r.size,i.size),u=c.context,f=this.canvasGraphicsFactory.createCanvasGraphics(u,t);return f.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(f,this.paintType,this.color),u.translate(-r.scale*o,-i.scale*a),f.transform(0,r.scale,0,0,i.scale,0,0),u.save(),(p=f.dependencyTracker)==null||p.save(),this.clipBbox(f,o,a,l,d),f.baseTransform=ji(f.ctx),f.executeOperatorList(this.operatorList),f.endDrawing(),(g=f.dependencyTracker)==null||g.restore(),u.restore(),c}_getCombinedScales(){const e=new Float32Array(2);yt.singularValueDecompose2dScale(this.matrix,e);const[t,r]=e;return yt.singularValueDecompose2dScale(this.baseTransform,e),[t*e[0],r*e[1]]}drawPattern(e,t,r=!1,[i,o],a){const[l,d,c,u]=this.bbox,f=e.dependencyTracker;if(f&&(e.dependencyTracker=new Yj(f,a)),e.save(),r?e.ctx.clip(t,"evenodd"):e.ctx.clip(t),e.ctx.setTransform(...this.patternBaseMatrix),e.ctx.translate(i*this.xstep,o*this.ystep),this.needsIsolation||e.ctx.globalAlpha!==1||e.ctx.globalCompositeOperation!=="source-over"||e.inSMaskMode){const p=c-l,g=u-d,[m,y]=this._getCombinedScales(),v=this.getSizeAndScale(p,this.ctx.canvas.width,m),x=this.getSizeAndScale(g,this.ctx.canvas.height,y),w=this._renderTileCanvas(e,a,v,x);e.ctx.drawImage(w.canvas,l,d,p,g),e.canvasFactory.destroy(w)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,l,d,c,u),e.baseTransformStack.push(e.baseTransform),e.baseTransform=ji(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();e.restore(),f&&(e.dependencyTracker=f)}createPatternCanvas(e,t){const[r,i,o,a]=this.bbox,l=o-r,d=a-i;let{xstep:c,ystep:u}=this;c=Math.abs(c),u=Math.abs(u),nD("TilingType: "+this.tilingType);const[f,p]=this._getCombinedScales();let g=l,m=d,y=!1,v=!1;Math.ceil(c*f)>=Math.ceil(l*f)?g=c:y=!0,Math.ceil(u*p)>=Math.ceil(d*p)?m=u:v=!0;const x=this.getSizeAndScale(g,this.ctx.canvas.width,f),w=this.getSizeAndScale(m,this.ctx.canvas.height,p),S=this._renderTileCanvas(e,t,x,w);if(y||v){const _=S.canvas;y&&(g=c),v&&(m=u);const b=this.getSizeAndScale(g,this.ctx.canvas.width,f),C=this.getSizeAndScale(m,this.ctx.canvas.height,p),T=b.size,F=C.size,A=e.canvasFactory.create(T,F),D=A.context,P=y?Math.floor(l/c):0,L=v?Math.floor(d/u):0;for(let W=0;W<=P;W++)for(let O=0;O<=L;O++)D.drawImage(_,T*W,F*O,T,F,0,0,T,F);return e.canvasFactory.destroy(S),{canvas:A.canvas,canvasEntry:A,scaleX:b.scale,scaleY:C.scale,offsetX:r,offsetY:i}}return{canvas:S.canvas,canvasEntry:S,scaleX:x.scale,scaleY:w.scale,offsetX:r,offsetY:i}}getSizeAndScale(e,t,r){const i=Math.max(UT.MAX_PATTERN_SIZE,t);let o=Math.ceil(e*r);return o>=i?o=i:r=o/e,{scale:r,size:o}}clipBbox(e,t,r,i,o){const a=i-t,l=o-r,d=new Path2D;d.rect(t,r,a,l),yt.axialAlignedBoundingBox([t,r,i,o],ji(e.ctx),e.current.minMax),e.ctx.clip(d),e.current.updateClipFromPath()}setFillAndStrokeStyleToContext(e,t,r){const i=e.ctx,o=e.current;switch(o.patternFill=o.patternStroke=!1,t){case jN.COLORED:const{fillStyle:a,strokeStyle:l}=this.ctx;i.fillStyle=o.fillColor=a,i.strokeStyle=o.strokeColor=l;break;case jN.UNCOLORED:i.fillStyle=i.strokeStyle=r,o.fillColor=o.strokeColor=r;break;default:throw new Gce(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,r,i,o){const a=i!==To.SHADING?yt.transform(r,this.patternBaseMatrix):r,l=this.createPatternCanvas(t,o);let d=new DOMMatrix(a);d=d.translate(l.offsetX,l.offsetY),d=d.scale(1/l.scaleX,1/l.scaleY);const c=e.createPattern(l.canvas,"repeat");return t.canvasFactory.destroy(l.canvasEntry),c.setTransform(d),c}};ve(UT,"MAX_PATTERN_SIZE",3e3);let ij=UT;function Hue({src:n,srcPos:e=0,dest:t,width:r,height:i,nonBlackColor:o=4294967295,inverseDecode:a=!1}){const l=Ds.isLittleEndian?4278190080:255,[d,c]=a?[o,l]:[l,o],u=r>>3,f=r&7,p=d^c,g=n.length;t=new Uint32Array(t.buffer);let m=0;for(let y=0;y>7&1)&p,t[m+1]=d^-(w>>6&1)&p,t[m+2]=d^-(w>>5&1)&p,t[m+3]=d^-(w>>4&1)&p,t[m+4]=d^-(w>>3&1)&p,t[m+5]=d^-(w>>2&1)&p,t[m+6]=d^-(w>>1&1)&p,t[m+7]=d^-(w&1)&p}if(f===0)continue;const v=e>7-x&1)&p}return{srcPos:e,destPos:m}}const kN=16,_N=100,que=15,CN=10,Xa=16,WP=new DOMMatrix,Ol=new Float32Array(2);function Vue(n,e){if(n._removeMirroring)throw new Error("Context is already forwarding operations.");n.__originalSave=n.save,n.__originalRestore=n.restore,n.__originalRotate=n.rotate,n.__originalScale=n.scale,n.__originalTranslate=n.translate,n.__originalTransform=n.transform,n.__originalSetTransform=n.setTransform,n.__originalResetTransform=n.resetTransform,n.__originalClip=n.clip,n.__originalMoveTo=n.moveTo,n.__originalLineTo=n.lineTo,n.__originalBezierCurveTo=n.bezierCurveTo,n.__originalRect=n.rect,n.__originalClosePath=n.closePath,n.__originalBeginPath=n.beginPath,n._removeMirroring=()=>{n.save=n.__originalSave,n.restore=n.__originalRestore,n.rotate=n.__originalRotate,n.scale=n.__originalScale,n.translate=n.__originalTranslate,n.transform=n.__originalTransform,n.setTransform=n.__originalSetTransform,n.resetTransform=n.__originalResetTransform,n.clip=n.__originalClip,n.moveTo=n.__originalMoveTo,n.lineTo=n.__originalLineTo,n.bezierCurveTo=n.__originalBezierCurveTo,n.rect=n.__originalRect,n.closePath=n.__originalClosePath,n.beginPath=n.__originalBeginPath,delete n._removeMirroring},n.save=function(){e.save(),this.__originalSave()},n.restore=function(){e.restore(),this.__originalRestore()},n.translate=function(t,r){e.translate(t,r),this.__originalTranslate(t,r)},n.scale=function(t,r){e.scale(t,r),this.__originalScale(t,r)},n.transform=function(t,r,i,o,a,l){e.transform(t,r,i,o,a,l),this.__originalTransform(t,r,i,o,a,l)},n.setTransform=function(t,r,i,o,a,l){r===void 0?(e.setTransform(t),this.__originalSetTransform(t)):(e.setTransform(t,r,i,o,a,l),this.__originalSetTransform(t,r,i,o,a,l))},n.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},n.rotate=function(t){e.rotate(t),this.__originalRotate(t)},n.clip=function(t){e.clip(t),this.__originalClip(t)},n.moveTo=function(t,r){e.moveTo(t,r),this.__originalMoveTo(t,r)},n.lineTo=function(t,r){e.lineTo(t,r),this.__originalLineTo(t,r)},n.bezierCurveTo=function(t,r,i,o,a,l){e.bezierCurveTo(t,r,i,o,a,l),this.__originalBezierCurveTo(t,r,i,o,a,l)},n.rect=function(t,r,i,o){e.rect(t,r,i,o),this.__originalRect(t,r,i,o)},n.closePath=function(){e.closePath(),this.__originalClosePath()},n.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}function X2(n,e,t,r,i,o,a,l,d,c){const[u,f,p,g,m,y]=ji(n);if(f===0&&p===0){const w=a*u+m,S=Math.round(w),_=l*g+y,b=Math.round(_),C=(a+d)*u+m,T=Math.abs(Math.round(C)-S)||1,F=(l+c)*g+y,A=Math.abs(Math.round(F)-b)||1;return n.setTransform(Math.sign(u),0,0,Math.sign(g),S,b),n.drawImage(e,t,r,i,o,0,0,T,A),n.setTransform(u,f,p,g,m,y),[T,A]}if(u===0&&g===0){const w=l*p+m,S=Math.round(w),_=a*f+y,b=Math.round(_),C=(l+c)*p+m,T=Math.abs(Math.round(C)-S)||1,F=(a+d)*f+y,A=Math.abs(Math.round(F)-b)||1;return n.setTransform(0,Math.sign(f),Math.sign(p),0,S,b),n.drawImage(e,t,r,i,o,0,0,A,T),n.setTransform(u,f,p,g,m,y),[A,T]}n.drawImage(e,t,r,i,o,a,l,d,c);const v=Math.hypot(u,f),x=Math.hypot(p,g);return[v*d,x*c]}class AN{constructor(e,t){ve(this,"alphaIsShape",!1);ve(this,"fontSize",0);ve(this,"fontSizeScale",1);ve(this,"textMatrix",null);ve(this,"textMatrixScale",1);ve(this,"fontMatrix",GB);ve(this,"leading",0);ve(this,"x",0);ve(this,"y",0);ve(this,"lineX",0);ve(this,"lineY",0);ve(this,"charSpacing",0);ve(this,"wordSpacing",0);ve(this,"textHScale",1);ve(this,"textRenderingMode",Rs.FILL);ve(this,"textRise",0);ve(this,"fillColor","#000000");ve(this,"strokeColor","#000000");ve(this,"tilingPatternDims",null);ve(this,"patternFill",!1);ve(this,"patternStroke",!1);ve(this,"fillAlpha",1);ve(this,"strokeAlpha",1);ve(this,"lineWidth",1);ve(this,"activeSMask",null);ve(this,"transferMaps","none");ve(this,"minMax",_m.slice());this.clipBox=new Float32Array([0,0,e,t])}clone(){var t;const e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e.tilingPatternDims=(t=this.tilingPatternDims)==null?void 0:t.slice(),e}getPathBoundingBox(e=To.FILL,t=null){const r=this.minMax.slice();if(e===To.STROKE){t||Hr("Stroke bounding box must include transform."),yt.singularValueDecompose2dScale(t,Ol);const i=Ol[0]*this.lineWidth/2,o=Ol[1]*this.lineWidth/2;r[0]-=i,r[1]-=o,r[2]+=i,r[3]+=o}return r}updateClipFromPath(){const e=yt.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(_m,0)}getClippedPathBoundingBox(e=To.FILL,t=null){return yt.intersect(this.clipBox,this.getPathBoundingBox(e,t))}}function TN(n,e){if(e instanceof ImageData){n.putImageData(e,0,0);return}const t=e.height,r=e.width,i=t%Xa,o=(t-i)/Xa,a=i===0?o:o+1,l=n.createImageData(r,Xa);let d=0,c;const u=e.data,f=l.data;let p,g,m,y;if(e.kind===E5.GRAYSCALE_1BPP){const v=u.byteLength,x=new Uint32Array(f.buffer,0,f.byteLength>>2),w=x.length,S=r+7>>3,_=4294967295,b=Ds.isLittleEndian?4278190080:255;for(p=0;pS?r:C*8-7,A=F&-8;let D=0,P=0;for(;T>=1}for(;c=o&&(m=i,y=r*m),c=0,g=y;g--;)f[c++]=u[d++],f[c++]=u[d++],f[c++]=u[d++],f[c++]=255;n.putImageData(l,0,p*Xa)}else throw new Error(`bad image kind: ${e.kind}`)}function FN(n,e){if(e.bitmap){n.drawImage(e.bitmap,0,0);return}const t=e.height,r=e.width,i=t%Xa,o=(t-i)/Xa,a=i===0?o:o+1,l=n.createImageData(r,Xa);let d=0;const c=e.data,u=l.data;for(let f=0;fCN&&typeof r=="function",f=u?Date.now()+que:0;let p=0;const g=this.commonObjs,m=this.objs;let y,v;for(;;){if(i!==void 0){if(d===i.nextBreakPoint)return i.breakIt(d,r),d;if(i.shouldSkip(d)){if(++d===c)return d;continue}}if(!o||o(d))if(y=l[d],v=a[d]??null,y!==Sh.dependency)v===null?this[y](d):this[y](d,...v);else for(const w of v){(x=this.dependencyTracker)==null||x.recordNamedData(w,d);const S=w.startsWith("g_")?g:m;if(!S.has(w))return S.get(w,r),d}if(d++,d===c)return d;if(u&&++p>CN){if(Date.now()>f)return r(),d;p=0}}}endDrawing(){q(this,Pc,jI).call(this);for(const e of this.smaskGroupCanvases)this.canvasFactory.destroy(e);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0,this.cachedPatterns.clear();for(const e of this._cachedBitmapsMap.values()){for(const t of e.values())typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),q(this,Pc,kI).call(this)}_scaleImage(e,t){const r=e.width??e.displayWidth,i=e.height??e.displayHeight,o=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),l=[];let d=o,c=a,u=r,f=i;for(;d>2&&u>1||c>2&&f>1;){let x=u,w=f;d>2&&u>1&&(x=Math.ceil(u/2),d/=u/x),c>2&&f>1&&(w=Math.ceil(f/2),c/=f/w),l.push({newWidth:x,newHeight:w}),u=x,f=w}if(l.length===0)return{img:e,paintWidth:r,paintHeight:i,tmpCanvas:null};if(l.length===1){const{newWidth:x,newHeight:w}=l[0],S=this.canvasFactory.create(x,w);return S.context.drawImage(e,0,0,r,i,0,0,x,w),{img:S.canvas,paintWidth:x,paintHeight:w,tmpCanvas:S}}let p=this.canvasFactory.create(1,1),g=this.canvasFactory.create(1,1),m=r,y=i,v=e;for(const{newWidth:x,newHeight:w}of l)this.canvasFactory.reset(g,x,w),g.context.drawImage(v,0,0,m,y,0,0,x,w),[p,g]=[g,p],v=p.canvas,m=x,y=w;return this.canvasFactory.destroy(g),{img:p.canvas,paintWidth:m,paintHeight:y,tmpCanvas:p}}_createMaskCanvas(e,t){var P,L;const r=this.ctx,{width:i,height:o}=t,a=this.current.fillColor,l=this.current.patternFill,d=ji(r);let c,u,f,p;if((t.bitmap||t.data)&&t.count>1){const W=t.bitmap||t.data.buffer;u=JSON.stringify(l?d:[d.slice(0,4),a]),c=this._cachedBitmapsMap.getOrInsertComputed(W,D3);const O=c.get(u);if(O&&!l){const U=Math.round(Math.min(d[0],d[2])+d[4]),M=Math.round(Math.min(d[1],d[3])+d[5]);return(P=this.dependencyTracker)==null||P.recordDependencies(e,id.transformAndFill),{canvas:O,offsetX:U,offsetY:M}}f=O}f||(p=this.canvasFactory.create(i,o),FN(p.context,t));let g=yt.transform(d,[1/i,0,0,-1/o,0,0]);g=yt.transform(g,[1,0,0,1,0,-o]);const m=_m.slice();yt.axialAlignedBoundingBox([0,0,i,o],g,m);const[y,v,x,w]=m,S=Math.round(x-y)||1,_=Math.round(w-v)||1,b=this.canvasFactory.create(S,_),C=b.context,T=y,F=v;C.translate(-T,-F),C.transform(...g);let A=null;if(!f){const W=this._scaleImage(p.canvas,Kc(C));f=W.img,A=W.tmpCanvas,f!==p.canvas&&(this.canvasFactory.destroy(p),p=null),c&&l&&(c.set(u,f),A=null,p=null)}C.imageSmoothingEnabled=DN(ji(C),t.interpolate),X2(C,f,0,0,f.width,f.height,0,0,i,o),A&&this.canvasFactory.destroy(A),p&&this.canvasFactory.destroy(p),C.globalCompositeOperation="source-in";const D=yt.transform(Kc(C),[1,0,0,1,-T,-F]);return C.fillStyle=l?a.getPattern(r,this,D,To.FILL,e):a,C.fillRect(0,0,i,o),c&&!l&&c.set(u,b.canvas),(L=this.dependencyTracker)==null||L.recordDependencies(e,id.transformAndFill),{canvas:b.canvas,canvasEntry:c&&!l?null:b,offsetX:Math.round(T),offsetY:Math.round(F)}}setLineWidth(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("lineWidth",e),t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("lineCap",e),this.ctx.lineCap=Gue[t]}setLineJoin(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("lineJoin",e),this.ctx.lineJoin=Kue[t]}setMiterLimit(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("miterLimit",e),this.ctx.miterLimit=t}setDash(e,t,r){var o;(o=this.dependencyTracker)==null||o.recordSimpleData("dash",e);const i=this.ctx;i.setLineDash!==void 0&&(i.setLineDash(t),i.lineDashOffset=r)}setRenderingIntent(e,t){}setFlatness(e,t){}setGState(e,t){var r,i,o,a,l;for(const[d,c]of t)switch(d){case"LW":this.setLineWidth(e,c);break;case"LC":this.setLineCap(e,c);break;case"LJ":this.setLineJoin(e,c);break;case"ML":this.setMiterLimit(e,c);break;case"D":this.setDash(e,c[0],c[1]);break;case"RI":this.setRenderingIntent(e,c);break;case"FL":this.setFlatness(e,c);break;case"Font":this.setFont(e,c[0],c[1]);break;case"CA":(r=this.dependencyTracker)==null||r.recordSimpleData("strokeAlpha",e),this.current.strokeAlpha=c;break;case"ca":(i=this.dependencyTracker)==null||i.recordSimpleData("fillAlpha",e),this.ctx.globalAlpha=this.current.fillAlpha=c;break;case"BM":(o=this.dependencyTracker)==null||o.recordSimpleData("globalCompositeOperation",e),this.ctx.globalCompositeOperation=c;break;case"SMask":(a=this.dependencyTracker)==null||a.recordSimpleData("SMask",e),this.current.activeSMask=c?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(e);break;case"TR":(l=this.dependencyTracker)==null||l.recordSimpleData("filter",e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(c);break}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0}_ensurePreparedSMask(e,t,r){e!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(e,t,r))}checkSMaskState(e){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode(e):!this.current.activeSMask&&t?this.endSMaskMode():this.current.activeSMask&&t&&this._ensurePreparedSMask(this.current.activeSMask,this.ctx.canvas.width,this.ctx.canvas.height)}_prepareSMaskCanvas(e,t,r){const{canvas:i,subtype:o,backdrop:a,transferMap:l}=e,d=o==="Luminosity"||o==="Alpha"&&l;if(!a&&!d){this.smaskPreparedFor=e;return}let c,u,f;if(a&&d){const p=this.canvasFactory.create(t,r),g=p.context;g.drawImage(i,e.offsetX,e.offsetY),g.globalCompositeOperation="destination-atop",g.fillStyle=a,g.fillRect(0,0,t,r),g.globalCompositeOperation="source-over",c=this.canvasFactory.create(t,r);const m=c.context;m.filter=o==="Alpha"?this.filterFactory.addAlphaFilter(l):this.filterFactory.addLuminosityFilter(l),m.drawImage(p.canvas,0,0),m.filter="none",this.canvasFactory.destroy(p),u=f=0}else if(d){c=this.canvasFactory.create(i.width,i.height);const p=c.context;p.filter=o==="Alpha"?this.filterFactory.addAlphaFilter(l):this.filterFactory.addLuminosityFilter(l),p.drawImage(i,0,0),p.filter="none",{offsetX:u,offsetY:f}=e}else{c=this.canvasFactory.create(t,r);const p=c.context;p.drawImage(i,e.offsetX,e.offsetY),p.globalCompositeOperation="destination-atop",p.fillStyle=a,p.fillRect(0,0,t,r),p.globalCompositeOperation="source-over",u=f=0}this.smaskPreparedEntry=c,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=u,this.smaskPreparedOffsetY=f}beginSMaskMode(e){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:t,height:r}=this.ctx.canvas,i=this.canvasFactory.create(t,r);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const o=this.ctx=i.context;o.setTransform(this.suspendedCtx.getTransform()),qw(this.suspendedCtx,o),Vue(o,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask,t,r),this.setGState(e,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),qw(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const t=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,t,this.ctx,e),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(e[0],e[1],e[2]-e[0],e[3]-e[1]),this.ctx.restore()}composeSMask(e,t,r,i){const o=i[0],a=i[1],l=i[2]-o,d=i[3]-a;if(l===0||d===0)return;const c=this.smaskPreparedEntry;if(c){const u=o-this.smaskPreparedOffsetX,f=a-this.smaskPreparedOffsetY;r.save(),r.globalAlpha=1,r.setTransform(1,0,0,1,0,0);const p=new Path2D;p.rect(o,a,l,d),r.clip(p),r.globalCompositeOperation="destination-in",r.drawImage(c.canvas,u,f,l,d,o,a,l,d),r.restore()}else this.genericComposeSMask(t.context,r,l,d,o,a,t.offsetX,t.offsetY);e.save(),e.globalAlpha=1,e.globalCompositeOperation=t.blendMode||"source-over",e.setTransform(1,0,0,1,0,0),e.drawImage(r.canvas,o,a,l,d,o,a,l,d),e.restore()}genericComposeSMask(e,t,r,i,o,a,l,d){const c=e.canvas,u=o-l,f=a-d;t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const p=new Path2D;p.rect(o,a,r,i),t.clip(p),t.globalCompositeOperation="destination-in",t.drawImage(c,u,f,r,i,o,a,r,i),t.restore()}save(e){var r;this.inSMaskMode&&qw(this.ctx,this.suspendedCtx),this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone(),(r=this.dependencyTracker)==null||r.save(e)}restore(e){var t;if((t=this.dependencyTracker)==null||t.restore(e),this.stateStack.length===0){this.inSMaskMode&&this.endSMaskMode();return}this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(qw(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(e),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(e,t,r,i,o,a,l){var d;(d=this.dependencyTracker)==null||d.recordIncrementalData("transform",e),this.ctx.transform(t,r,i,o,a,l),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,r,i){let[o]=r;if(!i){o||(o=r[0]=new Path2D),t!==Sh.stroke&&t!==Sh.closeStroke&&(this.current.tilingPatternDims=null),this[t](e,o);return}if(this.dependencyTracker!==null){const l=t===Sh.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(e).recordBBox(e,this.ctx,i[0]-l,i[2]+l,i[1]-l,i[3]+l).recordDependencies(e,["transform"])}o instanceof Path2D||(o=r[0]=hV(o)),yt.axialAlignedBoundingBox(i,ji(this.ctx),this.current.minMax);const a=this.current.tilingPatternDims;if(a&&t!==Sh.stroke&&t!==Sh.closeStroke&&this.current.fillColor instanceof ij){const l=yt.intersect(this.current.clipBox,this.current.minMax);l?this.current.fillColor.updatePatternDims(l,a):this.current.tilingPatternDims=null}this[t](e,o),this._pathStartIdx=e}closePath(e){this.ctx.closePath()}stroke(e,t,r=!0){var a;const i=this.ctx,o=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof o=="object"&&(o!=null&&o.getPattern)){const l=o.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=o.getPattern(i,this,Kc(i),To.STROKE,e),l){const d=new Path2D;d.addPath(t,i.getTransform().invertSelf().multiplySelf(l)),t=d}this.rescaleAndStroke(t,!1),i.restore()}else this.rescaleAndStroke(t,!0);(a=this.dependencyTracker)==null||a.recordDependencies(e,id.stroke),r&&this.consumePath(e,t,this.current.getClippedPathBoundingBox(To.STROKE,ji(this.ctx))),i.globalAlpha=this.current.fillAlpha}closeStroke(e,t){this.stroke(e,t)}fill(e,t,r=!0){var c,u,f;const i=this.ctx,o=this.current.fillColor,a=this.current.patternFill;let l=!1;const d=this.current.getClippedPathBoundingBox();if((c=this.dependencyTracker)==null||c.recordDependencies(e,id.fill),a){const p=this.current.tilingPatternDims,g=p&&o.canSkipPatternCanvas(p);if(g){o.drawPattern(this,t,this.pendingEOFill,g,e),this.pendingEOFill=!1,r&&this.consumePath(e,t,d),this.current.tilingPatternDims=null;return}const m=o.isModifyingCurrentTransform()?i.getTransform():null;if((u=this.dependencyTracker)==null||u.save(e),i.save(),i.fillStyle=o.getPattern(i,this,Kc(i),To.FILL,e),m){const y=new Path2D;y.addPath(t,i.getTransform().invertSelf().multiplySelf(m)),t=y}l=!0}this.contentVisible&&d!==null&&(this.pendingEOFill?(i.fill(t,"evenodd"),this.pendingEOFill=!1):i.fill(t)),l&&(i.restore(),(f=this.dependencyTracker)==null||f.restore(e)),r&&this.consumePath(e,t,d)}eoFill(e,t){this.pendingEOFill=!0,this.fill(e,t)}fillStroke(e,t){this.fill(e,t,!1),this.stroke(e,t,!1),this.consumePath(e,t)}eoFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}closeFillStroke(e,t){this.fillStroke(e,t)}closeEOFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}endPath(e,t){this.consumePath(e,t)}rawFillPath(e,t){var r;this.ctx.fill(t),(r=this.dependencyTracker)==null||r.recordDependencies(e,id.rawFillPath).recordOperation(e)}clip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=Xue}eoClip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=EN}beginText(e){var t;this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,(t=this.dependencyTracker)==null||t.recordOpenMarker(e).resetIncrementalData("sameLineText").resetIncrementalData("moveText",e)}endText(e){const t=this.pendingTextPaths,r=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;t!==void 0&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",e),i.recordCloseMarker(e)}if(t!==void 0){const i=new Path2D,o=r.getTransform().invertSelf();for(const{transform:a,x:l,y:d,fontSize:c,path:u}of t)u&&i.addPath(u,new DOMMatrix(a).preMultiplySelf(o).translate(l,d).scale(c,-c));r.clip(i)}delete this.pendingTextPaths}setCharSpacing(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("charSpacing",e),this.current.charSpacing=t}setWordSpacing(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("wordSpacing",e),this.current.wordSpacing=t}setHScale(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("hScale",e),this.current.textHScale=t/100}setLeading(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("leading",e),this.current.leading=-t}setFont(e,t,r){var f,p;(f=this.dependencyTracker)==null||f.recordSimpleData("font",e).recordSimpleDataFromNamed("fontObj",t,e);const i=this.commonObjs.get(t),o=this.current;if(!i)throw new Error(`Can't find font for ${t}`);if(o.fontMatrix=i.fontMatrix||GB,(o.fontMatrix[0]===0||o.fontMatrix[3]===0)&&Bn("Invalid font matrix for font "+t),r<0?(r=-r,o.fontDirection=-1):o.fontDirection=1,this.current.font=i,this.current.fontSize=r,i.isType3Font)return;const a=i.loadedName||"sans-serif",l=((p=i.systemFontInfo)==null?void 0:p.css)||`"${a}", ${i.fallbackName}`;let d="normal";i.black?d="900":i.bold&&(d="bold");const c=i.italic?"italic":"normal";let u=r;r_N&&(u=_N),this.current.fontSizeScale=r/u,this.ctx.font=`${c} ${d} ${u}px ${l}`}setTextRenderingMode(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("textRenderingMode",e),this.current.textRenderingMode=t}setTextRise(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("textRise",e),this.current.textRise=t}moveText(e,t,r){var i;(i=this.dependencyTracker)==null||i.resetIncrementalData("sameLineText").recordIncrementalData("moveText",e),this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=r}setLeadingMoveText(e,t,r){this.setLeading(e,-r),this.moveText(e,t,r)}setTextMatrix(e,t){var i;(i=this.dependencyTracker)==null||i.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",e);const{current:r}=this;r.textMatrix=t,r.textMatrixScale=Math.hypot(t[0],t[1]),r.x=r.lineX=0,r.y=r.lineY=0}nextLine(e){var t;this.moveText(e,0,this.current.leading),(t=this.dependencyTracker)==null||t.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??e)}paintChar(e,t,r,i,o,a){var x,w,S,_;const l=this.ctx,d=this.current,c=d.font,u=d.textRenderingMode,f=d.fontSize/d.fontSizeScale,p=u&Rs.FILL_STROKE_MASK,g=!!(u&Rs.ADD_TO_PATH_FLAG),m=d.patternFill&&!c.missingFile,y=d.patternStroke&&!c.missingFile;let v;if((c.disableFontFace||g||m||y)&&!c.missingFile&&(v=c.getPathGenerator(this.commonObjs,t)),v&&(c.disableFontFace||m||y)){l.save(),l.translate(r,i),l.scale(f,-f),(x=this.dependencyTracker)==null||x.recordCharacterBBox(e,l,c);let b;if(p===Rs.FILL||p===Rs.FILL_STROKE)if(o){b=l.getTransform(),l.setTransform(...o);const C=q(this,Pc,_I).call(this,v,b,o);l.fill(C)}else l.fill(v);if(p===Rs.STROKE||p===Rs.FILL_STROKE)if(a){b||(b=l.getTransform()),l.setTransform(...a);const{a:C,b:T,c:F,d:A}=b,D=yt.inverseTransform(a),P=yt.transform([C,T,F,A,0,0],D);yt.singularValueDecompose2dScale(P,Ol),l.lineWidth*=Math.max(Ol[0],Ol[1])/f,l.stroke(q(this,Pc,_I).call(this,v,b,a))}else l.lineWidth/=f,l.stroke(v);l.restore()}else(p===Rs.FILL||p===Rs.FILL_STROKE)&&(l.fillText(t,r,i),(w=this.dependencyTracker)==null||w.recordCharacterBBox(e,l,c,f,r,i,()=>l.measureText(t))),(p===Rs.STROKE||p===Rs.FILL_STROKE)&&(this.dependencyTracker&&((S=this.dependencyTracker)==null||S.recordCharacterBBox(e,l,c,f,r,i,()=>l.measureText(t)).recordDependencies(e,id.stroke)),l.strokeText(t,r,i));g&&((this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:ji(l),x:r,y:i,fontSize:f,path:v}),(_=this.dependencyTracker)==null||_.recordCharacterBBox(e,l,c,f,r,i))}get isFontSubpixelAAEnabled(){const e=this.canvasFactory.create(10,10),t=e.context;t.scale(1.5,1),t.fillText("I",0,10);const r=t.getImageData(0,0,10,10).data;this.canvasFactory.destroy(e);let i=!1;for(let o=3;o0&&r[o]<255){i=!0;break}return Cn(this,"isFontSubpixelAAEnabled",i)}showText(e,t){var P,L,W,O;this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,id.showText).resetBBox(e),this.current.textRenderingMode&Rs.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",e).inheritPendingDependenciesAsFutureForcedDependencies());const r=this.current,i=r.font;if(i.isType3Font){this.showType3Text(e,t),(P=this.dependencyTracker)==null||P.recordShowTextOperation(e);return}const o=r.fontSize;if(o===0){(L=this.dependencyTracker)==null||L.recordOperation(e);return}const a=this.ctx,l=r.fontSizeScale,d=r.charSpacing,c=r.wordSpacing,u=r.fontDirection,f=r.textHScale*u,p=t.length,g=i.vertical,m=g?1:-1,y=i.defaultVMetrics,v=o*r.fontMatrix[0],x=r.textRenderingMode===Rs.FILL&&!i.disableFontFace&&!r.patternFill;a.save(),r.textMatrix&&a.transform(...r.textMatrix),a.translate(r.x,r.y+r.textRise),u>0?a.scale(f,-1):a.scale(f,1);let w,S;const _=r.textRenderingMode&Rs.FILL_STROKE_MASK,b=_===Rs.FILL||_===Rs.FILL_STROKE,C=_===Rs.STROKE||_===Rs.FILL_STROKE;let T=r.lineWidth;const F=r.textMatrixScale;if(F===0||T===0?C&&(T=this.getSinglePixelWidth()):T/=F,l!==1&&(a.scale(l,l),T/=l),a.lineWidth=T,b&&r.patternFill){a.save();const U=r.fillColor.getPattern(a,this,Kc(a),To.FILL,e);w=ji(a),a.restore(),a.fillStyle=U}if(C&&r.patternStroke){a.save();const U=r.strokeColor.getPattern(a,this,Kc(a),To.STROKE,e);S=ji(a),a.restore(),a.strokeStyle=U}if(i.isInvalidPDFjsFont){const U=[];let M=0;for(const H of t)U.push(H.unicode),M+=H.width;const I=U.join("");if(a.fillText(I,0,0),this.dependencyTracker!==null){const H=a.measureText(I);this.dependencyTracker.recordBBox(e,this.ctx,-H.actualBoundingBoxLeft,H.actualBoundingBoxRight,-H.actualBoundingBoxAscent,H.actualBoundingBoxDescent).recordShowTextOperation(e)}r.x+=M*v*f,a.restore(),this.compose();return}let A=0,D;for(D=0;D0){me=a.measureText(H);const ne=me.width*1e3/o*l;if(reme??a.measureText(H));else if(this.paintChar(e,H,G,te,w,S),z){const ne=G+o*z.offset.x/l,ye=te-o*z.offset.y/l;this.paintChar(e,z.fontChar,ne,ye,w,S)}}const J=g?re*v-I*u:re*v+I*u;A+=J,M&&a.restore()}g?r.y-=A:r.x+=A*f,a.restore(),this.compose(),(O=this.dependencyTracker)==null||O.recordShowTextOperation(e)}showType3Text(e,t){const r=this.ctx,i=this.current,o=i.font,a=i.fontSize,l=i.fontDirection,d=o.vertical?1:-1,c=i.charSpacing,u=i.wordSpacing,f=i.textHScale*l,p=i.fontMatrix||GB,g=t.length,m=i.textRenderingMode===Rs.INVISIBLE;let y,v,x,w;if(m||a===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,r.save(),i.textMatrix&&r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),r.scale(f,l);const S=this.dependencyTracker;for(this.dependencyTracker=S?new Yj(S,e):null,y=0;ynew q3(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new Yj(this.dependencyTracker,l,!0):null)};r=new ij(t,this.ctx,o,i)}else r=this._getPattern(e,t[1],t[2]);return r}setStrokeColorN(e,...t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("strokeColor",e),this.current.strokeColor=this.getColorN_Pattern(e,t),this.current.patternStroke=!0}setFillColorN(e,...t){var i;(i=this.dependencyTracker)==null||i.recordSimpleData("fillColor",e);const r=this.current.fillColor=this.getColorN_Pattern(e,t);this.current.patternFill=!0,this.current.tilingPatternDims=r instanceof ij?[0,0,0,0]:null}setStrokeRGBColor(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(e){var t;(t=this.dependencyTracker)==null||t.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(e){var t;(t=this.dependencyTracker)==null||t.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(e,t,r=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=Uue(this.getObject(e,t)),this.cachedPatterns.set(t,i)),r&&(i.matrix=r),i}shadingFill(e,t){var a;if(!this.contentVisible)return;const r=this.ctx;this.save(e);const i=this._getPattern(e,t);r.fillStyle=i.getPattern(r,this,Kc(r),To.SHADING,e);const o=Kc(r);if(o){const{width:l,height:d}=r.canvas,c=_m.slice();yt.axialAlignedBoundingBox([0,0,l,d],o,c);const[u,f,p,g]=c;this.ctx.fillRect(u,f,p-u,g-f)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);(a=this.dependencyTracker)==null||a.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,id.transform).recordDependencies(e,id.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e)}beginInlineImage(){Hr("Should not call beginInlineImage")}beginImageData(){Hr("Should not call beginImageData")}paintFormXObjectBegin(e,t,r){var i;if(this.contentVisible&&(this.save(e),this.baseTransformStack.push(this.baseTransform),t&&this.transform(e,...t),this.baseTransform=ji(this.ctx),r)){yt.axialAlignedBoundingBox(r,this.baseTransform,this.current.minMax);const[o,a,l,d]=r,c=new Path2D;c.rect(o,a,l-o,d-a),this.ctx.clip(c),(i=this.dependencyTracker)==null||i.recordClipBox(e,this.ctx,o,l,a,d),this.endPath(e)}}paintFormXObjectEnd(e){this.contentVisible&&(this.restore(e),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e,t){var m;if(!this.contentVisible)return;this.save(e);const{inSMaskMode:r}=this;r&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;if(t.isolated||nD("TODO: Support non-isolated groups."),t.knockout&&Bn("Knockout groups not supported."),!t.needsIsolation&&i.globalAlpha===1&&i.globalCompositeOperation==="source-over"&&!r){if(t.bbox){let y=new Path2D;const[v,x,w,S]=t.bbox;if(y.rect(v,x,w-v,S-x),t.matrix){const _=new Path2D;_.addPath(y,new DOMMatrix(t.matrix)),y=_}i.clip(y)}this.groupStack.push(null),this.groupLevel++;return}const o=ji(i);t.matrix&&i.transform(...t.matrix);const a=[0,0,i.canvas.width,i.canvas.height];let l;t.bbox?(l=_m.slice(),yt.axialAlignedBoundingBox(t.bbox,ji(i),l),l=yt.intersect(l,a)||[0,0,0,0]):l=a;const d=Math.floor(l[0]),c=Math.floor(l[1]),u=Math.max(Math.ceil(l[2])-d,1),f=Math.max(Math.ceil(l[3])-c,1);this.current.startNewPathAndClipBox([0,0,u,f]);const p=this.canvasFactory.create(u,f);t.smask&&this.smaskGroupCanvases.push(p);const g=p.context;if(g.translate(-d,-c),g.transform(...o),!t.isolated&&!t.smask&&r&&t.needsIsolation&&(g.save(),g.setTransform(1,0,0,1,0,0),g.drawImage(i.canvas,-d,-c),g.restore()),t.bbox){let y=new Path2D;const[v,x,w,S]=t.bbox;if(y.rect(v,x,w-v,S-x),t.matrix){const _=new Path2D;_.addPath(y,new DOMMatrix(t.matrix)),y=_}g.clip(y)}t.smask&&this.smaskStack.push({canvas:p.canvas,context:g,offsetX:d,offsetY:c,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null}),(!t.smask||this.dependencyTracker)&&(i.setTransform(1,0,0,1,0,0),i.translate(d,c),i.save()),qw(i,g),this.ctx=g,(m=this.dependencyTracker)==null||m.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(e,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),this.groupLevel++}endGroup(e,t){var o;if(!this.contentVisible)return;this.groupLevel--;const r=this.ctx,i=this.groupStack.pop();if(i===null){this.restore(e);return}if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,(o=this.dependencyTracker)==null||o.popBaseTransform(),t.smask)this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform()));else{this.ctx.restore();const a=ji(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...a);const l=_m.slice();yt.axialAlignedBoundingBox([0,0,r.canvas.width,r.canvas.height],a,l),this.ctx.drawImage(r.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy({canvas:r.canvas,context:r}),this.compose(l)}}beginAnnotation(e,t,r,i,o,a){if(q(this,Pc,jI).call(this),Y2(this.ctx),this.ctx.save(),this.save(e),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),r){const l=r[2]-r[0],d=r[3]-r[1];if(a&&this.annotationCanvasMap){i=i.slice(),i[4]-=r[0],i[5]-=r[1],r=r.slice(),r[0]=r[1]=0,r[2]=l,r[3]=d,yt.singularValueDecompose2dScale(ji(this.ctx),Ol);const{viewportScale:c}=this,u=Math.ceil(l*this.outputScaleX*c),f=Math.ceil(d*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,f);const{canvas:p,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(Ol[0],0,0,-Ol[1],0,d*Ol[1]),Y2(this.ctx)}else{Y2(this.ctx),this.endPath(e);const c=new Path2D;c.rect(r[0],r[1],l,d),this.ctx.clip(c)}}this.current=new AN(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...i),this.transform(e,...o),this.baseTransform=ji(this.ctx)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),q(this,Pc,kI).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(e,t){var l;if(!this.contentVisible)return;const r=t.count;t=this.getObject(e,t.data,t),t.count=r;const i=this.ctx,o=this._createMaskCanvas(e,t),a=o.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,o.offsetX,o.offsetY),(l=this.dependencyTracker)==null||l.resetBBox(e).recordBBox(e,this.ctx,o.offsetX,o.offsetX+a.width,o.offsetY,o.offsetY+a.height).recordOperation(e),i.restore(),o.canvasEntry&&this.canvasFactory.destroy(o.canvasEntry),this.compose()}paintImageMaskXObjectRepeat(e,t,r,i=0,o=0,a,l){var f,p,g;if(!this.contentVisible)return;t=this.getObject(e,t.data,t);const d=this.ctx;d.save();const c=ji(d);d.transform(r,i,o,a,0,0);const u=this._createMaskCanvas(e,t);d.setTransform(1,0,0,1,u.offsetX-c[4],u.offsetY-c[5]),(f=this.dependencyTracker)==null||f.resetBBox(e);for(let m=0,y=l.length;mf?u/f:1,l=c>f?c/f:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=l}return this._cachedScaleForStroking}rescaleAndStroke(e,t){const{ctx:r,current:{lineWidth:i}}=this,[o,a]=this.getScaleForStroking();if(o===a){r.lineWidth=(i||1)*o,r.stroke(e);return}const l=r.getLineDash();t&&r.save(),r.scale(o,a),WP.a=1/o,WP.d=1/a;const d=new Path2D;if(d.addPath(e,WP),l.length>0){const c=Math.max(o,a);r.setLineDash(l.map(u=>u/c)),r.lineDashOffset/=c}r.lineWidth=i||1,r.stroke(d),t&&r.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};Pc=new WeakSet,jI=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)},kI=function(){if(this.pageColors){const e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){const t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}},_I=function(e,t,r){const i=new Path2D;return i.addPath(e,new DOMMatrix(r).invertSelf().multiplySelf(t)),i};let db=q3;for(const n in Sh)db.prototype[n]!==void 0&&(db.prototype[Sh[n]]=db.prototype[n]);var Ik,Mk;class oD{constructor(e,t,r){N(this,Ik,null);N(this,Mk,null);ve(this,"_fullReader",null);ve(this,"_rangeReaders",new Set);ve(this,"_source",null);this._source=e,R(this,Ik,t),R(this,Mk,r)}get _progressiveDataLength(){var e;return((e=this._fullReader)==null?void 0:e._loaded)??0}getFullReader(){return Zi(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new(h(this,Ik))(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const r=new(h(this,Mk))(this,e,t);return this._rangeReaders.add(r),r}cancelAllRequests(e){var t;(t=this._fullReader)==null||t.cancel(e);for(const r of new Set(this._rangeReaders))r.cancel(e)}}Ik=new WeakMap,Mk=new WeakMap;class aD{constructor(e){ve(this,"onProgress",null);ve(this,"_contentLength",0);ve(this,"_filename",null);ve(this,"_headersCapability",Promise.withResolvers());ve(this,"_isRangeSupported",!1);ve(this,"_isStreamingSupported",!1);ve(this,"_loaded",0);ve(this,"_stream",null);this._stream=e}_callOnProgress(){var e;(e=this.onProgress)==null||e.call(this,{loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){Hr("Abstract method `read` called")}cancel(e){Hr("Abstract method `cancel` called")}}class lD{constructor(e,t,r){ve(this,"_stream",null);this._stream=e}async read(){Hr("Abstract method `read` called")}cancel(e){Hr("Abstract method `cancel` called")}}function Yue(n){let e=!0,t=r("filename\\*","i").exec(n);if(t){t=t[1];let u=l(t);return u=unescape(u),u=d(u),u=c(u),o(u)}if(t=a(n),t){const u=c(t);return o(u)}if(t=r("filename","i").exec(n),t){t=t[1];let u=l(t);return u=c(u),o(u)}function r(u,f){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',f)}function i(u,f){if(u){if(!/^[\x00-\xFF]+$/.test(f))return f;try{const p=new TextDecoder(u,{fatal:!0}),g=rD(f);f=p.decode(g),e=!1}catch{}}return f}function o(u){return e&&/[\x80-\xff]/.test(u)&&(u=i("utf-8",u),e&&(u=i("iso-8859-1",u))),u}function a(u){const f=[];let p;const g=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(p=g.exec(u))!==null;){let[,y,v,x]=p;if(y=parseInt(y,10),y in f){if(y===0)break;continue}f[y]=[v,x]}const m=[];for(let y=0;y{t._responseOrigin=dD(c.url),lG(c.status,a),this._reader=c.body.getReader();const u=c.headers,{contentLength:f,isRangeSupported:p}=iG({responseHeaders:u,isHttp:!0,rangeChunkSize:o,disableRange:r});this._contentLength=f,this._isRangeSupported=p,this._filename=sG(u),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Ng("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:uD(t),done:!1})}cancel(t){var r;(r=this._reader)==null||r.cancel(t),this._abortController.abort()}}class Zue extends lD{constructor(t,r,i){super(t,r,i);ve(this,"_abortController",new AbortController);ve(this,"_readCapability",Promise.withResolvers());ve(this,"_reader",null);const{url:o,withCredentials:a}=t._source,l=new Headers(t.headers);l.append("Range",`bytes=${r}-${i-1}`),aG(o,l,a,this._abortController).then(d=>{const c=dD(d.url);oG(c,t._responseOrigin),lG(d.status,o),this._reader=d.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:{value:uD(t),done:!1}}cancel(t){var r;(r=this._reader)==null||r.cancel(t),this._abortController.abort()}}function PN(n){return n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function hD(){for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}var HT,dG;class Jue extends oD{constructor(t){super(t,ehe,the);N(this,HT);ve(this,"_progressiveDone",!1);ve(this,"_queuedChunks",[]);const{pdfDataRangeTransport:r}=t,{initialData:i,progressiveDone:o}=r;if((i==null?void 0:i.length)>0){const l=PN(i);this._queuedChunks.push(l)}this._progressiveDone=o;const a=l=>{var d;switch(l.type){case"range":case"progressiveRead":q(this,HT,dG).call(this,l.begin,l.chunk);break;case"progressiveDone":(d=this._fullReader)==null||d.progressiveDone(),this._progressiveDone=!0;break}};r.transportReady(a)}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,r){const i=super.getRangeReader(t,r);return i&&(i.onDone=()=>this._rangeReaders.delete(i),this._source.pdfDataRangeTransport.requestDataRange(t,r)),i}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}HT=new WeakSet,dG=function(t,r){const i=PN(r);if(t===void 0)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const o=this._rangeReaders.keys().find(a=>a._begin===t);Zi(o,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),o._enqueue(i)}};var zk;class ehe extends aD{constructor(t){super(t);N(this,zk,hD.bind(this));ve(this,"_done",!1);ve(this,"_queuedChunks",null);ve(this,"_requests",[]);const{pdfDataRangeTransport:r,disableRange:i,disableStream:o}=t._source,{length:a,contentDispositionFilename:l}=r;this._queuedChunks=t._queuedChunks||[];for(const c of this._queuedChunks)this._loaded+=c.byteLength;this._done=t._progressiveDone,this._contentLength=a,this._isStreamingSupported=!o,this._isRangeSupported=!i,R3(l)&&(this._filename=l),this._headersCapability.resolve();const d=this._loaded;Promise.resolve().then(()=>{d>0&&this._loaded===d&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,h(this,zk).call(this)}progressiveDone(){this._done||(this._done=!0),this._queuedChunks.length===0&&h(this,zk).call(this)}}zk=new WeakMap;var Ok;class the extends lD{constructor(t,r,i){super(t,r,i);N(this,Ok,hD.bind(this));ve(this,"onDone",null);ve(this,"_begin",-1);ve(this,"_done",!1);ve(this,"_queuedChunk",null);ve(this,"_requests",[]);this._begin=r}_enqueue(t){var r;this._done||(this._requests.length===0?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),h(this,Ok).call(this)),this._done=!0,(r=this.onDone)==null||r.call(this))}async read(){if(this._queuedChunk){const r=this._queuedChunk;return this._queuedChunk=null,{value:r,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){var r;this._done=!0,h(this,Ok).call(this),(r=this.onDone)==null||r.call(this)}}Ok=new WeakMap;const UP=200,RN=206;function nhe(n){return typeof n!="string"?n:rD(n).buffer}var fu,d1,cG,uG;class rhe extends oD{constructor(t){super(t,ihe,she);N(this,d1);N(this,fu,new WeakMap);ve(this,"_responseOrigin",null);const{httpHeaders:r,url:i}=t;this.url=i,this.isHttp=/https?:/.test(i.protocol),this.headers=rG(this.isHttp,r)}_request(t){const r=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};h(this,fu).set(r,i),r.open("GET",this.url),r.withCredentials=this._source.withCredentials;for(const[o,a]of this.headers)r.setRequestHeader(o,a);return this.isHttp&&"begin"in t&&"end"in t?(r.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.validateStatus=o=>o===RN||o===UP):i.validateStatus=o=>o===UP,r.responseType="arraybuffer",Zi(t.onError,"Expected `onError` callback to be provided."),r.onerror=()=>t.onError(r.status),r.onreadystatechange=q(this,d1,uG).bind(this,r),r.onprogress=q(this,d1,cG).bind(this,r),r.send(null),r}_abortRequest(t){h(this,fu).has(t)&&(h(this,fu).delete(t),t.abort())}getRangeReader(t,r){const i=super.getRangeReader(t,r);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}}fu=new WeakMap,d1=new WeakSet,cG=function(t,r){var o;const i=h(this,fu).get(t);(o=i==null?void 0:i.onProgress)==null||o.call(i,r)},uG=function(t,r){const i=h(this,fu).get(t);if(!i||(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),t.readyState!==4)||!h(this,fu).has(t))return;if(h(this,fu).delete(t),t.status===0&&this.isHttp){i.onError(t.status);return}const o=t.status||UP;if(!i.validateStatus(o)){i.onError(t.status);return}const a=nhe(t.response);if(o===RN){const l=t.getResponseHeader("Content-Range");/bytes (\d+)-(\d+)\/(\d+)/.test(l)?i.onDone(a):(Bn('Missing or invalid "Content-Range" header.'),i.onError(0))}else a?i.onDone(a):i.onError(t.status)};var Lk,Nu,hG,fG,pG,gG;class ihe extends aD{constructor(t){super(t);N(this,Nu);N(this,Lk,hD.bind(this));ve(this,"_cachedChunks",[]);ve(this,"_done",!1);ve(this,"_requests",[]);ve(this,"_storedError",null);this._fullRequestXhr=t._request({onHeadersReceived:q(this,Nu,hG).bind(this),onDone:q(this,Nu,fG).bind(this),onError:q(this,Nu,pG).bind(this),onProgress:q(this,Nu,gG).bind(this)})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),h(this,Lk).call(this),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}Lk=new WeakMap,Nu=new WeakSet,hG=function(){const t=this._stream,{disableRange:r,rangeChunkSize:i}=t._source,o=this._fullRequestXhr;t._responseOrigin=dD(o.responseURL);const a=o.getAllResponseHeaders(),l=new Headers(a?a.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(u=>{const[f,...p]=u.split(": ");return[f,p.join(": ")]}):[]),{contentLength:d,isRangeSupported:c}=iG({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:i,disableRange:r});this._contentLength=d,this._isRangeSupported=c,this._filename=sG(l),this._isRangeSupported&&t._abortRequest(o),this._headersCapability.resolve()},fG=function(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,this._cachedChunks.length===0&&h(this,Lk).call(this)},pG=function(t){this._storedError=cD(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const r of this._requests)r.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0},gG=function(t){var r;(r=this.onProgress)==null||r.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})};var Nk,Ff,mG,yG,CI;class she extends lD{constructor(t,r,i){super(t,r,i);N(this,Ff);N(this,Nk,hD.bind(this));ve(this,"onClosed",null);ve(this,"_done",!1);ve(this,"_queuedChunk",null);ve(this,"_requests",[]);ve(this,"_storedError",null);this._requestXhr=t._request({begin:r,end:i,onHeadersReceived:q(this,Ff,mG).bind(this),onDone:q(this,Ff,yG).bind(this),onError:q(this,Ff,CI).bind(this),onProgress:null})}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const r=this._queuedChunk;return this._queuedChunk=null,{value:r,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){var r;this._done=!0,h(this,Nk).call(this),this._stream._abortRequest(this._requestXhr),(r=this.onClosed)==null||r.call(this)}}Nk=new WeakMap,Ff=new WeakSet,mG=function(){var r;const t=dD((r=this._requestXhr)==null?void 0:r.responseURL);try{oG(t,this._stream._responseOrigin)}catch(i){this._storedError=i,q(this,Ff,CI).call(this,0)}},yG=function(t){var r;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,h(this,Nk).call(this),(r=this.onClosed)==null||r.call(this)},CI=function(t){this._storedError??(this._storedError=cD(t,this._stream.url));for(const r of this._requests)r.reject(this._storedError);this._requests.length=0,this._queuedChunk=null};function xG(n,e=null){const t=process.getBuiltinModule("fs"),{Readable:r}=process.getBuiltinModule("stream"),i=t.createReadStream(n,e);return r.toWeb(i)}class ohe extends oD{constructor(e){super(e,ahe,lhe);const{url:t}=e;Zi(t.protocol==="file:","PDFNodeStream only supports file:// URLs.")}}class ahe extends aD{constructor(t){super(t);ve(this,"_reader",null);const{disableRange:r,disableStream:i,rangeChunkSize:o,url:a}=t._source;this._isStreamingSupported=!i,process.getBuiltinModule("fs/promises").lstat(a).then(d=>{const c=xG(a);this._reader=c.getReader();const{size:u}=d;this._contentLength=u,this._isRangeSupported=!r&&u>2*o,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Ng("Streaming is disabled.")),this._headersCapability.resolve()}).catch(d=>{d.code==="ENOENT"&&(d=cD(0,a)),this._headersCapability.reject(d)})}async read(){await this._headersCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:uD(t),done:!1})}cancel(t){var r;(r=this._reader)==null||r.cancel(t)}}class lhe extends lD{constructor(t,r,i){super(t,r,i);ve(this,"_readCapability",Promise.withResolvers());ve(this,"_reader",null);const{url:o}=t._source;try{const a=xG(o,{start:r,end:i-1});this._reader=a.getReader(),this._readCapability.resolve()}catch(a){this._readCapability.reject(a)}}async read(){await this._readCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:{value:uD(t),done:!1}}cancel(t){var r;(r=this._reader)==null||r.cancel(t)}}function dhe(n){return rj(n)?Que:zl?ohe:rhe}var Wk,Uk;class Bu{static get workerPort(){return h(this,Wk)}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw new Error("Invalid `workerPort` type.");R(this,Wk,e)}static get workerSrc(){return h(this,Uk)}static set workerSrc(e){if(typeof e!="string")throw new Error("Invalid `workerSrc` type.");R(this,Uk,e)}}Wk=new WeakMap,Uk=new WeakMap,N(Bu,Wk,null),N(Bu,Uk,"");var nv,Hk;class che{constructor({parsedData:e,rawData:t}){N(this,nv);N(this,Hk);R(this,nv,e),R(this,Hk,t)}getRaw(){return h(this,Hk)}get(e){return h(this,nv).get(e)??null}[Symbol.iterator](){return h(this,nv).entries()}}nv=new WeakMap,Hk=new WeakMap;const Ax=Symbol("INTERNAL");var qk,Vk,Gk,rv;class uhe{constructor(e,{name:t,intent:r,usage:i,rbGroups:o}){N(this,qk,!1);N(this,Vk,!1);N(this,Gk,!1);N(this,rv,!0);R(this,qk,!!(e&Rl.DISPLAY)),R(this,Vk,!!(e&Rl.PRINT)),this.name=t,this.intent=r,this.usage=i,this.rbGroups=o}get visible(){if(h(this,Gk))return h(this,rv);if(!h(this,rv))return!1;const{print:e,view:t}=this.usage;return h(this,qk)?(t==null?void 0:t.viewState)!=="OFF":h(this,Vk)?(e==null?void 0:e.printState)!=="OFF":!0}_setVisible(e,t,r=!1){e!==Ax&&Hr("Internal method `_setVisible` called."),R(this,Gk,r),R(this,rv,t)}}qk=new WeakMap,Vk=new WeakMap,Gk=new WeakMap,rv=new WeakMap;var Np,oi,iv,sv,Kk,AI;class hhe{constructor(e,t=Rl.DISPLAY){N(this,Kk);N(this,Np,null);N(this,oi,new Map);N(this,iv,null);N(this,sv,null);if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,R(this,sv,e.order);for(const r of e.groups)h(this,oi).set(r.id,new uhe(t,r));if(e.baseState==="OFF")for(const r of h(this,oi).values())r._setVisible(Ax,!1);for(const r of e.on)h(this,oi).get(r)._setVisible(Ax,!0);for(const r of e.off)h(this,oi).get(r)._setVisible(Ax,!1);R(this,iv,this.getHash())}}isVisible(e){if(h(this,oi).size===0)return!0;if(!e)return nD("Optional content group not defined."),!0;if(e.type==="OCG")return h(this,oi).has(e.id)?h(this,oi).get(e.id).visible:(Bn(`Optional content group not found: ${e.id}`),!0);if(e.type==="OCMD"){if(e.expression)return q(this,Kk,AI).call(this,e.expression);if(!e.policy||e.policy==="AnyOn"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(h(this,oi).get(t).visible)return!0}return!1}else if(e.policy==="AllOn"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(!h(this,oi).get(t).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(!h(this,oi).get(t).visible)return!0}return!1}else if(e.policy==="AllOff"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(h(this,oi).get(t).visible)return!1}return!0}return Bn(`Unknown optional content policy ${e.policy}.`),!0}return Bn(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,r=!0){var o;const i=h(this,oi).get(e);if(!i){Bn(`Optional content group not found: ${e}`);return}if(r&&t&&i.rbGroups.length)for(const a of i.rbGroups)for(const l of a)l!==e&&((o=h(this,oi).get(l))==null||o._setVisible(Ax,!1,!0));i._setVisible(Ax,!!t,!0),R(this,Np,null)}setOCGState({state:e,preserveRB:t}){let r;for(const i of e){switch(i){case"ON":case"OFF":case"Toggle":r=i;continue}const o=h(this,oi).get(i);if(o)switch(r){case"ON":this.setVisibility(i,!0,t);break;case"OFF":this.setVisibility(i,!1,t);break;case"Toggle":this.setVisibility(i,!o.visible,t);break}}R(this,Np,null)}get hasInitialVisibility(){return h(this,iv)===null||this.getHash()===h(this,iv)}getOrder(){return h(this,oi).size?h(this,sv)?h(this,sv).slice():[...h(this,oi).keys()]:null}getGroup(e){return h(this,oi).get(e)||null}getHash(){if(h(this,Np)!==null)return h(this,Np);const e=new gI;for(const[t,r]of h(this,oi))e.update(`${t}:${r.visible}`);return R(this,Np,e.hexdigest())}[Symbol.iterator](){return h(this,oi).entries()}}Np=new WeakMap,oi=new WeakMap,iv=new WeakMap,sv=new WeakMap,Kk=new WeakSet,AI=function(e){const t=e.length;if(t<2)return!0;const r=e[0];for(let i=1;ip===g+1)&&R(this,bs,null)}deletePages(e){q(this,ra,jS).call(this);const t=h(this,bs),r=q(this,ra,kS).call(this);R(this,pu,{pageNumberToId:t.slice(),pagesNumber:h(this,ko),prevPageNumbers:h(this,pc).slice()});const i=h(this,ko)-e.length;R(this,ko,i);const o=R(this,bs,new Uint32Array(i));R(this,pc,new Int32Array(i));let a=0,l=0;for(const d of e){const c=d-1;c!==a&&(o.set(t.subarray(a,c),l),l+=c-a),a=c+1}ah(this,bs)[t-1])})}cancelCopy(){R(this,my,null)}pastePages(e){q(this,ra,jS).call(this);const t=h(this,bs),r=q(this,ra,kS).call(this),{pageNumbers:i,pageIds:o}=h(this,my),a=h(this,ko)+i.length;R(this,ko,a);const l=R(this,bs,new Uint32Array(a));R(this,pc,new Int32Array(a)),l.set(t.subarray(0,e),0),l.set(o,e),l.set(t.subarray(e),e+i.length),q(this,ra,q5).call(this,r,null,e,i),R(this,my,null)}hasBeenAltered(){return h(this,bs)!==null}getPageMappingForSaving(e=null){e??(e=q(this,ra,kS).call(this));let t=0;for(const i of e.values())t=Math.max(t,i.length);const r=new Array(t);for(let i=0;ia[0]-l[0]);for(let a=0,l=i.length;ar-i);const t=new Map;for(let r=0,i=e.length;r=r&&c({...Promise.withResolvers(),data:Tx});var bd;class bG{constructor(){N(this,bd,new Map)}get(e,t=null){if(t){const i=h(this,bd).getOrInsertComputed(e,BN);return i.promise.then(()=>t(i.data)),null}const r=h(this,bd).get(e);if(!r||r.data===Tx)throw new Error(`Requesting object that isn't resolved yet ${e}.`);return r.data}has(e){const t=h(this,bd).get(e);return!!t&&t.data!==Tx}delete(e){const t=h(this,bd).get(e);return!t||t.data===Tx?!1:(h(this,bd).delete(e),!0)}resolve(e,t=null){const r=h(this,bd).getOrInsertComputed(e,BN);if(r.data!==Tx)throw new Error(`Object already resolved ${e}.`);r.data=t,r.resolve()}clear(){var e;for(const{data:t}of h(this,bd).values())(e=t==null?void 0:t.bitmap)==null||e.close();h(this,bd).clear()}*[Symbol.iterator](){for(const[e,{data:t}]of h(this,bd))t!==Tx&&(yield[e,t])}}bd=new WeakMap;const phe=1e5,IN=30;var o7,Wp,ga,Xk,Yk,ov,yy,qh,Qk,$k,xy,Zk,av,Up,lv,Jk,dv,by,e_,t_,cv,vy,n_,uv,hv,Df,vG,wG,TI,Kl,V5,FI,SG,jG;const vo=class vo{constructor({textContentSource:e,images:t,container:r,viewport:i}){N(this,Df);N(this,Wp,Promise.withResolvers());N(this,ga,null);N(this,Xk,!1);N(this,Yk,!!((o7=globalThis.FontInspector)!=null&&o7.enabled));N(this,ov,null);N(this,yy,null);N(this,qh,null);N(this,Qk,0);N(this,$k,0);N(this,xy,null);N(this,Zk,null);N(this,av,0);N(this,Up,0);N(this,lv,Object.create(null));N(this,Jk,[]);N(this,dv,null);N(this,by,[]);N(this,e_,new WeakMap);N(this,t_,null);var c;if(e instanceof ReadableStream)R(this,dv,e);else if(typeof e=="object")R(this,dv,new ReadableStream({start(u){u.enqueue(e),u.close()}}));else throw new Error('No "textContentSource" parameter specified.');R(this,ga,R(this,Zk,r)),R(this,ov,t),R(this,Up,i.scale*Lu.pixelRatio),R(this,av,i.rotation),R(this,qh,{div:null,properties:null,ctx:null});const{pageWidth:o,pageHeight:a,pageX:l,pageY:d}=i.rawDims;R(this,t_,[1,0,0,-1,-l,d+a]),R(this,$k,o),R(this,Qk,a),q(c=vo,Kl,SG).call(c),r.style.setProperty("--min-font-size",h(vo,uv)),k0(r,i),h(this,Wp).promise.finally(()=>{h(vo,hv).delete(this),R(this,qh,null),R(this,lv,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:e,isFirefox:t}=Ds.platform;return Cn(this,"fontFamilyMap",new Map([["sans-serif",`${e&&t?"Calibri, ":""}sans-serif`],["monospace",`${e&&t?"Lucida Console, ":""}monospace`]]))}render(){h(this,ov)&&h(this,ga).append(h(this,ov).render());const e=()=>{h(this,xy).read().then(({value:t,done:r})=>{if(r){h(this,Wp).resolve();return}h(this,yy)??R(this,yy,t.lang),Object.assign(h(this,lv),t.styles),q(this,Df,vG).call(this,t.items),e()},h(this,Wp).reject)};return R(this,xy,h(this,dv).getReader()),h(vo,hv).add(this),e(),h(this,Wp).promise}update({viewport:e,onBefore:t=null}){var o;const r=e.scale*Lu.pixelRatio,i=e.rotation;if(i!==h(this,av)&&(t==null||t(),R(this,av,i),k0(h(this,Zk),{rotation:i})),r!==h(this,Up)){t==null||t(),R(this,Up,r);const a={div:null,properties:null,ctx:q(o=vo,Kl,V5).call(o,h(this,yy))};for(const l of h(this,by))a.properties=h(this,e_).get(l),a.div=l,q(this,Df,TI).call(this,a)}}cancel(){var t;const e=new Ng("TextLayer task cancelled.");(t=h(this,xy))==null||t.cancel(e).catch(()=>{}),R(this,xy,null),h(this,Wp).reject(e)}get textDivs(){return h(this,by)}get textContentItemsStr(){return h(this,Jk)}static cleanup(){if(!(h(this,hv).size>0)){h(this,cv).clear();for(const{canvas:e}of h(this,vy).values())e.remove();h(this,vy).clear()}}};Wp=new WeakMap,ga=new WeakMap,Xk=new WeakMap,Yk=new WeakMap,ov=new WeakMap,yy=new WeakMap,qh=new WeakMap,Qk=new WeakMap,$k=new WeakMap,xy=new WeakMap,Zk=new WeakMap,av=new WeakMap,Up=new WeakMap,lv=new WeakMap,Jk=new WeakMap,dv=new WeakMap,by=new WeakMap,e_=new WeakMap,t_=new WeakMap,cv=new WeakMap,vy=new WeakMap,n_=new WeakMap,uv=new WeakMap,hv=new WeakMap,Df=new WeakSet,vG=function(e){var i,o;if(h(this,Xk))return;(o=h(this,qh)).ctx??(o.ctx=q(i=vo,Kl,V5).call(i,h(this,yy)));const t=h(this,by),r=h(this,Jk);for(const a of e){if(t.length>phe){Bn("Ignoring additional textDivs for performance reasons."),R(this,Xk,!0);return}if(a.str===void 0){if(a.type==="beginMarkedContentProps"||a.type==="beginMarkedContent"){const l=h(this,ga);R(this,ga,document.createElement("span")),h(this,ga).classList.add("markedContent"),a.id&&h(this,ga).setAttribute("id",`${a.id}`),a.tag==="Artifact"&&(h(this,ga).ariaHidden=!0),l.append(h(this,ga))}else a.type==="endMarkedContent"&&R(this,ga,h(this,ga).parentNode);continue}r.push(a.str),q(this,Df,wG).call(this,a)}},wG=function(e){var m;const t=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};h(this,by).push(t);const i=yt.transform(h(this,t_),e.transform);let o=Math.atan2(i[1],i[0]);const a=h(this,lv)[e.fontName];a.vertical&&(o+=Math.PI/2);let l=h(this,Yk)&&a.fontSubstitution||a.fontFamily;l=vo.fontFamilyMap.get(l)||l;const d=Math.hypot(i[2],i[3]),c=d*q(m=vo,Kl,jG).call(m,l,a,h(this,yy));let u,f;o===0?(u=i[4],f=i[5]-c):(u=i[4]+c*Math.sin(o),f=i[5]-c*Math.cos(o));const p=t.style;p.left=`${(100*u/h(this,$k)).toFixed(2)}%`,p.top=`${(100*f/h(this,Qk)).toFixed(2)}%`,p.setProperty("--font-height",`${d.toFixed(2)}px`),p.fontFamily=l,r.fontSize=d,t.setAttribute("role","presentation"),t.textContent=e.str,t.dir=e.dir,h(this,Yk)&&(t.dataset.fontName=a.fontSubstitutionLoadedName||e.fontName),o!==0&&(r.angle=o*(180/Math.PI));let g=!1;if(e.str.length>1)g=!0;else if(e.str!==" "&&e.transform[0]!==e.transform[3]){const y=Math.abs(e.transform[0]),v=Math.abs(e.transform[3]);y!==v&&Math.max(y,v)/Math.min(y,v)>1.5&&(g=!0)}if(g&&(r.canvasWidth=a.vertical?e.height:e.width),h(this,e_).set(t,r),h(this,qh).div=t,h(this,qh).properties=r,q(this,Df,TI).call(this,h(this,qh)),r.hasText&&h(this,ga).append(t),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),h(this,ga).append(y)}},TI=function(e){var a;const{div:t,properties:r,ctx:i}=e,{style:o}=t;if(r.canvasWidth!==0&&r.hasText){const{fontFamily:l}=o,{canvasWidth:d,fontSize:c}=r;q(a=vo,Kl,FI).call(a,i,c*h(this,Up),l);const{width:u}=i.measureText(t.textContent);u>0&&o.setProperty("--scale-x",d*h(this,Up)/u)}r.angle!==0&&o.setProperty("--rotate",`${r.angle}deg`)},Kl=new WeakSet,V5=function(e=null){let t=h(this,vy).get(e||(e=""));if(!t){const r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=e,document.body.append(r),t=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),h(this,vy).set(e,t),h(this,n_).set(t,{size:0,family:""})}return t},FI=function(e,t,r){const i=h(this,n_).get(e);t===i.size&&r===i.family||(e.font=`${t}px ${r}`,i.size=t,i.family=r)},SG=function(){if(h(this,uv)!==null)return;const e=document.createElement("div");e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize="1px",e.style.position="absolute",e.textContent="X",document.body.append(e),R(this,uv,e.getBoundingClientRect().height),e.remove()},jG=function(e,t,r){const i=h(this,cv).get(e);if(i)return i;const o=q(this,Kl,V5).call(this,r);o.canvas.width=o.canvas.height=IN,q(this,Kl,FI).call(this,o,IN,e);const a=o.measureText(""),l=a.fontBoundingBoxAscent,d=Math.abs(a.fontBoundingBoxDescent);o.canvas.width=o.canvas.height=0;let c=.8;return l?c=l/(l+d):(Ds.platform.isFirefox&&Bn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),t.ascent?c=t.ascent:t.descent&&(c=1+t.descent)),h(this,cv).set(e,c),c},N(vo,Kl),N(vo,cv,new Map),N(vo,vy,new Map),N(vo,n_,new WeakMap),N(vo,uv,null),N(vo,hv,new Set);let Qj=vo;const ghe=100;function kG(n={}){typeof n=="string"||n instanceof URL?n={url:n}:(n instanceof ArrayBuffer||ArrayBuffer.isView(n))&&(n={data:n});const e=new DI,{docId:t}=e,r=n.url?wue(n.url):null,i=n.data?Sue(n.data):null,o=n.httpHeaders||null,a=n.withCredentials===!0,l=n.password??null,d=n.range instanceof _G?n.range:null,c=Number.isInteger(n.rangeChunkSize)&&n.rangeChunkSize>0?n.rangeChunkSize:2**16;let u=n.worker instanceof $j?n.worker:null;const f=n.verbosity,p=typeof n.docBaseUrl=="string"&&!iD(n.docBaseUrl)?n.docBaseUrl:null,g=G2(n.cMapUrl),m=n.cMapPacked!==!1,y=G2(n.iccUrl),v=G2(n.standardFontDataUrl),x=G2(n.wasmUrl),w=n.stopAtErrors!==!0,S=Number.isInteger(n.maxImageSize)&&n.maxImageSize>-1?n.maxImageSize:-1,_=typeof n.isOffscreenCanvasSupported=="boolean"?n.isOffscreenCanvasSupported:!zl,b=typeof n.isImageDecoderSupported=="boolean"?n.isImageDecoderSupported:!zl&&(Ds.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(n.canvasMaxAreaInBytes)?n.canvasMaxAreaInBytes:-1,T=typeof n.disableFontFace=="boolean"?n.disableFontFace:zl,F=n.fontExtraProperties===!0,A=n.enableXfa===!0,D=n.ownerDocument||globalThis.document,P=n.disableRange===!0,L=n.disableStream===!0,W=n.disableAutoFetch===!0,O=n.pdfBug===!0,U=n.CanvasFactory||(zl?Due:Cue),M=n.FilterFactory||(zl?Fue:Aue),I=n.BinaryDataFactory||(zl?Eue:SN),H=n.enableHWA===!0,G=n.enableWebGPU===!0?Bue():Promise.resolve(!1),te=n.useWasm!==!1,re=n.pagesMapper||new fhe,me=typeof n.useSystemFonts=="boolean"?n.useSystemFonts:!zl&&!T,J=typeof n.useWorkerFetch=="boolean"?n.useWorkerFetch:!!(I===SN&&g&&m&&v&&x&&rj(g,document.baseURI)&&rj(v,document.baseURI)&&rj(x,document.baseURI)),ne=null;Hce(f);const ye={canvasFactory:new U({ownerDocument:D,enableHWA:H}),filterFactory:new M({docId:t,ownerDocument:D}),binaryDataFactory:J?null:new I({cMapUrl:g,standardFontDataUrl:v,wasmUrl:x})};u||(u=$j.create({verbosity:f,port:Bu.workerPort}),e._worker=u);const ke={docId:t,apiVersion:"5.7.284",data:i,password:l,disableAutoFetch:W,rangeChunkSize:c,docBaseUrl:p,enableXfa:A,evaluatorOptions:{maxImageSize:S,disableFontFace:T,ignoreErrors:w,isOffscreenCanvasSupported:_,isImageDecoderSupported:b,canvasMaxAreaInBytes:C,fontExtraProperties:F,useSystemFonts:me,useWasm:te,useWorkerFetch:J,cMapUrl:g,cMapPacked:m,iccUrl:y,standardFontDataUrl:v,wasmUrl:x,hasGPU:!1}},Ye={ownerDocument:D,pdfBug:O,styleElement:ne,enableHWA:H,loadingParams:{disableAutoFetch:W,enableXfa:A}};return Promise.all([u.promise,G]).then(function([,De]){if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");ke.evaluatorOptions.hasGPU=De;const qe=u.messageHandler.sendWithPromise("GetDocRequest",ke,i?[i.buffer]:null);let ue;if(!i)if(d)ue=new Jue({pdfDataRangeTransport:d,disableRange:P,disableStream:L});else if(r){const Ze=dhe(r);ue=new Ze({url:r,httpHeaders:o,withCredentials:a,rangeChunkSize:c,disableRange:P,disableStream:L})}else throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");return qe.then(Ze=>{if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const ee=new xS(t,Ze,u.port),Z=new yhe(ee,e,ue,Ye,ye,re);e._transport=Z,ee.send("Ready",null)})}).catch(e._capability.reject),e}var qT;const VT=class VT{constructor(){ve(this,"_capability",Promise.withResolvers());ve(this,"_transport",null);ve(this,"_worker",null);ve(this,"docId",`d${Gi(VT,qT)._++}`);ve(this,"destroyed",!1);ve(this,"onPassword",null);ve(this,"onProgress",null)}get promise(){return this._capability.promise}async destroy(){var e,t,r,i;this.destroyed=!0;try{(e=this._worker)!=null&&e.port&&(this._worker._pendingDestroy=!0),await((t=this._transport)==null?void 0:t.destroy())}catch(o){throw(r=this._worker)!=null&&r.port&&delete this._worker._pendingDestroy,o}this._transport=null,(i=this._worker)==null||i.destroy(),this._worker=null}async getData(){return this._transport.getData()}};qT=new WeakMap,N(VT,qT,0);let DI=VT;var fv,wy;class _G{constructor(e,t,r=!1,i=null){N(this,fv,Promise.withResolvers());N(this,wy,null);this.length=e,this.initialData=t,this.progressiveDone=r,this.contentDispositionFilename=i,Object.defineProperty(this,"onDataProgress",{value:()=>{eue("`PDFDataRangeTransport.prototype.onDataProgress` - method was removed, since loading progress is now reported automatically through the `PDFDataTransportStream` class (and related code).")}})}onDataRange(e,t){h(this,wy).call(this,{type:"range",begin:e,chunk:t})}onDataProgressiveRead(e){h(this,fv).promise.then(()=>{h(this,wy).call(this,{type:"progressiveRead",chunk:e})})}onDataProgressiveDone(){h(this,fv).promise.then(()=>{h(this,wy).call(this,{type:"progressiveDone"})})}transportReady(e){R(this,wy,e),h(this,fv).resolve()}requestDataRange(e,t){Hr("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}fv=new WeakMap,wy=new WeakMap;class mhe{constructor(e,t){this._pdfInfo=e,this._transport=t}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Cn(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(e,t){return this._transport.getAnnotationsByType(e,t)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(e){return this._transport.extractPages(e)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(e){return this._transport.getRawData(e)}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}var Vh,Sy,jy,_S;const V3=class V3{constructor(e,t,r,i,o=!1){N(this,jy);N(this,Vh,!1);N(this,Sy,null);this._pageIndex=e,this._pageInfo=t,this._transport=r,this._stats=o?new uN:null,this._pdfBug=o,this.commonObjs=r.commonObjs,this.objs=new bG,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,R(this,Sy,i),this.imageCoordinates=null}clone(e){const t=new V3(e,this._pageInfo,this._transport,h(this,Sy),this._pdfBug);return t.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(t),t}get pageNumber(){return this._pageIndex+1}set pageNumber(e){this._pageIndex=e-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:r=0,offsetY:i=0,dontFlip:o=!1}={}){return new dC({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:r,offsetY:i,dontFlip:o})}getAnnotations({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Cn(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var e;return((e=this._transport._htmlForXfa)==null?void 0:e.children[this._pageIndex])||null}render({canvasContext:e,canvas:t=e.canvas,viewport:r,intent:i="display",annotationMode:o=Ru.ENABLE,transform:a=null,background:l=null,optionalContentConfigPromise:d=null,annotationCanvasMap:c=null,pageColors:u=null,printAnnotationStorage:f=null,isEditing:p=!1,recordImages:g=!1,recordOperations:m=!1,operationsFilter:y=null}){var W,O,U;(W=this._stats)==null||W.time("Overall");const v=this._transport.getRenderingIntent(i,o,f,p),{renderingIntent:x,cacheKey:w}=v;R(this,Vh,!1),d||(d=this._transport.getOptionalContentConfig(x));const S=this._intentStates.getOrInsertComputed(w,QB);S.streamReaderCancelTimeout&&(clearTimeout(S.streamReaderCancelTimeout),S.streamReaderCancelTimeout=null);const _=!!(x&Rl.PRINT);S.displayReadyCapability||(S.displayReadyCapability=Promise.withResolvers(),S.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(O=this._stats)==null||O.time("Page Request"),this._pumpOperatorList(v));const b=!!(this._pdfBug&&((U=globalThis.StepperManager)!=null&&U.enabled)),C=!!t&&!this.recordedBBoxes&&(m||b),T=!!t&&!this.imageCoordinates&&g,F=M=>{var I,H,z,G;if(S.renderTasks.delete(P),C){const te=(I=P.gfx)==null?void 0:I.dependencyTracker.take();te&&((H=P.stepper)==null||H.setOperatorBBoxes(te,P.gfx.dependencyTracker.takeDebugMetadata()),m&&(this.recordedBBoxes=te))}T&&!M&&(this.imageCoordinates=(z=P.gfx)==null?void 0:z.imagesTracker.take()),_&&R(this,Vh,!0),q(this,jy,_S).call(this),M?(P.capability.reject(M),this._abortOperatorList({intentState:S,reason:M instanceof Error?M:new Error(M)})):P.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(G=globalThis.Stats)!=null&&G.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let A=null,D=null;(C||T)&&(D=new hue(t,S.operatorList.length)),C&&(A=new fue(D,b));const P=new PI({callback:F,params:{canvas:t,canvasContext:e,dependencyTracker:A??D,imagesTracker:T?new xI(t):null,viewport:r,transform:a,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:S.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!_,pdfBug:this._pdfBug,pageColors:u,enableHWA:this._transport.enableHWA,operationsFilter:y});(S.renderTasks||(S.renderTasks=new Set)).add(P);const L=P.task;return Promise.all([S.displayReadyCapability.promise,d]).then(([M,I])=>{var H;if(this.destroyed){F();return}if((H=this._stats)==null||H.time("Rendering"),!(I.renderingIntent&x))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");P.initializeGraphics({transparency:M,optionalContentConfig:I}),P.operatorListChanged()}).catch(F),L}getOperatorList({intent:e="display",annotationMode:t=Ru.ENABLE,printAnnotationStorage:r=null,isEditing:i=!1}={}){var c;function o(){l.operatorList.lastChunk&&(l.opListReadCapability.resolve(l.operatorList),l.renderTasks.delete(d))}const a=this._transport.getRenderingIntent(e,t,r,i,!0),l=this._intentStates.getOrInsertComputed(a.cacheKey,QB);let d;return l.opListReadCapability||(d=Object.create(null),d.operatorListChanged=o,l.opListReadCapability=Promise.withResolvers(),(l.renderTasks||(l.renderTasks=new Set)).add(d),l.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(c=this._stats)==null||c.time("Page Request"),this._pumpOperatorList(a)),l.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:h(this,Sy).getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(i){return i.items.length}})}async getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(i=>Kj.textContent(i));const t=this.streamTextContent(e),r={items:[],styles:Object.create(null),lang:null};for await(const i of t)r.lang??(r.lang=i.lang),Object.assign(r.styles,i.styles),r.items.push(...i.items);return r}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const e=[];for(const t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:new Error("Page was destroyed."),force:!0}),!t.opListReadCapability)for(const r of t.renderTasks)e.push(r.completed),r.cancel();return this.objs.clear(),R(this,Vh,!1),Promise.all(e)}cleanup(e=!1){R(this,Vh,!0);const t=q(this,jy,_S).call(this);return e&&t&&this._stats&&(this._stats=new uN),t}_startRenderPage(e,t){var i,o;const r=this._intentStates.get(t);r&&((i=this._stats)==null||i.timeEnd("Page Request"),(o=r.displayReadyCapability)==null||o.resolve(e))}_renderPageChunk(e,t){for(let r=0,i=e.length;r{d.read().then(({value:f,done:p})=>{if(p){c.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(f,c),u())},f=>{if(c.streamReader=null,!this._transport.destroyed){if(c.operatorList){c.operatorList.lastChunk=!0;for(const p of c.renderTasks)p.operatorListChanged();q(this,jy,_S).call(this)}if(c.displayReadyCapability)c.displayReadyCapability.reject(f);else if(c.opListReadCapability)c.opListReadCapability.reject(f);else throw f}})};u()}_abortOperatorList({intentState:e,reason:t,force:r=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&(clearTimeout(e.streamReaderCancelTimeout),e.streamReaderCancelTimeout=null),!r){if(e.renderTasks.size>0)return;if(t instanceof P3){let i=ghe;t.extraDelay>0&&t.extraDelay<1e3&&(i+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},i);return}}if(e.streamReader.cancel(new Ng(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(const[i,o]of this._intentStates)if(o===e){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}};Vh=new WeakMap,Sy=new WeakMap,jy=new WeakSet,_S=function(){if(!h(this,Vh)||this.destroyed)return!1;for(const{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),R(this,Vh,!1),!0};let EI=V3;var Hp,gc,Gh,ky,GT,_y,Cy,ka,G5,CG,AG,CS,pv,K5;const ss=class ss{constructor({name:e=null,port:t=null,verbosity:r=qce()}={}){N(this,ka);N(this,Hp,Promise.withResolvers());N(this,gc,null);N(this,Gh,null);N(this,ky,null);if(this.name=e,this.destroyed=!1,this.verbosity=r,t){if(h(ss,Cy).has(t))throw new Error("Cannot use more than one PDFWorker per port.");h(ss,Cy).set(t,this),q(this,ka,CG).call(this,t)}else q(this,ka,AG).call(this)}get promise(){return h(this,Hp).promise}get port(){return h(this,Gh)}get messageHandler(){return h(this,gc)}destroy(){var e,t;this.destroyed=!0,(e=h(this,ky))==null||e.terminate(),R(this,ky,null),h(ss,Cy).delete(h(this,Gh)),R(this,Gh,null),(t=h(this,gc))==null||t.destroy(),R(this,gc,null)}static create(e){const t=h(this,Cy).get(e==null?void 0:e.port);if(t){if(t._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new ss(e)}static get workerSrc(){if(Bu.workerSrc)return Bu.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Cn(this,"_setupFakeWorkerGlobal",(async()=>h(this,pv,K5)?h(this,pv,K5):(await import(this.workerSrc)).WorkerMessageHandler)())}};Hp=new WeakMap,gc=new WeakMap,Gh=new WeakMap,ky=new WeakMap,GT=new WeakMap,_y=new WeakMap,Cy=new WeakMap,ka=new WeakSet,G5=function(){h(this,Hp).resolve(),h(this,gc).send("configure",{verbosity:this.verbosity})},CG=function(e){R(this,Gh,e),R(this,gc,new xS("main","worker",e)),h(this,gc).on("ready",()=>{}),q(this,ka,G5).call(this)},AG=function(){if(h(ss,_y)||h(ss,pv,K5)){q(this,ka,CS).call(this);return}let{workerSrc:e}=ss;try{ss._isSameOrigin(window.location,e)||(e=ss._createCDNWrapper(new URL(e,window.location).href));const t=new Worker(e,{type:"module"}),r=new xS("main","worker",t),i=()=>{o.abort(),r.destroy(),t.terminate(),this.destroyed?h(this,Hp).reject(new Error("Worker was destroyed")):q(this,ka,CS).call(this)},o=new AbortController;t.addEventListener("error",()=>{h(this,ky)||i()},{signal:o.signal}),r.on("test",l=>{if(o.abort(),this.destroyed||!l){i();return}R(this,gc,r),R(this,Gh,t),R(this,ky,t),q(this,ka,G5).call(this)}),r.on("ready",l=>{if(o.abort(),this.destroyed){i();return}try{a()}catch{q(this,ka,CS).call(this)}});const a=()=>{const l=new Uint8Array;r.send("test",l,[l.buffer])};a();return}catch{nD("The worker has been disabled.")}q(this,ka,CS).call(this)},CS=function(){h(ss,_y)||(Bn("Setting up fake worker."),R(ss,_y,!0)),ss._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){h(this,Hp).reject(new Error("Worker was destroyed"));return}const t=new _ue;R(this,Gh,t);const r=`fake${Gi(ss,GT)._++}`,i=new xS(r+"_worker",r,t);e.setup(i,t),R(this,gc,new xS(r,r+"_worker",t)),q(this,ka,G5).call(this)}).catch(e=>{h(this,Hp).reject(new Error(`Setting up fake worker failed: "${e.message}".`))})},pv=new WeakSet,K5=function(){var e;try{return((e=globalThis.pdfjsWorker)==null?void 0:e.WorkerMessageHandler)||null}catch{return null}},N(ss,pv),N(ss,GT,0),N(ss,_y,!1),N(ss,Cy,new WeakMap),zl&&(R(ss,_y,!0),Bu.workerSrc||(Bu.workerSrc="./pdf.worker.mjs")),ss._isSameOrigin=(e,t)=>{const r=URL.parse(e);if(!(r!=null&&r.origin)||r.origin==="null")return!1;const i=new URL(t,r);return r.origin===i.origin},ss._createCDNWrapper=e=>{const t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};let $j=ss;var bl,Ay,Kh,mc,Ty,gv,Xh,Ac,AS,X5;class yhe{constructor(e,t,r,i,o,a){N(this,Ac);ve(this,"downloadInfoCapability",Promise.withResolvers());N(this,bl,null);N(this,Ay,new Map);N(this,Kh,null);N(this,mc,new Map);N(this,Ty,new Map);N(this,gv,new Map);N(this,Xh,null);this.messageHandler=e,this.loadingTask=t,R(this,Kh,r),this.commonObjs=new bG,this.fontLoader=new pue({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=o.canvasFactory,this.filterFactory=o.filterFactory,this.binaryDataFactory=o.binaryDataFactory,this.pagesMapper=a,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(e){const{_pageIndex:t}=e;h(this,mc).set(t,e),h(this,Ty).set(t,Promise.resolve(e))}get annotationStorage(){return Cn(this,"annotationStorage",new I3)}getRenderingIntent(e,t=Ru.ENABLE,r=null,i=!1,o=!1){let a=Rl.DISPLAY,l=Xj;switch(e){case"any":a=Rl.ANY;break;case"display":break;case"print":a=Rl.PRINT;break;default:Bn(`getRenderingIntent - invalid intent: ${e}`)}const d=a&Rl.PRINT&&r instanceof GV?r:this.annotationStorage;switch(t){case Ru.DISABLE:a+=Rl.ANNOTATIONS_DISABLE;break;case Ru.ENABLE:break;case Ru.ENABLE_FORMS:a+=Rl.ANNOTATIONS_FORMS;break;case Ru.ENABLE_STORAGE:a+=Rl.ANNOTATIONS_STORAGE,l=d.serializable;break;default:Bn(`getRenderingIntent - invalid annotationMode: ${t}`)}i&&(a+=Rl.IS_EDITING),o&&(a+=Rl.OPLIST);const{ids:c,hash:u}=d.modifiedIds,f=[a,l.hash,u];return{renderingIntent:a,cacheKey:f.join("_"),annotationStorageSerializable:l,modifiedIds:c}}destroy(){var r;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(r=h(this,Xh))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const e=[];for(const i of h(this,mc).values())e.push(i._destroy());h(this,mc).clear(),h(this,Ty).clear(),h(this,gv).clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const t=this.messageHandler.sendWithPromise("Terminate",null);return e.push(t),Promise.all(e).then(()=>{var i,o;this.commonObjs.clear(),this.fontLoader.clear(),h(this,Ay).clear(),this.filterFactory.destroy(),Qj.cleanup(),(i=h(this,Kh))==null||i.cancelAllRequests(new Ng("Worker was terminated.")),(o=this.messageHandler)==null||o.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:e,loadingTask:t}=this;e.on("GetReader",(r,i)=>{Zi(h(this,Kh),"GetReader - no `BasePDFStream` instance available."),R(this,bl,h(this,Kh).getFullReader()),h(this,bl).onProgress=o=>q(this,Ac,X5).call(this,o),i.onPull=()=>{h(this,bl).read().then(function({value:o,done:a}){if(a){i.close();return}Zi(o instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(o),1,[o])}).catch(o=>{i.error(o)})},i.onCancel=o=>{h(this,bl).cancel(o),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),e.on("ReaderHeadersReady",async r=>{await h(this,bl).headersReady;const{isStreamingSupported:i,isRangeSupported:o,contentLength:a}=h(this,bl);return i&&o&&(h(this,bl).onProgress=null),{isStreamingSupported:i,isRangeSupported:o,contentLength:a}}),e.on("GetRangeReader",(r,i)=>{Zi(h(this,Kh),"GetRangeReader - no `BasePDFStream` instance available.");const o=h(this,Kh).getRangeReader(r.begin,r.end);if(!o){i.close();return}i.onPull=()=>{o.read().then(function({value:a,done:l}){if(l){i.close();return}Zi(a instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(a),1,[a])}).catch(a=>{i.error(a)})},i.onCancel=a=>{o.cancel(a),i.ready.catch(l=>{if(!this.destroyed)throw l})}}),e.on("GetDoc",({pdfInfo:r})=>{this.pagesMapper.pagesNumber=r.numPages,this._numPages=r.numPages,this._htmlForXfa=r.htmlForXfa,delete r.htmlForXfa,t._capability.resolve(new mhe(r,this))}),e.on("DocException",r=>{t._capability.reject(La(r))}),e.on("PasswordRequest",r=>{R(this,Xh,Promise.withResolvers());try{if(!t.onPassword)throw La(r);const i=o=>{o instanceof Error?h(this,Xh).reject(o):h(this,Xh).resolve({password:o})};t.onPassword(i,r.code)}catch(i){h(this,Xh).reject(i)}return h(this,Xh).promise}),e.on("DataLoaded",r=>{q(this,Ac,X5).call(this,{loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),e.on("StartRenderPage",r=>{if(this.destroyed)return;h(this,mc).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),e.on("commonobj",([r,i,o])=>{var a;if(this.destroyed||this.commonObjs.has(r))return null;switch(i){case"Font":if("error"in o){const p=o.error;Bn(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const l=new xue(o),d=this._params.pdfBug&&((a=globalThis.FontInspector)!=null&&a.enabled)?(p,g)=>globalThis.FontInspector.fontAdded(p,g):null,c=new gue(l,d,o.charProcOperatorList,o.extra);this.fontLoader.bind(c).catch(()=>e.sendWithPromise("FontFallback",{id:r})).finally(()=>{c.fontExtraProperties||c.clearData(),this.commonObjs.resolve(r,c)});break;case"CopyLocalImage":const{imageRef:u}=o;Zi(u,"The imageRef must be defined.");for(const p of h(this,mc).values())for(const[,g]of p.objs){if((g==null?void 0:g.ref)!==u)continue;if(!g.dataLen)return null;const m=structuredClone(g);return this.commonObjs.resolve(r,m),g.dataLen}break;case"FontPath":this.commonObjs.resolve(r,new vue(o));break;case"Image":this.commonObjs.resolve(r,o);break;case"Pattern":const f=new bue(o);this.commonObjs.resolve(r,f.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),e.on("obj",([r,i,o,a])=>{var d;if(this.destroyed)return;const l=h(this,mc).get(i);if(!l.objs.has(r)){if(l._intentStates.size===0){(d=a==null?void 0:a.bitmap)==null||d.close();return}switch(o){case"Image":case"Pattern":l.objs.resolve(r,a);break;default:throw new Error(`Got unknown object type ${o}`)}}}),e.on("DocProgress",r=>{this.destroyed||q(this,Ac,X5).call(this,r)}),e.on("FetchBinaryData",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(r)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var r;this.annotationStorage.size<=0&&Bn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:((r=h(this,bl))==null?void 0:r.filename)??null},t).finally(()=>{this.annotationStorage.resetModified()})}extractPages(e){const t={pageInfos:e};let r;if(this.annotationStorage.size>0){const{map:i,transfer:o}=this.annotationStorage.serializable;t.annotationStorage=i,r=o}return this.messageHandler.sendWithPromise("ExtractPages",t,r).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const t=e-1,r=this.pagesMapper.getPageId(e)-1,i=h(this,Ty).get(t);if(i)return i;const o=this.messageHandler.sendWithPromise("GetPage",{pageIndex:r}).then(a=>{if(this.destroyed)throw new Error("Transport destroyed");a.refStr&&h(this,gv).set(a.refStr,r);const l=new EI(t,a,this,this.pagesMapper,this._params.pdfBug);return h(this,mc).set(t,l),l});return h(this,Ty).set(t,o),o}async getPageIndex(e){if(!vI(e))throw new Error("Invalid pageIndex request.");const t=await this.messageHandler.sendWithPromise("GetPageIndex",{num:e.num,gen:e.gen}),r=this.pagesMapper.getPageNumber(t+1);if(r===0)throw new Error("GetPageIndex: page has been removed.");return r-1}getAnnotations(e,t){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(e+1)-1,intent:t})}getFieldObjects(){return q(this,Ac,AS).call(this,"GetFieldObjects")}hasJSActions(){return q(this,Ac,AS).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(e){return typeof e!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:e})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(e,t){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:e,pageIndexesToSkip:t})}getDocJSActions(){return q(this,Ac,AS).call(this,"GetDocJSActions")}getPageJSActions(e){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getStructTree(e){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(e){return q(this,Ac,AS).call(this,"GetOptionalContentConfig").then(t=>new hhe(t,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const e="GetMetadata";return h(this,Ay).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,null).then(t=>{var r,i;return{info:t[0],metadata:t[1]?new che(t[1]):null,contentDispositionFilename:((r=h(this,bl))==null?void 0:r.filename)??null,contentLength:((i=h(this,bl))==null?void 0:i.contentLength)??null,hasStructTree:t[2]}}))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(e){return this.messageHandler.sendWithPromise("GetRawData",e)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of h(this,mc).values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),h(this,Ay).clear(),this.filterFactory.destroy(!0),Qj.cleanup()}}cachedPageNumber(e){if(!vI(e))return null;const t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,r=h(this,gv).get(t);if(r>=0){const i=this.pagesMapper.getPageNumber(r+1);if(i!==0)return i}return null}}bl=new WeakMap,Ay=new WeakMap,Kh=new WeakMap,mc=new WeakMap,Ty=new WeakMap,gv=new WeakMap,Xh=new WeakMap,Ac=new WeakSet,AS=function(e,t=null){return h(this,Ay).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))},X5=function({loaded:e,total:t}){var r,i;(i=(r=this.loadingTask).onProgress)==null||i.call(r,{loaded:e,total:t,percent:t?Bi(Math.round(e/t*100),0,100):NaN})};class xhe{constructor(e){ve(this,"_internalRenderTask",null);ve(this,"onContinue",null);ve(this,"onError",null);this._internalRenderTask=e}get promise(){return this._internalRenderTask.capability.promise}cancel(e=0){this._internalRenderTask.cancel(null,e)}get separateAnnots(){const{separateAnnots:e}=this._internalRenderTask.operatorList;if(!e)return!1;const{annotationCanvasMap:t}=this._internalRenderTask;return e.form||e.canvas&&(t==null?void 0:t.size)>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}var qp,Fy;const fm=class fm{constructor({callback:e,params:t,objs:r,commonObjs:i,annotationCanvasMap:o,operatorList:a,pageIndex:l,canvasFactory:d,filterFactory:c,useRequestAnimationFrame:u=!1,pdfBug:f=!1,pageColors:p=null,enableHWA:g=!1,operationsFilter:m=null}){N(this,qp,null);this.callback=e,this.params=t,this.objs=r,this.commonObjs=i,this.annotationCanvasMap=o,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=l,this.canvasFactory=d,this.filterFactory=c,this._pdfBug=f,this.pageColors=p,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new xhe(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvas,this._canvasContext=t.canvas?null:t.canvasContext,this._enableHWA=g,this._dependencyTracker=t.dependencyTracker,this._imagesTracker=t.imagesTracker,this._operationsFilter=m}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:t}){var c,u;if(this.cancelled)return;if(this._canvas){if(h(fm,Fy).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");h(fm,Fy).add(this._canvas)}this._pdfBug&&((c=globalThis.StepperManager)!=null&&c.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:r,transform:i,background:o,dependencyTracker:a,imagesTracker:l}=this.params,d=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new db(d,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:t},this.annotationCanvasMap,this.pageColors,a,l),this.gfx.beginDrawing({transform:i,viewport:r,transparency:e,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,(u=this.graphicsReadyCallback)==null||u.call(this)}cancel(e=null,t=0){var r,i,o;this.running=!1,this.cancelled=!0,(r=this.gfx)==null||r.endDrawing(),h(this,qp)&&(window.cancelAnimationFrame(h(this,qp)),R(this,qp,null)),h(fm,Fy).delete(this._canvas),e||(e=new P3(`Rendering cancelled, page ${this._pageIndex+1}`,t)),this.callback(e),(o=(i=this.task).onError)==null||o.call(i,e)}operatorListChanged(){var e,t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(e=this.gfx.dependencyTracker)==null||e.growOperationsCount(this.operatorList.fnArray.length),(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?R(this,qp,window.requestAnimationFrame(()=>{R(this,qp,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),h(fm,Fy).delete(this._canvas),this.callback())))}};qp=new WeakMap,Fy=new WeakMap,N(fm,Fy,new WeakSet);let PI=fm;const bhe="5.7.284",vhe="7e5b36c2d";var vl,Dy,mv,Is,r_,yv,Yh,i_,Vp,yc,s_,di,RI,BI,II,lm,TG,Jf;const Na=class Na{constructor({editor:e=null,uiManager:t=null}){N(this,di);N(this,vl,null);N(this,Dy,null);N(this,mv);N(this,Is,null);N(this,r_,!1);N(this,yv,!1);N(this,Yh,null);N(this,i_);N(this,Vp,null);N(this,yc,null);var r,i;e?(R(this,yv,!1),R(this,Yh,e)):R(this,yv,!0),R(this,yc,(e==null?void 0:e._uiManager)||t),R(this,i_,h(this,yc)._eventBus),R(this,mv,((r=e==null?void 0:e.color)==null?void 0:r.toUpperCase())||((i=h(this,yc))==null?void 0:i.highlightColors.values().next().value)||"#FFFF98"),h(Na,s_)||R(Na,s_,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return Cn(this,"_keyboardManager",new uC([[["Escape","mac+Escape"],Na.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],Na.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],Na.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],Na.prototype._moveToPrevious],[["Home","mac+Home"],Na.prototype._moveToBeginning],[["End","mac+End"],Na.prototype._moveToEnd]]))}renderButton(){const e=R(this,vl,document.createElement("button"));e.className="colorPicker",e.tabIndex="0",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),e.ariaHasPopup="true",h(this,Yh)&&(e.ariaControls=`${h(this,Yh).id}_colorpicker_dropdown`);const t=h(this,yc)._signal;e.addEventListener("click",q(this,di,lm).bind(this),{signal:t}),e.addEventListener("keydown",q(this,di,II).bind(this),{signal:t});const r=R(this,Dy,document.createElement("span"));return r.className="swatch",r.ariaHidden="true",r.style.backgroundColor=h(this,mv),e.append(r),e}renderMainDropdown(){const e=R(this,Is,q(this,di,RI).call(this));return e.ariaOrientation="horizontal",e.ariaLabelledBy="highlightColorPickerLabel",e}_colorSelectFromKeyboard(e){if(e.target===h(this,vl)){q(this,di,lm).call(this,e);return}const t=e.target.getAttribute("data-color");t&&q(this,di,BI).call(this,t,e)}_moveToNext(e){var t,r;if(!h(this,di,Jf)){q(this,di,lm).call(this,e);return}if(e.target===h(this,vl)){(t=h(this,Is).firstElementChild)==null||t.focus();return}(r=e.target.nextSibling)==null||r.focus()}_moveToPrevious(e){var t,r;if(e.target===((t=h(this,Is))==null?void 0:t.firstElementChild)||e.target===h(this,vl)){h(this,di,Jf)&&this._hideDropdownFromKeyboard();return}h(this,di,Jf)||q(this,di,lm).call(this,e),(r=e.target.previousSibling)==null||r.focus()}_moveToBeginning(e){var t;if(!h(this,di,Jf)){q(this,di,lm).call(this,e);return}(t=h(this,Is).firstElementChild)==null||t.focus()}_moveToEnd(e){var t;if(!h(this,di,Jf)){q(this,di,lm).call(this,e);return}(t=h(this,Is).lastElementChild)==null||t.focus()}hideDropdown(){var e,t;(e=h(this,Is))==null||e.classList.add("hidden"),h(this,vl).ariaExpanded="false",(t=h(this,Vp))==null||t.abort(),R(this,Vp,null)}_hideDropdownFromKeyboard(){var e;if(!h(this,yv)){if(!h(this,di,Jf)){(e=h(this,Yh))==null||e.unselect();return}this.hideDropdown(),h(this,vl).focus({preventScroll:!0,focusVisible:h(this,r_)})}}updateColor(e){if(h(this,Dy)&&(h(this,Dy).style.backgroundColor=e),!h(this,Is))return;const t=h(this,yc).highlightColors.values();for(const r of h(this,Is).children)r.ariaSelected=t.next().value===e.toUpperCase()}destroy(){var e,t;(e=h(this,vl))==null||e.remove(),R(this,vl,null),R(this,Dy,null),(t=h(this,Is))==null||t.remove(),R(this,Is,null)}};vl=new WeakMap,Dy=new WeakMap,mv=new WeakMap,Is=new WeakMap,r_=new WeakMap,yv=new WeakMap,Yh=new WeakMap,i_=new WeakMap,Vp=new WeakMap,yc=new WeakMap,s_=new WeakMap,di=new WeakSet,RI=function(){const e=document.createElement("div"),t=h(this,yc)._signal;e.addEventListener("contextmenu",Hd,{signal:t}),e.className="dropdown",e.role="listbox",e.ariaMultiSelectable="false",e.ariaOrientation="vertical",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),h(this,Yh)&&(e.id=`${h(this,Yh).id}_colorpicker_dropdown`);for(const[r,i]of h(this,yc).highlightColors){const o=document.createElement("button");o.tabIndex="0",o.role="option",o.setAttribute("data-color",i),o.title=r,o.setAttribute("data-l10n-id",h(Na,s_)[r]);const a=document.createElement("span");o.append(a),a.className="swatch",a.style.backgroundColor=i,o.ariaSelected=i===h(this,mv),o.addEventListener("click",q(this,di,BI).bind(this,i),{signal:t}),e.append(o)}return e.addEventListener("keydown",q(this,di,II).bind(this),{signal:t}),e},BI=function(e,t){t.stopPropagation(),h(this,i_).dispatch("switchannotationeditorparams",{source:this,type:Wn.HIGHLIGHT_COLOR,value:e}),this.updateColor(e)},II=function(e){Na._keyboardManager.exec(this,e)},lm=function(e){if(h(this,di,Jf)){this.hideDropdown();return}if(R(this,r_,e.detail===0),h(this,Vp)||(R(this,Vp,new AbortController),window.addEventListener("pointerdown",q(this,di,TG).bind(this),{signal:h(this,yc).combinedSignal(h(this,Vp))})),h(this,vl).ariaExpanded="true",h(this,Is)){h(this,Is).classList.remove("hidden");return}const t=R(this,Is,q(this,di,RI).call(this));h(this,vl).append(t)},TG=function(e){var t;(t=h(this,Is))!=null&&t.contains(e.target)||this.hideDropdown()},Jf=function(){return h(this,Is)&&!h(this,Is).classList.contains("hidden")},N(Na,s_,null);let ST=Na;var wl,xv,Ey,Qh,o_;const pm=class pm{constructor(e){N(this,wl,null);N(this,xv,!1);N(this,Ey,null);N(this,Qh,null);R(this,Ey,e),R(this,Qh,e._uiManager),h(pm,o_)||R(pm,o_,Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"}))}renderButton(){if(h(this,wl))return h(this,wl);const{editorType:e,colorType:t,colorAndOpacityType:r,opacityType:i,color:o,opacity:a}=h(this,Ey),l=R(this,xv,Ds.isAlphaColorInputSupported&&i!==void 0),d=R(this,wl,document.createElement("input"));if(d.type="color",l){d.setAttribute("alpha","");const c=yt.hexNums[Math.round((a??1)*255)];d.value=(o||"#000000")+c}else d.value=o||"#000000";return d.className="basicColorPicker",d.tabIndex=0,d.setAttribute("data-l10n-id",h(pm,o_)[e]),d.addEventListener("input",()=>{if(l){const c=B3(d.value);if(!c)return;const[u,f,p,g]=c,m=yt.makeHexColor(u,f,p);r!==void 0?h(this,Qh).updateParams(r,{color:m,opacity:g}):(h(this,Qh).updateParams(t,m),h(this,Qh).updateParams(i,g))}else h(this,Qh).updateParams(t,d.value)},{signal:h(this,Qh)._signal}),d}update(e){if(h(this,wl))if(h(this,xv)){const t=yt.hexNums[Math.round(h(this,Ey).opacity*255)];h(this,wl).value=e+t}else h(this,wl).value=e}updateOpacity(e){if(!h(this,wl)||!h(this,xv))return;const t=yt.hexNums[Math.round(e*255)];h(this,wl).value=h(this,Ey).color+t}destroy(){var e;(e=h(this,wl))==null||e.remove(),R(this,wl,null)}hideDropdown(){}};wl=new WeakMap,xv=new WeakMap,Ey=new WeakMap,Qh=new WeakMap,o_=new WeakMap,N(pm,o_,null);let jT=pm;function MN(n){return Math.floor(Bi(n,0,1)*255).toString(16).padStart(2,"0")}function Vw(n){return Bi(n,0,1)*255}class zN{static CMYK_G([e,t,r,i]){return["G",1-Math.min(1,.3*e+.59*r+.11*t+i)]}static G_CMYK([e]){return["CMYK",0,0,0,1-e]}static G_RGB([e]){return["RGB",e,e,e]}static G_rgb([e]){return e=Vw(e),[e,e,e]}static G_HTML([e]){const t=MN(e);return`#${t}${t}${t}`}static RGB_G([e,t,r]){return["G",.3*e+.59*t+.11*r]}static RGB_rgb(e){return e.map(Vw)}static RGB_HTML(e){return`#${e.map(MN).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([e,t,r,i]){return["RGB",1-Math.min(1,e+i),1-Math.min(1,r+i),1-Math.min(1,t+i)]}static CMYK_rgb([e,t,r,i]){return[Vw(1-Math.min(1,e+i)),Vw(1-Math.min(1,r+i)),Vw(1-Math.min(1,t+i))]}static CMYK_HTML(e){const t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,r]){const i=1-e,o=1-t,a=1-r,l=Math.min(i,o,a);return["CMYK",i,o,a,l]}}class whe{create(e,t,r=!1){if(e<=0||t<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),r||(i.setAttribute("width",`${e}px`),i.setAttribute("height",`${t}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${e} ${t}`),i}createElement(e){if(typeof e!="string")throw new Error("Invalid SVG element type");return this._createSVG(e)}_createSVG(e){Hr("Abstract method `_createSVG` called.")}}class kT extends whe{_createSVG(e){return document.createElementNS(hh,e)}}const She=9,C0=new WeakSet,jhe=new Date().getTimezoneOffset()*60*1e3;class HP{static create(e){switch(e.data.annotationType){case Cs.LINK:return new z3(e);case Cs.TEXT:return new _he(e);case Cs.WIDGET:switch(e.data.fieldType){case"Tx":return new Che(e);case"Btn":return e.data.radioButton?new EG(e):e.data.checkBox?new The(e):new Fhe(e);case"Ch":return new Dhe(e);case"Sig":return new Ahe(e)}return new U0(e);case Cs.POPUP:return new zI(e);case Cs.FREETEXT:return new MG(e);case Cs.LINE:return new Phe(e);case Cs.SQUARE:return new Rhe(e);case Cs.CIRCLE:return new Bhe(e);case Cs.POLYLINE:return new zG(e);case Cs.CARET:return new Mhe(e);case Cs.INK:return new O3(e);case Cs.POLYGON:return new Ihe(e);case Cs.HIGHLIGHT:return new OG(e);case Cs.UNDERLINE:return new zhe(e);case Cs.SQUIGGLY:return new Ohe(e);case Cs.STRIKEOUT:return new Lhe(e);case Cs.STAMP:return new LG(e);case Cs.FILEATTACHMENT:return new Nhe(e);default:return new ts(e)}}}var Py,bv,vd,a_,MI;const G3=class G3{constructor(e,{isRenderable:t=!1,ignoreBorder:r=!1,createQuadrilaterals:i=!1}={}){N(this,a_);N(this,Py,null);N(this,bv,!1);N(this,vd,null);this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,this.hasOwnCommentButton=!1,t&&(this.contentElement=this.container=this._createContainer(r)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:t}){return!!(e!=null&&e.str||t!=null&&t.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return G3._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){var r;const{data:e}=this,t=(r=this.annotationStorage)==null?void 0:r.getEditor(e.id);return t?t.getData():e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){var l;const e=(l=this.annotationStorage)==null?void 0:l.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;const{quadPoints:t,inkLists:r,rect:i}=this.data;let o=-1/0,a=-1/0;if((t==null?void 0:t.length)>=8){for(let d=0;da?(a=t[d+1],o=t[d+2]):t[d+1]===a&&(o=Math.max(o,t[d+2]));return[o,a]}if((r==null?void 0:r.length)>=1){for(const d of r)for(let c=0,u=d.length;ca?(a=d[c+1],o=d[c]):d[c+1]===a&&(o=Math.max(o,d[c]));if(o!==1/0)return[o,a]}return i?[i[2],i[3]]:null}_normalizePoint(e){const{page:{view:t},viewport:{rawDims:{pageWidth:r,pageHeight:i,pageX:o,pageY:a}}}=this.parent;return e[1]=t[3]-e[1]+t[1],e[0]=100*(e[0]-o)/r,e[1]=100*(e[1]-a)/i,e}get commentText(){var t,r,i;const{data:e}=this;return((r=(t=this.annotationStorage.getRawValue(`${Gj}${e.id}`))==null?void 0:t.popup)==null?void 0:r.contents)||((i=e.contentsObj)==null?void 0:i.str)||""}set commentText(e){const{data:t}=this,r={deleted:!e,contents:e||""};this.annotationStorage.updateEditor(t.id,{popup:r})||this.annotationStorage.setValue(`${Gj}${t.id}`,{id:t.id,annotationType:t.annotationType,page:this.parent.page,popup:r,popupRef:t.popupRef,modificationDate:new Date}),e||this.removePopup()}removePopup(){var e,t;(t=((e=h(this,vd))==null?void 0:e.popup)||this.popup)==null||t.remove(),R(this,vd,this.popup=null)}updateEdited(e){var o;if(!this.container)return;e.rect&&(h(this,Py)||R(this,Py,{rect:this.data.rect.slice(0)}));const{rect:t,popup:r}=e;t&&q(this,a_,MI).call(this,t);let i=((o=h(this,vd))==null?void 0:o.popup)||this.popup;!i&&(r!=null&&r.text)&&(this._createPopup(r),i=h(this,vd).popup),i&&(i.updateEdited(e),r!=null&&r.deleted&&(i.remove(),R(this,vd,null),this.popup=null))}resetEdited(){var e;h(this,Py)&&(q(this,a_,MI).call(this,h(this,Py).rect),(e=h(this,vd))==null||e.popup.resetEdited(),R(this,Py,null))}_createContainer(e){const{data:t,parent:{page:r,viewport:i}}=this,o=document.createElement("section");o.setAttribute("data-annotation-id",t.id),!(this instanceof U0)&&!(this instanceof z3)&&(o.tabIndex=0);const{style:a}=o;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,t.alternativeText&&(o.title=t.alternativeText),t.noRotate&&o.classList.add("norotate"),!t.rect||this instanceof zI){const{rotation:y}=t;return!t.hasOwnCanvas&&y!==0&&this.setRotation(y,o),o}const{width:l,height:d}=this;if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;const y=t.borderStyle.horizontalCornerRadius,v=t.borderStyle.verticalCornerRadius;if(y>0||v>0){const w=`calc(${y}px * var(--total-scale-factor)) / calc(${v}px * var(--total-scale-factor))`;a.borderRadius=w}else if(this instanceof EG){const w=`calc(${l}px * var(--total-scale-factor)) / calc(${d}px * var(--total-scale-factor))`;a.borderRadius=w}switch(t.borderStyle.style){case Sx.SOLID:a.borderStyle="solid";break;case Sx.DASHED:a.borderStyle="dashed";break;case Sx.BEVELED:Bn("Unimplemented border style: beveled");break;case Sx.INSET:Bn("Unimplemented border style: inset");break;case Sx.UNDERLINE:a.borderBottomStyle="solid";break}const x=t.borderColor||null;x?(R(this,bv,!0),a.borderColor=yt.makeHexColor(...x)):a.borderWidth=0}const c=yt.normalizeRect([t.rect[0],r.view[3]-t.rect[1]+r.view[1],t.rect[2],r.view[3]-t.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:f,pageX:p,pageY:g}=i.rawDims;a.left=`${100*(c[0]-p)/u}%`,a.top=`${100*(c[1]-g)/f}%`;const{rotation:m}=t;return t.hasOwnCanvas||m===0?(a.width=`${100*l/u}%`,a.height=`${100*d/f}%`):this.setRotation(m,o),o}setRotation(e,t=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:i}=this.parent.viewport.rawDims;let{width:o,height:a}=this;e%180!==0&&([o,a]=[a,o]),t.style.width=`${100*o/r}%`,t.style.height=`${100*a/i}%`,t.setAttribute("data-main-rotation",(360-e)%360)}get _commonActions(){const e=(t,r,i)=>{const o=i.detail[t],a=o[0],l=o.slice(1);i.target.style[r]=zN[`${a}_HTML`](l),this.annotationStorage.setValue(this.data.id,{[r]:zN[`${a}_rgb`](l)})};return Cn(this,"_commonActions",{display:t=>{const{display:r}=t.detail,i=r%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:r===1||r===2})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:r}=t.detail;this.container.style.visibility=r?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:r,noView:r})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{e("bgColor","backgroundColor",t)},fillColor:t=>{e("fillColor","backgroundColor",t)},fgColor:t=>{e("fgColor","color",t)},textColor:t=>{e("textColor","color",t)},borderColor:t=>{e("borderColor","borderColor",t)},strokeColor:t=>{e("strokeColor","borderColor",t)},rotation:t=>{const r=t.detail.rotation;this.setRotation(r),this.annotationStorage.setValue(this.data.id,{rotation:r})}})}_dispatchEventFromSandbox(e,t){const r=this._commonActions;for(const i of Object.keys(t.detail)){const o=e[i]||r[i];o==null||o(t)}}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;const t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;const r=this._commonActions;for(const[i,o]of Object.entries(t)){const a=r[i];if(a){const l={detail:{[i]:o},target:e};a(l),delete t[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:e}=this.data;if(!e)return;const[t,r,i,o]=this.data.rect.map(y=>Math.fround(y));if(e.length===8){const[y,v,x,w]=e.subarray(2,6);if(i===y&&o===v&&t===x&&r===w)return}const{style:a}=this.container;let l;if(h(this,bv)){const{borderColor:y,borderWidth:v}=a;a.borderWidth=0,l=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const d=i-t,c=o-r,{svgFactory:u}=this,f=u.createElement("svg");f.classList.add("quadrilateralsContainer"),f.setAttribute("width",0),f.setAttribute("height",0),f.role="none";const p=u.createElement("defs");f.append(p);const g=u.createElement("clipPath"),m=`clippath_${this.data.id}`;g.setAttribute("id",m),g.setAttribute("clipPathUnits","objectBoundingBox"),p.append(g);for(let y=2,v=e.length;y`)}h(this,bv)&&(l.push("')"),a.backgroundImage=l.join("")),this.container.append(f),this.container.style.clipPath=`url(#${m})`}_createPopup(e=null){const{data:t}=this;let r,i;e?(r={str:e.text},i=e.date):(r=t.contentsObj,i=t.modificationDate),R(this,vd,new zI({data:{color:t.color,titleObj:t.titleObj,modificationDate:i,contentsObj:r,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]}))}get hasPopupElement(){return!!(h(this,vd)||this.popup||this.data.popupRef)}get extraPopupElement(){return h(this,vd)}render(){Hr("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){const r=[];if(this._fieldObjects){const i=this._fieldObjects[e];if(i)for(const{page:o,id:a,exportValues:l}of i){if(o===-1||a===t)continue;const d=typeof l=="string"?l:null,c=document.querySelector(`[data-element-id="${a}"]`);if(c&&!C0.has(c)){Bn(`_getElementsByName - element not allowed: ${a}`);continue}r.push({id:a,exportValue:d,domElement:c})}return r}for(const i of document.getElementsByName(e)){const{exportValue:o}=i,a=i.getAttribute("data-element-id");a!==t&&C0.has(i)&&r.push({id:a,exportValue:o,domElement:i})}return r}show(){var e;this.container&&(this.container.hidden=!1),(e=this.popup)==null||e.maybeShow()}hide(){var e;this.container&&(this.container.hidden=!0),(e=this.popup)==null||e.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(const t of e)t.classList.add("highlightArea");else e.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener("dblclick",()=>{var r;(r=this.linkService.eventBus)==null||r.dispatch("switchannotationeditormode",{source:this,mode:e,editId:t,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}};Py=new WeakMap,bv=new WeakMap,vd=new WeakMap,a_=new WeakSet,MI=function(e){const{container:{style:t},data:{rect:r,rotation:i},parent:{viewport:{rawDims:{pageWidth:o,pageHeight:a,pageX:l,pageY:d}}}}=this;r==null||r.splice(0,4,...e),t.left=`${100*(e[0]-l)/o}%`,t.top=`${100*(a-e[3]+d)/a}%`,i===0?(t.width=`${100*(e[2]-e[0])/o}%`,t.height=`${100*(e[3]-e[1])/a}%`):this.setRotation(i)};let ts=G3;class khe extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.editor=e.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:e}=this;e.hasComment&&this._createPopup(e.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){this.editor.comment=e,e||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}var Ll,dm,FG,DG;class z3 extends ts{constructor(t,r=null){super(t,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});N(this,Ll);this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:r}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let o=!1;return t.url?(r.addLinkAttributes(i,t.url,t.newWindow),o=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),o=!0):t.attachment?(q(this,Ll,FG).call(this,i,t.attachment,t.overlaidText,t.attachmentDest),o=!0):t.setOCGState?(q(this,Ll,DG).call(this,i,t.setOCGState,t.overlaidText),o=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),o=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),o=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),o=!0):this.isTooltipOnly&&!o&&(this._bindLink(i,""),o=!0)),this.container.classList.add("linkAnnotation"),o&&(this.contentElement=i,this.container.append(i)),this.container}_bindLink(t,r,i=""){t.href=this.linkService.getDestinationHash(r),t.onclick=()=>(r&&this.linkService.goToDestination(r),!1),(r||r==="")&&q(this,Ll,dm).call(this),i&&(t.title=i)}_bindNamedAction(t,r,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(r),!1),i&&(t.title=i),q(this,Ll,dm).call(this)}_bindJSAction(t,r){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const o of Object.keys(r.actions)){const a=i.get(o);a&&(t[a]=()=>{var l;return(l=this.linkService.eventBus)==null||l.dispatch("dispatcheventinsandbox",{source:this,detail:{id:r.id,name:o}}),!1})}r.overlaidText&&(t.title=r.overlaidText),t.onclick||(t.onclick=()=>!1),q(this,Ll,dm).call(this)}_bindResetFormAction(t,r){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),q(this,Ll,dm).call(this),!this._fieldObjects){Bn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(t.onclick=()=>!1);return}t.onclick=()=>{var f;i==null||i();const{fields:o,refs:a,include:l}=r,d=[];if(o.length!==0||a.length!==0){const p=new Set(a);for(const g of o){const m=this._fieldObjects[g]||[];for(const{id:y}of m)p.add(y)}for(const g of Object.values(this._fieldObjects))for(const m of g)p.has(m.id)===l&&d.push(m)}else for(const p of Object.values(this._fieldObjects))d.push(...p);const c=this.annotationStorage,u=[];for(const p of d){const{id:g}=p;switch(u.push(g),p.type){case"text":{const y=p.defaultValue||"";c.setValue(g,{value:y});break}case"checkbox":case"radiobutton":{const y=p.defaultValue===p.exportValues;c.setValue(g,{value:y});break}case"combobox":case"listbox":{const y=p.defaultValue||"";c.setValue(g,{value:y});break}default:continue}const m=document.querySelector(`[data-element-id="${g}"]`);if(m){if(!C0.has(m)){Bn(`_bindResetFormAction - element not allowed: ${g}`);continue}}else continue;m.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((f=this.linkService.eventBus)==null||f.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Ll=new WeakSet,dm=function(){this.container.setAttribute("data-internal-link","")},FG=function(t,r,i="",o=null){t.href=this.linkService.getAnchorUrl(""),r.description?t.title=r.description:i&&(t.title=i),t.onclick=()=>{var a;return(a=this.downloadManager)==null||a.openOrDownloadData(r.content,r.filename,o),!1},q(this,Ll,dm).call(this)},DG=function(t,r,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(r),!1),i&&(t.title=i),q(this,Ll,dm).call(this)};class _he extends ts{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const e=document.createElement("img");return e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),e.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(e),this.container}}class U0 extends ts{render(){return this.container}showElementAndHideCanvas(e){var t;this.data.hasOwnCanvas&&(((t=e.previousSibling)==null?void 0:t.nodeName)==="CANVAS"&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return Ds.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,r,i,o){r.includes("mouse")?e.addEventListener(r,a=>{var l;(l=this.linkService.eventBus)==null||l.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:o(a),shift:a.shiftKey,modifier:this._getKeyModifier(a)}})}):e.addEventListener(r,a=>{var l;if(r==="blur"){if(!t.focused||!a.relatedTarget)return;t.focused=!1}else if(r==="focus"){if(t.focused)return;t.focused=!0}o&&((l=this.linkService.eventBus)==null||l.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:o(a)}}))})}_setEventListeners(e,t,r,i){var o,a,l;for(const[d,c]of r)(c==="Action"||(o=this.data.actions)!=null&&o[c])&&((c==="Focus"||c==="Blur")&&(t||(t={focused:!1})),this._setEventListener(e,t,d,c,i),c==="Focus"&&!((a=this.data.actions)!=null&&a.Blur)?this._setEventListener(e,t,"blur","Blur",null):c==="Blur"&&!((l=this.data.actions)!=null&&l.Focus)&&this._setEventListener(e,t,"focus","Focus",null))}_setBackgroundColor(e){const t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?"transparent":yt.makeHexColor(...t)}_setTextStyle(e){const t=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||She,o=e.style;let a;const l=2,d=c=>Math.round(10*c)/10;if(this.data.multiLine){const c=Math.abs(this.data.rect[3]-this.data.rect[1]-l),u=Math.round(c/(OP*i))||1,f=c/u;a=Math.min(i,d(f/OP))}else{const c=Math.abs(this.data.rect[3]-this.data.rect[1]-l);a=Math.min(i,d(c/OP))}o.fontSize=`calc(${a}px * var(--total-scale-factor))`,o.color=yt.makeHexColor(...r),this.data.textAlignment!==null&&(o.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute("required",!0):e.removeAttribute("required"),e.setAttribute("aria-required",t)}}class Che extends U0{constructor(e){const t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,r,i){const o=this.annotationStorage;for(const a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=r),o.setValue(a.id,{[i]:r})}render(){var i,o;const e=this.annotationStorage,t=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){const a=e.getValue(t,{value:this.data.fieldValue});let l=a.value||"";const d=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;d&&l.length>d&&(l=l.slice(0,d));let c=a.formattedValue||((i=this.data.textContent)==null?void 0:i.join(` `))||null;c&&this.data.comb&&(c=c.replaceAll(/\s+/g,""));const u={userValue:l,formattedValue:c,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=c??l,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type=this.data.password?"password":"text",r.setAttribute("value",c??l),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),C0.add(r),this.contentElement=r,r.setAttribute("data-element-id",t),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=0;const{datetimeFormat:f,datetimeType:p,timeStep:g}=this.data,m=!!p&&this.enableScripting;f&&(r.title=f),this._setRequired(r,this.data.required),d&&(r.maxLength=d),r.addEventListener("input",v=>{e.setValue(t,{value:v.target.value}),this.setPropertyOnSiblings(r,"value",v.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",v=>{const x=this.data.defaultFieldValue??"";r.value=u.userValue=x,u.formattedValue=null});let y=v=>{const{formattedValue:x}=u;x!=null&&(v.target.value=x),v.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",x=>{var S;if(u.focused)return;const{target:w}=x;if(m&&(w.type=p,g&&(w.step=g)),u.userValue){const _=u.userValue;if(m)if(p==="time"){const b=new Date(_),C=[b.getHours(),b.getMinutes(),b.getSeconds()];w.value=C.map(T=>T.toString().padStart(2,"0")).join(":")}else w.value=new Date(_-jhe).toISOString().split(p==="date"?"T":".",1)[0];else w.value=_}u.lastCommittedValue=w.value,u.commitKey=1,(S=this.data.actions)!=null&&S.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",x=>{this.showElementAndHideCanvas(x.target);const w={value(S){u.userValue=S.detail.value??"",m||e.setValue(t,{value:u.userValue.toString()}),S.target.value=u.userValue},formattedValue(S){const{formattedValue:_}=S.detail;u.formattedValue=_,_!=null&&S.target!==document.activeElement&&(S.target.value=_);const b={formattedValue:_};m&&(b.value=_),e.setValue(t,b)},selRange(S){S.target.setSelectionRange(...S.detail.selRange)},charLimit:S=>{var T;const{charLimit:_}=S.detail,{target:b}=S;if(_===0){b.removeAttribute("maxLength");return}b.setAttribute("maxLength",_);let C=u.userValue;!C||C.length<=_||(C=C.slice(0,_),b.value=u.userValue=C,e.setValue(t,{value:C}),(T=this.linkService.eventBus)==null||T.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:C,willCommit:!0,commitKey:1,selStart:b.selectionStart,selEnd:b.selectionEnd}}))}};this._dispatchEventFromSandbox(w,x)}),r.addEventListener("keydown",x=>{var _;u.commitKey=1;let w=-1;if(x.key==="Escape"?w=0:x.key==="Enter"&&!this.data.multiLine?w=2:x.key==="Tab"&&(u.commitKey=3),w===-1)return;const{value:S}=x.target;u.lastCommittedValue!==S&&(u.lastCommittedValue=S,u.userValue=S,(_=this.linkService.eventBus)==null||_.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:S,willCommit:!0,commitKey:w,selStart:x.target.selectionStart,selEnd:x.target.selectionEnd}}))});const v=y;y=null,r.addEventListener("blur",x=>{var _,b;if(!u.focused||!x.relatedTarget)return;(_=this.data.actions)!=null&&_.Blur||(u.focused=!1);const{target:w}=x;let{value:S}=w;if(m){if(S&&p==="time"){const C=S.split(":").map(T=>parseInt(T,10));S=new Date(2e3,0,1,C[0],C[1],C[2]||0).valueOf(),w.step=""}else S.includes("T")||(S=`${S}T00:00`),S=new Date(S).valueOf();w.type="text"}u.userValue=S,u.lastCommittedValue!==S&&((b=this.linkService.eventBus)==null||b.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:S,willCommit:!0,commitKey:u.commitKey,selStart:x.target.selectionStart,selEnd:x.target.selectionEnd}})),v(x)}),(o=this.data.actions)!=null&&o.Keystroke&&r.addEventListener("beforeinput",x=>{var A;u.lastCommittedValue=null;const{data:w,target:S}=x,{value:_,selectionStart:b,selectionEnd:C}=S;let T=b,F=C;switch(x.inputType){case"deleteWordBackward":{const D=_.substring(0,b).match(/\w*[^\w]*$/);D&&(T-=D[0].length);break}case"deleteWordForward":{const D=_.substring(b).match(/^[^\w]*\w*/);D&&(F+=D[0].length);break}case"deleteContentBackward":b===C&&(T-=1);break;case"deleteContentForward":b===C&&(F+=1);break}x.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:_,change:w||"",willCommit:!1,selStart:T,selEnd:F}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],x=>x.target.value)}if(y&&r.addEventListener("blur",y),this.data.comb){const x=(this.data.rect[2]-this.data.rect[0])/d;r.classList.add("comb"),r.style.letterSpacing=`calc(${x}px * var(--total-scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class Ahe extends U0{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}}class The extends U0{constructor(e){super(e,{isRenderable:e.renderForms})}render(){const e=this.annotationStorage,t=this.data,r=t.id;let i=e.getValue(r,{value:t.exportValue===t.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",e.setValue(r,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const o=document.createElement("input");return C0.add(o),o.setAttribute("data-element-id",r),o.disabled=t.readOnly,this._setRequired(o,this.data.required),o.type="checkbox",o.name=t.fieldName,i&&o.setAttribute("checked",!0),o.setAttribute("exportValue",t.exportValue),o.tabIndex=0,o.addEventListener("change",a=>{const{name:l,checked:d}=a.target;for(const c of this._getElementsByName(l,r)){const u=d&&c.exportValue===t.exportValue;c.domElement&&(c.domElement.checked=u),e.setValue(c.id,{value:u})}e.setValue(r,{value:d})}),o.addEventListener("resetform",a=>{const l=t.defaultFieldValue||"Off";a.target.checked=l===t.exportValue}),this.enableScripting&&this.hasJSActions&&(o.addEventListener("updatefromsandbox",a=>{const l={value(d){d.target.checked=d.detail.value!=="Off",e.setValue(r,{value:d.target.checked})}};this._dispatchEventFromSandbox(l,a)}),this._setEventListeners(o,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)),this._setBackgroundColor(o),this._setDefaultPropertiesFromJS(o),this.container.append(o),this.container}}class EG extends U0{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const e=this.annotationStorage,t=this.data,r=t.id;let i=e.getValue(r,{value:t.fieldValue===t.buttonValue}).value;if(typeof i=="string"&&(i=i!==t.buttonValue,e.setValue(r,{value:i})),i)for(const a of this._getElementsByName(t.fieldName,r))e.setValue(a.id,{value:!1});const o=document.createElement("input");if(C0.add(o),o.setAttribute("data-element-id",r),o.disabled=t.readOnly,this._setRequired(o,this.data.required),o.type="radio",o.name=t.fieldName,i&&o.setAttribute("checked",!0),o.tabIndex=0,o.addEventListener("change",a=>{const{name:l,checked:d}=a.target;for(const c of this._getElementsByName(l,r))e.setValue(c.id,{value:!1});e.setValue(r,{value:d})}),o.addEventListener("resetform",a=>{const l=t.defaultFieldValue;a.target.checked=l!=null&&l===t.buttonValue}),this.enableScripting&&this.hasJSActions){const a=t.buttonValue;o.addEventListener("updatefromsandbox",l=>{const d={value:c=>{const u=a===c.detail.value;for(const f of this._getElementsByName(c.target.name)){const p=u&&f.id===r;f.domElement&&(f.domElement.checked=p),e.setValue(f.id,{value:p})}}};this._dispatchEventFromSandbox(d,l)}),this._setEventListeners(o,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],l=>l.target.checked)}return this._setBackgroundColor(o),this._setDefaultPropertiesFromJS(o),this.container.append(o),this.container}}class Fhe extends z3{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){const e=super.render();e.classList.add("buttonWidgetAnnotation","pushButton");const t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener("updatefromsandbox",r=>{this._dispatchEventFromSandbox({},r)})),e}}class Dhe extends U0{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const e=this.annotationStorage,t=this.data.id,r=e.getValue(t,{value:this.data.fieldValue}),i=document.createElement("select");C0.add(i),i.setAttribute("data-element-id",t),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=0;let o=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",f=>{const p=this.data.defaultFieldValue;for(const g of i.options)g.selected=g.value===p});const a=(f,p)=>{const g=p.replaceAll(" "," ");f.textContent=g,g!==p&&f.setAttribute("display-value",p)};for(const f of this.data.options){const p=document.createElement("option");a(p,f.displayValue),p.value=f.exportValue,r.value.includes(f.exportValue)&&(p.setAttribute("selected",!0),o=!1),i.append(p)}let l=null;if(o){const f=document.createElement("option");f.value=" ",f.setAttribute("hidden",!0),f.setAttribute("selected",!0),i.prepend(f),l=()=>{f.remove(),i.removeEventListener("input",l),l=null},i.addEventListener("input",l)}const d=f=>{const p=f?"value":"textContent",{options:g,multiple:m}=i;return m?Array.prototype.filter.call(g,y=>y.selected).map(y=>y[p]):g.selectedIndex===-1?null:g[g.selectedIndex][p]};let c=d(!1);const u=f=>{const p=f.target.options;return Array.prototype.map.call(p,g=>({displayValue:g.getAttribute("display-value")||g.textContent,exportValue:g.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",f=>{const p={value(g){l==null||l();const m=g.detail.value,y=new Set(Array.isArray(m)?m:[m]);for(const v of i.options)v.selected=y.has(v.value);e.setValue(t,{value:d(!0)}),c=d(!1)},multipleSelection(g){i.multiple=!0},remove(g){const m=i.options,y=g.detail.remove;m[y].selected=!1,i.remove(y),m.length>0&&Array.prototype.findIndex.call(m,x=>x.selected)===-1&&(m[0].selected=!0),e.setValue(t,{value:d(!0),items:u(g)}),c=d(!1)},clear(g){for(;i.length!==0;)i.remove(0);e.setValue(t,{value:null,items:[]}),c=d(!1)},insert(g){const{index:m,displayValue:y,exportValue:v}=g.detail.insert,x=i.children[m],w=document.createElement("option");a(w,y),w.value=v,x?x.before(w):i.append(w),e.setValue(t,{value:d(!0),items:u(g)}),c=d(!1)},items(g){const{items:m}=g.detail;for(;i.length!==0;)i.remove(0);for(const y of m){const{displayValue:v,exportValue:x}=y,w=document.createElement("option");a(w,v),w.value=x,i.append(w)}i.options.length>0&&(i.options[0].selected=!0),e.setValue(t,{value:d(!0),items:u(g)}),c=d(!1)},indices(g){const m=new Set(g.detail.indices);for(const y of g.target.options)y.selected=m.has(y.index);e.setValue(t,{value:d(!0)}),c=d(!1)},editable(g){g.target.disabled=!g.detail.editable}};this._dispatchEventFromSandbox(p,f)}),i.addEventListener("input",f=>{var m;const p=d(!0),g=d(!1);e.setValue(t,{value:p}),f.preventDefault(),(m=this.linkService.eventBus)==null||m.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:c,change:g,changeEx:p,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],f=>f.target.value)):i.addEventListener("input",function(f){e.setValue(t,{value:d(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}var l_,OI;class zI extends ts{constructor(t){const{data:r,elements:i,parent:o}=t,a=!!o._commentManager;super(t,{isRenderable:!a&&ts._hasPopupData(r)});N(this,l_);if(this.elements=i,a&&ts._hasPopupData(r)){const l=this.popup=q(this,l_,OI).call(this);for(const d of i)d.popup=l}else this.popup=null}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const r=this.popup=q(this,l_,OI).call(this),i=[];for(const o of this.elements)o.popup=r,o.container.ariaHasPopup="dialog",i.push(o.data.id),o.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(o=>`${Yx}${o}`).join(",")),this.container}}l_=new WeakSet,OI=function(){return new Ehe({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})};var Sl,Gp,KT,XT,vv,wv,ds,gu,Kp,Ry,Sv,jv,mu,jl,$h,Zh,cs,Jh,Xp,d_,ef,kv,By,Yp,ro,Qp,Hn,Y5,LI,NI,WI,Q5,UI,PG,RG,BG,IG,$5,Z5,HI;class Ehe{constructor({container:e,color:t,elements:r,titleObj:i,modificationDate:o,contentsObj:a,richText:l,parent:d,rect:c,parentRect:u,open:f,commentManager:p=null}){N(this,Hn);N(this,Sl,null);N(this,Gp,q(this,Hn,BG).bind(this));N(this,KT,q(this,Hn,HI).bind(this));N(this,XT,q(this,Hn,Z5).bind(this));N(this,vv,q(this,Hn,$5).bind(this));N(this,wv,null);N(this,ds,null);N(this,gu,null);N(this,Kp,null);N(this,Ry,null);N(this,Sv,null);N(this,jv,null);N(this,mu,!1);N(this,jl,null);N(this,$h,null);N(this,Zh,null);N(this,cs,null);N(this,Jh,null);N(this,Xp,null);N(this,d_,null);N(this,ef,null);N(this,kv,null);N(this,By,null);N(this,Yp,!1);N(this,ro,null);N(this,Qp,null);R(this,ds,e),R(this,kv,i),R(this,gu,a),R(this,ef,l),R(this,Sv,d),R(this,wv,t),R(this,d_,c),R(this,jv,u),R(this,Ry,r),R(this,Sl,p),R(this,ro,r[0]),R(this,Kp,bT.toDateObject(o)),this.trigger=r.flatMap(g=>g.getElementsToTriggerPopup()),p||(q(this,Hn,Y5).call(this),h(this,ds).hidden=!0,f&&q(this,Hn,$5).call(this))}renderCommentButton(){if(h(this,cs)){h(this,cs).parentNode||h(this,ro).container.after(h(this,cs));return}if(h(this,Jh)||q(this,Hn,LI).call(this),!h(this,Jh))return;const{signal:e}=R(this,$h,new AbortController),t=h(this,ro).hasOwnCommentButton,r=()=>{h(this,Sl).toggleCommentPopup(this,!0,void 0,!t)},i=()=>{h(this,Sl).toggleCommentPopup(this,!1,!0,!t)},o=()=>{h(this,Sl).toggleCommentPopup(this,!1,!1)};if(t){R(this,cs,h(this,ro).container);for(const a of this.trigger)a.ariaHasPopup="dialog",a.ariaControls="commentPopup",a.addEventListener("keydown",h(this,Gp),{signal:e}),a.addEventListener("click",r,{signal:e}),a.addEventListener("pointerenter",i,{signal:e}),a.addEventListener("pointerleave",o,{signal:e}),a.classList.add("popupTriggerArea")}else{const a=R(this,cs,document.createElement("button"));a.className="annotationCommentButton";const l=h(this,ro).container;a.style.zIndex=parseInt(l.style.zIndex,10)+1,a.tabIndex=0,a.ariaHasPopup="dialog",a.ariaControls="commentPopup",a.setAttribute("data-l10n-id","pdfjs-show-comment-button"),q(this,Hn,WI).call(this),q(this,Hn,NI).call(this),a.addEventListener("keydown",h(this,Gp),{signal:e}),a.addEventListener("click",r,{signal:e}),a.addEventListener("pointerenter",i,{signal:e}),a.addEventListener("pointerleave",o,{signal:e}),l.after(a)}}get commentButtonColor(){const{color:e,opacity:t}=h(this,ro).commentData;return e?h(this,Sv)._commentManager.makeCommentColor(e,t):null}focusCommentButton(){setTimeout(()=>{var e;(e=h(this,cs))==null||e.focus()},0)}getData(){const{richText:e,color:t,opacity:r,creationDate:i,modificationDate:o}=h(this,ro).commentData;return{contentsObj:{str:this.comment},richText:e,color:t,opacity:r,creationDate:i,modificationDate:o}}get elementBeforePopup(){return h(this,cs)}get comment(){return h(this,Qp)||R(this,Qp,h(this,ro).commentText),h(this,Qp)}set comment(e){e!==this.comment&&(h(this,ro).commentText=R(this,Qp,e))}focus(){var e;(e=h(this,ro).container)==null||e.focus()}get parentBoundingClientRect(){return h(this,ro).layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:t}){h(this,cs)&&(h(this,cs).classList.toggle("selected",e),h(this,cs).ariaExpanded=t)}setSelectedCommentButton(e){h(this,cs).classList.toggle("selected",e)}get commentPopupPosition(){if(h(this,Xp))return h(this,Xp);const{x:e,y:t,height:r}=h(this,cs).getBoundingClientRect(),{x:i,y:o,width:a,height:l}=h(this,ro).layer.getBoundingClientRect();return[(e-i)/a,(t+r-o)/l]}set commentPopupPosition(e){R(this,Xp,e)}hasDefaultPopupPosition(){return h(this,Xp)===null}get commentButtonPosition(){return h(this,Jh)}get commentButtonWidth(){return h(this,cs).getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){const[t,r]=h(this,Xp)||this.commentButtonPosition.map(c=>c/100),i=this.parentBoundingClientRect,{x:o,y:a,width:l,height:d}=i;h(this,Sl).showDialog(null,this,o+t*l,a+r*d,{...e,parentDimensions:i})}render(){var r,i;if(h(this,jl))return;const e=R(this,jl,document.createElement("div"));if(e.className="popup",h(this,wv)){const o=e.style.outlineColor=yt.makeHexColor(...h(this,wv));e.style.backgroundColor=`color-mix(in srgb, ${o} 30%, white)`}const t=document.createElement("span");if(t.className="header",(r=h(this,kv))!=null&&r.str){const o=document.createElement("span");o.className="title",t.append(o),{dir:o.dir,str:o.textContent}=h(this,kv)}if(e.append(t),h(this,Kp)){const o=document.createElement("time");o.className="popupDate",o.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),o.setAttribute("data-l10n-args",JSON.stringify({dateObj:h(this,Kp).valueOf()})),o.dateTime=h(this,Kp).toISOString(),t.append(o)}uV({html:h(this,Hn,Q5)||h(this,gu).str,dir:(i=h(this,gu))==null?void 0:i.dir,className:"popupContent"},e),h(this,ds).append(e)}updateEdited({rect:e,popup:t,deleted:r}){var i;if(h(this,Sl)){r?(this.remove(),R(this,Qp,null)):t&&(t.deleted?this.remove():(q(this,Hn,WI).call(this),R(this,Qp,t.text))),e&&(R(this,Jh,null),q(this,Hn,LI).call(this),q(this,Hn,NI).call(this));return}if(r||t!=null&&t.deleted){this.remove();return}q(this,Hn,Y5).call(this),h(this,By)||R(this,By,{contentsObj:h(this,gu),richText:h(this,ef)}),e&&R(this,Zh,null),t&&t.text&&(R(this,ef,q(this,Hn,RG).call(this,t.text)),R(this,Kp,bT.toDateObject(t.date)),R(this,gu,null)),(i=h(this,jl))==null||i.remove(),R(this,jl,null)}resetEdited(){var e;h(this,By)&&({contentsObj:Gi(this,gu)._,richText:Gi(this,ef)._}=h(this,By),R(this,By,null),(e=h(this,jl))==null||e.remove(),R(this,jl,null),R(this,Zh,null))}remove(){var e,t,r;if((e=h(this,$h))==null||e.abort(),R(this,$h,null),(t=h(this,jl))==null||t.remove(),R(this,jl,null),R(this,Yp,!1),R(this,mu,!1),(r=h(this,cs))==null||r.remove(),R(this,cs,null),this.trigger)for(const i of this.trigger)i.classList.remove("popupTriggerArea")}forceHide(){R(this,Yp,this.isVisible),h(this,Yp)&&(h(this,ds).hidden=!0)}maybeShow(){h(this,Sl)||(q(this,Hn,Y5).call(this),h(this,Yp)&&(h(this,jl)||q(this,Hn,Z5).call(this),R(this,Yp,!1),h(this,ds).hidden=!1))}get isVisible(){return h(this,Sl)?!1:h(this,ds).hidden===!1}}Sl=new WeakMap,Gp=new WeakMap,KT=new WeakMap,XT=new WeakMap,vv=new WeakMap,wv=new WeakMap,ds=new WeakMap,gu=new WeakMap,Kp=new WeakMap,Ry=new WeakMap,Sv=new WeakMap,jv=new WeakMap,mu=new WeakMap,jl=new WeakMap,$h=new WeakMap,Zh=new WeakMap,cs=new WeakMap,Jh=new WeakMap,Xp=new WeakMap,d_=new WeakMap,ef=new WeakMap,kv=new WeakMap,By=new WeakMap,Yp=new WeakMap,ro=new WeakMap,Qp=new WeakMap,Hn=new WeakSet,Y5=function(){var t;if(h(this,$h))return;R(this,$h,new AbortController);const{signal:e}=h(this,$h);for(const r of this.trigger)r.addEventListener("click",h(this,vv),{signal:e}),r.addEventListener("pointerenter",h(this,XT),{signal:e}),r.addEventListener("pointerleave",h(this,KT),{signal:e}),r.classList.add("popupTriggerArea");for(const r of h(this,Ry))(t=r.container)==null||t.addEventListener("keydown",h(this,Gp),{signal:e})},LI=function(){const e=h(this,Ry).find(t=>t.hasCommentButton);e&&R(this,Jh,e._normalizePoint(e.commentButtonPosition))},NI=function(){if(h(this,ro).extraPopupElement&&!h(this,ro).editor)return;h(this,cs)||this.renderCommentButton();const[e,t]=h(this,Jh),{style:r}=h(this,cs);r.left=`calc(${e}%)`,r.top=`calc(${t}% - var(--comment-button-dim))`},WI=function(){h(this,ro).extraPopupElement||(h(this,cs)||this.renderCommentButton(),h(this,cs).style.backgroundColor=this.commentButtonColor||"")},Q5=function(){const e=h(this,ef),t=h(this,gu);return e!=null&&e.str&&(!(t!=null&&t.str)||t.str===e.str)&&h(this,ef).html||null},UI=function(){var e,t,r;return((r=(t=(e=h(this,Hn,Q5))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:r.fontSize)||0},PG=function(){var e,t,r;return((r=(t=(e=h(this,Hn,Q5))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:r.color)||null},RG=function(e){const t=[],r={str:e,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:t}]}},i={style:{color:h(this,Hn,PG),fontSize:h(this,Hn,UI)?`calc(${h(this,Hn,UI)}px * var(--total-scale-factor))`:""}};for(const o of e.split(` `))t.push({name:"span",value:o,attributes:i});return r},BG=function(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key==="Enter"||e.key==="Escape"&&h(this,mu))&&q(this,Hn,$5).call(this)},IG=function(){if(h(this,Zh)!==null)return;const{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:r,pageX:i,pageY:o}}}=h(this,Sv);let a=!!h(this,jv),l=a?h(this,jv):h(this,d_);for(const m of h(this,Ry))if(!l||yt.intersect(m.data.rect,l)!==null){l=m.data.rect,a=!0;break}const d=yt.normalizeRect([l[0],e[3]-l[1]+e[1],l[2],e[3]-l[3]+e[1]]),u=a?l[2]-l[0]+5:0,f=d[0]+u,p=d[1];R(this,Zh,[100*(f-i)/t,100*(p-o)/r]);const{style:g}=h(this,ds);g.left=`${h(this,Zh)[0]}%`,g.top=`${h(this,Zh)[1]}%`},$5=function(){if(h(this,Sl)){h(this,Sl).toggleCommentPopup(this,!1);return}R(this,mu,!h(this,mu)),h(this,mu)?(q(this,Hn,Z5).call(this),h(this,ds).addEventListener("click",h(this,vv)),h(this,ds).addEventListener("keydown",h(this,Gp))):(q(this,Hn,HI).call(this),h(this,ds).removeEventListener("click",h(this,vv)),h(this,ds).removeEventListener("keydown",h(this,Gp)))},Z5=function(){h(this,jl)||this.render(),this.isVisible?h(this,mu)&&h(this,ds).classList.add("focused"):(q(this,Hn,IG).call(this),h(this,ds).hidden=!1,h(this,ds).style.zIndex=parseInt(h(this,ds).style.zIndex,10)+1e3)},HI=function(){h(this,ds).classList.remove("focused"),!(h(this,mu)||!this.isVisible)&&(h(this,ds).hidden=!0,h(this,ds).style.zIndex=parseInt(h(this,ds).style.zIndex,10)-1e3)};class MG extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=jn.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const e=this.contentElement=document.createElement("div");e.classList.add("annotationTextContent"),e.setAttribute("role","comment");for(const t of this.textContent){const r=document.createElement("span");r.textContent=t,e.append(r)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}var c_;class Phe extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,c_,null)}render(){this.container.classList.add("lineAnnotation");const{data:t,width:r,height:i}=this,o=this.svgFactory.create(r,i,!0),a=R(this,c_,this.svgFactory.createElement("svg:line"));return a.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),a.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),a.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),a.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),a.setAttribute("stroke-width",t.borderStyle.width||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),o.append(a),this.container.append(o),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,c_)}addHighlightArea(){this.container.classList.add("highlightArea")}}c_=new WeakMap;var u_;class Rhe extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,u_,null)}render(){this.container.classList.add("squareAnnotation");const{data:t,width:r,height:i}=this,o=this.svgFactory.create(r,i,!0),a=t.borderStyle.width,l=R(this,u_,this.svgFactory.createElement("svg:rect"));return l.setAttribute("x",a/2),l.setAttribute("y",a/2),l.setAttribute("width",r-a),l.setAttribute("height",i-a),l.setAttribute("stroke-width",a||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,u_)}addHighlightArea(){this.container.classList.add("highlightArea")}}u_=new WeakMap;var h_;class Bhe extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,h_,null)}render(){this.container.classList.add("circleAnnotation");const{data:t,width:r,height:i}=this,o=this.svgFactory.create(r,i,!0),a=t.borderStyle.width,l=R(this,h_,this.svgFactory.createElement("svg:ellipse"));return l.setAttribute("cx",r/2),l.setAttribute("cy",i/2),l.setAttribute("rx",r/2-a/2),l.setAttribute("ry",i/2-a/2),l.setAttribute("stroke-width",a||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,h_)}addHighlightArea(){this.container.classList.add("highlightArea")}}h_=new WeakMap;var f_;class zG extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,f_,null);this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:r,borderStyle:i,popupRef:o},width:a,height:l}=this;if(!r)return this.container;const d=this.svgFactory.create(a,l,!0);let c=[];for(let f=0,p=r.length;f=0&&a.setAttribute("stroke-width",r||1),i)for(let l=0,d=h(this,Iy).length;l{a.key==="Enter"&&(o?a.metaKey:a.ctrlKey)&&q(this,y_,VI).call(this)}),!r.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return h(this,m_)}addHighlightArea(){this.container.classList.add("highlightArea")}}m_=new WeakMap,y_=new WeakSet,VI=function(){var t;(t=this.downloadManager)==null||t.openOrDownloadData(this.content,this.filename)};var My,zy,_v,$p,x_,Oy,kl,b_,vf,J5,KI;const K3=class K3{constructor({div:e,accessibilityManager:t,annotationCanvasMap:r,annotationEditorUIManager:i,page:o,viewport:a,structTreeLayer:l,commentManager:d,linkService:c,annotationStorage:u}){N(this,vf);N(this,My,null);N(this,zy,null);N(this,_v,null);N(this,$p,new Map);N(this,x_,null);N(this,Oy,null);N(this,kl,[]);N(this,b_,!1);ve(this,"zIndex",0);this.div=e,R(this,My,t),R(this,zy,r),R(this,x_,l||null),R(this,Oy,c||null),R(this,_v,u||new I3),this.page=o,this.viewport=a,this._annotationEditorUIManager=i,this._commentManager=d||null}hasEditableAnnotations(){return h(this,$p).size>0}async render(e){var l;const{annotations:t}=e,r=this.div;k0(r,this.viewport);const i=new Map,o=[],a={data:null,layer:r,linkService:h(this,Oy),downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new kT,annotationStorage:h(this,_v),enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(const d of t){if(d.noHTML)continue;const c=d.annotationType===Cs.POPUP;if(c){const p=i.get(d.id);if(!p)continue;if(!this._commentManager){o.push(d);continue}a.elements=p}else if(d.rect[2]===d.rect[0]||d.rect[3]===d.rect[1])continue;a.data=d;const u=HP.create(a);if(!u.isRenderable)continue;c||(h(this,kl).push(u),d.popupRef&&i.getOrInsertComputed(d.popupRef,F3).push(u));const f=u.render();d.hidden&&(f.style.visibility="hidden"),u._isEditable&&(h(this,$p).set(u.data.id,u),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(u))}await q(this,vf,J5).call(this);for(const d of o){const c=a.elements=i.get(d.id);a.data=d;const u=HP.create(a);if(!u.isRenderable)continue;const f=u.render();u.contentElement.id=`${Yx}${d.id}`,d.hidden&&(f.style.visibility="hidden"),c.at(-1).container.after(f)}q(this,vf,KI).call(this)}async addLinkAnnotations(e){const t={data:null,layer:this.div,linkService:h(this,Oy),svgFactory:new kT,parent:this};for(const r of e){r.borderStyle||(r.borderStyle=K3._defaultBorderStyle),t.data=r;const i=HP.create(t);i.isRenderable&&(i.render(),i.contentElement.id=`${Yx}${r.id}`,h(this,kl).push(i))}await q(this,vf,J5).call(this)}update({viewport:e}){const t=this.div;this.viewport=e,k0(t,{rotation:e.rotation}),q(this,vf,KI).call(this),t.hidden=!1}getEditableAnnotations(){return h(this,$p).values()}getEditableAnnotation(e){return h(this,$p).get(e)}addFakeAnnotation(e){const{div:t}=this,{id:r,rotation:i}=e,o=new khe({data:{id:r,rect:e.getPDFRect(),rotation:i},editor:e,layer:t,parent:this,enableComment:!!this._commentManager,linkService:h(this,Oy),annotationStorage:h(this,_v)});return o.render(),o.contentElement.id=`${Yx}${r}`,o.createOrUpdatePopup(),h(this,kl).push(o),o}removeAnnotation(e){var i;const t=h(this,kl).findIndex(o=>o.data.id===e);if(t<0)return;const[r]=h(this,kl).splice(t,1);(i=h(this,My))==null||i.removePointerInTextLayer(r.contentElement)}updateFakeAnnotations(e){if(e.length!==0){for(const t of e)t.updateFakeAnnotationElement(this);q(this,vf,J5).call(this)}}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}static get _defaultBorderStyle(){return Cn(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:Sx.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}};My=new WeakMap,zy=new WeakMap,_v=new WeakMap,$p=new WeakMap,x_=new WeakMap,Oy=new WeakMap,kl=new WeakMap,b_=new WeakMap,vf=new WeakSet,J5=async function(){var r,i,o;if(h(this,kl).length===0)return;this.div.replaceChildren();const e=[];if(!h(this,b_)){R(this,b_,!0);for(const{contentElement:a,data:{id:l}}of h(this,kl)){const d=a.id=`${Yx}${l}`;e.push((r=h(this,x_))==null?void 0:r.getAriaAttributes(d).then(c=>{if(c)for(const[u,f]of c)a.setAttribute(u,f)}))}}h(this,kl).sort(({data:{rect:[a,l,d,c]}},{data:{rect:[u,f,p,g]}})=>{if(a===d&&l===c)return 1;if(u===p&&f===g)return-1;const m=c,y=l,v=(l+c)/2,x=g,w=f,S=(f+g)/2;if(v>=x&&S<=y)return-1;if(S>=m&&v<=w)return 1;const _=(a+d)/2,b=(u+p)/2;return _-b});const t=document.createDocumentFragment();for(const a of h(this,kl))t.append(a.container),this._commentManager?(o=((i=a.extraPopupElement)==null?void 0:i.popup)||a.popup)==null||o.renderCommentButton():a.extraPopupElement&&t.append(a.extraPopupElement.render());if(this.div.append(t),await Promise.all(e),h(this,My))for(const a of h(this,kl))h(this,My).addPointerInTextLayer(a.contentElement,!1)},KI=function(){var t;if(!h(this,zy))return;const e=this.div;for(const[r,i]of h(this,zy)){const o=e.querySelector(`[data-annotation-id="${r}"]`);if(!o)continue;i.className="annotationContent";const{firstChild:a}=o;a?a.nodeName==="CANVAS"?a.replaceWith(i):a.classList.contains("annotationContent")?a.after(i):a.before(i):o.append(i);const l=h(this,$p).get(r);l&&(l._hasNoCanvas?((t=this._annotationEditorUIManager)==null||t.setMissingCanvas(r,o.id,i),l._hasNoCanvas=!1):l.canvas=i)}h(this,zy).clear()};let GI=K3;const Q2=/\r\n?|\n/g;var _l,v_,Ly,Cl,Es,NG,WG,UG,eA,wf,tA,nA,HG,YI,qG;const wi=class wi extends xi{constructor(t){super({...t,name:"freeTextEditor"});N(this,Es);N(this,_l,"");N(this,v_,`${this.id}-editor`);N(this,Ly,null);N(this,Cl);ve(this,"_colorPicker",null);this.color=t.color||wi._defaultColor||xi._defaultLineColor,R(this,Cl,t.fontSize||wi._defaultFontSize),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert"),this.canAddComment=!1}static get _keyboardManager(){const t=wi.prototype,r=a=>a.isEmpty(),i=_0.TRANSLATE_SMALL,o=_0.TRANSLATE_BIG;return Cn(this,"_keyboardManager",new uC([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:r}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-o,0],checker:r}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:r}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[o,0],checker:r}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:r}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-o],checker:r}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:r}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,o],checker:r}]]))}static initialize(t,r){xi.initialize(t,r);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,r){switch(t){case Wn.FREETEXT_SIZE:wi._defaultFontSize=r;break;case Wn.FREETEXT_COLOR:wi._defaultColor=r;break}}updateParams(t,r){switch(t){case Wn.FREETEXT_SIZE:q(this,Es,NG).call(this,r);break;case Wn.FREETEXT_COLOR:q(this,Es,WG).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Wn.FREETEXT_SIZE,wi._defaultFontSize],[Wn.FREETEXT_COLOR,wi._defaultColor||xi._defaultLineColor]]}get propertiesToUpdate(){return[[Wn.FREETEXT_SIZE,h(this,Cl)],[Wn.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||(this._colorPicker=new jT(this)),[["colorPicker",this._colorPicker]]}get colorType(){return Wn.FREETEXT_COLOR}onUpdatedColor(){var t;this.editorDiv.style.color=this.color,(t=this._colorPicker)==null||t.update(this.color),super.onUpdatedColor()}_translateEmpty(t,r){this._uiManager.translateSelectedEditors(t,r,!0)}getInitialTranslation(){const t=this.parentScale;return[-wi._internalPadding*t,-(wi._internalPadding+h(this,Cl))*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),R(this,Ly,new AbortController);const t=this._uiManager.combinedSignal(h(this,Ly));return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){var t;return super.disableEditMode()?(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",h(this,v_)),this._isDraggable=!0,(t=h(this,Ly))==null||t.abort(),R(this,Ly,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0):!1}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){var r;this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),(r=this._initialOptions)!=null&&r.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=h(this,_l),r=R(this,_l,q(this,Es,UG).call(this).trimEnd());if(t===r)return;const i=o=>{if(R(this,_l,o),!o){this.remove();return}q(this,Es,nA).call(this),this._uiManager.rebuild(this),q(this,Es,eA).call(this)};this.addCommands({cmd:()=>{i(r)},undo:()=>{i(t)},mustExec:!1}),q(this,Es,eA).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){wi._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,r;(this._isCopy||this.annotationElementId)&&(t=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",h(this,v_)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${h(this,Cl)}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[o,a]=this.parentDimensions;if(this.annotationElementId){const{position:l}=this._initialData;let[d,c]=this.getInitialTranslation();[d,c]=this.pageTranslationToScreen(d,c);const[u,f]=this.pageDimensions,[p,g]=this.pageTranslation;let m,y;switch(this.rotation){case 0:m=t+(l[0]-p)/u,y=r+this.height-(l[1]-g)/f;break;case 90:m=t+(l[0]-p)/u,y=r-(l[1]-g)/f,[d,c]=[c,-d];break;case 180:m=t-this.width+(l[0]-p)/u,y=r-(l[1]-g)/f,[d,c]=[-d,-c];break;case 270:m=t+(l[0]-p-this.height*f)/u,y=r+(l[1]-g-this.width*u)/f,[d,c]=[-c,d];break}this.setAt(m*o,y*a,d,c)}else this._moveAfterPaste(t,r);q(this,Es,nA).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(t){var m,y,v;const r=t.clipboardData||window.clipboardData,{types:i}=r;if(i.length===1&&i[0]==="text/plain")return;t.preventDefault();const o=q(m=wi,wf,YI).call(m,r.getData("text")||"").replaceAll(Q2,` `);if(!o)return;const a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();const l=a.getRangeAt(0);if(!o.includes(` `)){l.insertNode(document.createTextNode(o)),this.editorDiv.normalize(),a.collapseToStart();return}const{startContainer:d,startOffset:c}=l,u=[],f=[];if(d.nodeType===Node.TEXT_NODE){const x=d.parentElement;if(f.push(d.nodeValue.slice(c).replaceAll(Q2,"")),x!==this.editorDiv){let w=u;for(const S of this.editorDiv.childNodes){if(S===x){w=f;continue}w.push(q(y=wi,wf,tA).call(y,S))}}u.push(d.nodeValue.slice(0,c).replaceAll(Q2,""))}else if(d===this.editorDiv){let x=u,w=0;for(const S of this.editorDiv.childNodes)w++===c&&(x=f),x.push(q(v=wi,wf,tA).call(v,S))}R(this,_l,`${u.join(` `)}${o}${f.join(` `)}`),q(this,Es,nA).call(this);const p=new Range;let g=Math.sumPrecise(u.map(x=>x.length));for(const{firstChild:x}of this.editorDiv.childNodes)if(x.nodeType===Node.TEXT_NODE){const w=x.nodeValue.length;if(g<=w){p.setStart(x,g),p.setEnd(x,g);break}g-=w}a.removeAllRanges(),a.addRange(p)}get contentDiv(){return this.editorDiv}getPDFRect(){const t=wi._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,r,i){var l;let o=null;if(t instanceof MG){const{data:{defaultAppearanceData:{fontSize:d,fontColor:c},rect:u,rotation:f,id:p,popupRef:g,richText:m,contentsObj:y,creationDate:v,modificationDate:x},textContent:w,textPosition:S,parent:{page:{pageNumber:_}}}=t;if(!w||w.length===0)return null;o=t={annotationType:jn.FREETEXT,color:Array.from(c),fontSize:d,value:w.join(` `),position:S,pageIndex:_-1,rect:u.slice(0),rotation:f,annotationElementId:p,id:p,deleted:!1,popupRef:g,comment:(y==null?void 0:y.str)||null,richText:m,creationDate:v,modificationDate:x}}const a=await super.deserialize(t,r,i);return R(a,Cl,t.fontSize),a.color=yt.makeHexColor(...t.color),R(a,_l,q(l=wi,wf,YI).call(l,t.value)),a._initialData=o,t.comment&&a.setCommentData(t),a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const r=xi._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:r,fontSize:h(this,Cl),value:q(this,Es,HG).call(this)});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!q(this,Es,qG).call(this,i)?null:(i.id=this.annotationElementId,i)}renderAnnotationElement(t){const r=super.renderAnnotationElement(t);if(!r)return null;const{style:i}=r;i.fontSize=`calc(${h(this,Cl)}px * var(--total-scale-factor))`,i.color=this.color,r.replaceChildren();for(const o of h(this,_l).split(` `)){const a=document.createElement("div");a.append(o?document.createTextNode(o):document.createElement("br")),r.append(a)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:h(this,_l)}}),r}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}};_l=new WeakMap,v_=new WeakMap,Ly=new WeakMap,Cl=new WeakMap,Es=new WeakSet,NG=function(t){const r=o=>{this.editorDiv.style.fontSize=`calc(${o}px * var(--total-scale-factor))`,this.translate(0,-(o-h(this,Cl))*this.parentScale),R(this,Cl,o),q(this,Es,eA).call(this)},i=h(this,Cl);this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},WG=function(t){const r=o=>{this.color=o,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},UG=function(){var i;const t=[];this.editorDiv.normalize();let r=null;for(const o of this.editorDiv.childNodes)(r==null?void 0:r.nodeType)===Node.TEXT_NODE&&o.nodeName==="BR"||(t.push(q(i=wi,wf,tA).call(i,o)),r=o);return t.join(` `)},eA=function(){const[t,r]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:o,div:a}=this,l=a.style.display,d=a.classList.contains("hidden");a.classList.remove("hidden"),a.style.display="hidden",o.div.append(this.div),i=a.getBoundingClientRect(),a.remove(),a.style.display=l,a.classList.toggle("hidden",d)}this.rotation%180===this.parentRotation%180?(this.width=i.width/t,this.height=i.height/r):(this.width=i.height/t,this.height=i.width/r),this.fixAndSetPosition()},wf=new WeakSet,tA=function(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Q2,"")},nA=function(){if(this.editorDiv.replaceChildren(),!!h(this,_l))for(const t of h(this,_l).split(` `)){const r=document.createElement("div");r.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(r)}},HG=function(){return h(this,_l).replaceAll(" "," ")},YI=function(t){return t.replaceAll(" "," ")},qG=function(t){const{value:r,fontSize:i,color:o,pageIndex:a}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==r||t.fontSize!==i||t.color.some((l,d)=>l!==o[d])||t.pageIndex!==a},N(wi,wf),ve(wi,"_freeTextDefaultContent",""),ve(wi,"_internalPadding",0),ve(wi,"_defaultColor",null),ve(wi,"_defaultFontSize",10),ve(wi,"_type","freetext"),ve(wi,"_editorType",jn.FREETEXT);let XI=wi;class Wt{toSVGPath(){Hr("Abstract method `toSVGPath` must be implemented.")}get box(){Hr("Abstract getter `box` must be implemented.")}serialize(e,t){Hr("Abstract method `serialize` must be implemented.")}static _rescale(e,t,r,i,o,a){a||(a=new Float32Array(e.length));for(let l=0,d=e.length;l=6;i-=6)isNaN(t[i])?r.push(`L${t[i+4]} ${t[i+5]}`):r.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);return q(this,Hs,GG).call(this,r),r.join(" ")}newFreeDrawOutline(e,t,r,i,o,a){return new $G(e,t,r,i,o,a)}getOutlines(){var f;const e=h(this,yu),t=h(this,xc),r=h(this,Jn),[i,o,a,l]=h(this,Al),d=new Float32Array((((f=h(this,Zp))==null?void 0:f.length)??0)+2);for(let p=0,g=d.length-2;p=6;p-=6)for(let g=0;g<6;g+=2){if(isNaN(t[p+g])){c[u]=c[u+1]=NaN,u+=2;continue}c[u]=t[p+g],c[u+1]=t[p+g+1],u+=2}return q(this,Hs,YG).call(this,c,u),this.newFreeDrawOutline(c,d,h(this,Al),h(this,Tv),h(this,Cv),h(this,Av))}};Al=new WeakMap,xc=new WeakMap,Cv=new WeakMap,Av=new WeakMap,yu=new WeakMap,Jn=new WeakMap,Ny=new WeakMap,Wy=new WeakMap,w_=new WeakMap,S_=new WeakMap,Tv=new WeakMap,Fv=new WeakMap,Zp=new WeakMap,j_=new WeakMap,YT=new WeakMap,QT=new WeakMap,Hs=new WeakSet,TS=function(){const e=h(this,Jn).subarray(4,6),t=h(this,Jn).subarray(16,18),[r,i,o,a]=h(this,Al);return[(h(this,Ny)+(e[0]-t[0])/2-r)/o,(h(this,Wy)+(e[1]-t[1])/2-i)/a,(h(this,Ny)+(t[0]-e[0])/2-r)/o,(h(this,Wy)+(t[1]-e[1])/2-i)/a]},VG=function(){const[e,t,r,i]=h(this,Al),[o,a,l,d]=q(this,Hs,TS).call(this);return`M${(h(this,Jn)[2]-e)/r} ${(h(this,Jn)[3]-t)/i} L${(h(this,Jn)[4]-e)/r} ${(h(this,Jn)[5]-t)/i} L${o} ${a} L${l} ${d} L${(h(this,Jn)[16]-e)/r} ${(h(this,Jn)[17]-t)/i} L${(h(this,Jn)[14]-e)/r} ${(h(this,Jn)[15]-t)/i} Z`},GG=function(e){const t=h(this,xc);e.push(`L${t[4]} ${t[5]} Z`)},KG=function(e){const[t,r,i,o]=h(this,Al),a=h(this,Jn).subarray(4,6),l=h(this,Jn).subarray(16,18),[d,c,u,f]=q(this,Hs,TS).call(this);e.push(`L${(a[0]-t)/i} ${(a[1]-r)/o} L${d} ${c} L${u} ${f} L${(l[0]-t)/i} ${(l[1]-r)/o}`)},XG=function(e){const t=h(this,Jn),[r,i,o,a]=h(this,Al),[l,d,c,u]=q(this,Hs,TS).call(this),f=new Float32Array(36);return f.set([NaN,NaN,NaN,NaN,(t[2]-r)/o,(t[3]-i)/a,NaN,NaN,NaN,NaN,(t[4]-r)/o,(t[5]-i)/a,NaN,NaN,NaN,NaN,l,d,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,(t[16]-r)/o,(t[17]-i)/a,NaN,NaN,NaN,NaN,(t[14]-r)/o,(t[15]-i)/a],0),this.newFreeDrawOutline(f,e,h(this,Al),h(this,Tv),h(this,Cv),h(this,Av))},YG=function(e,t){const r=h(this,xc);return e.set([NaN,NaN,NaN,NaN,r[4],r[5]],t),t+=6},QG=function(e,t){const r=h(this,Jn).subarray(4,6),i=h(this,Jn).subarray(16,18),[o,a,l,d]=h(this,Al),[c,u,f,p]=q(this,Hs,TS).call(this);return e.set([NaN,NaN,NaN,NaN,(r[0]-o)/l,(r[1]-a)/d,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,f,p,NaN,NaN,NaN,NaN,(i[0]-o)/l,(i[1]-a)/d],t),t+=24},N(xh,j_,8),N(xh,YT,2),N(xh,QT,h(xh,j_)+h(xh,YT));let _T=xh;var Dv,Uy,tf,k_,Tl,__,vs,$T,ZG;class $G extends Wt{constructor(t,r,i,o,a,l){super();N(this,$T);N(this,Dv);N(this,Uy,new Float32Array(4));N(this,tf);N(this,k_);N(this,Tl);N(this,__);N(this,vs);R(this,vs,t),R(this,Tl,r),R(this,Dv,i),R(this,__,o),R(this,tf,a),R(this,k_,l),this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],q(this,$T,ZG).call(this,l);const[d,c,u,f]=h(this,Uy);for(let p=0,g=t.length;px?(l=v,d=x):d===x&&(l=f(l,v)),up[1]?(l=p[0],d=p[1]):d===p[1]&&(l=f(l,p[0])),ut[0]-r[0]||t[1]-r[1]||t[2]-r[2]);const e=[];for(const t of h(this,Jp))t[3]?(e.push(...q(this,Ta,$I).call(this,t)),q(this,Ta,eK).call(this,t)):(q(this,Ta,tK).call(this,t),e.push(...q(this,Ta,$I).call(this,t)));return q(this,Ta,JG).call(this,e)}}C_=new WeakMap,A_=new WeakMap,T_=new WeakMap,Jp=new WeakMap,bc=new WeakMap,Ta=new WeakSet,JG=function(e){const t=[],r=new Set;for(const a of e){const[l,d,c]=a;t.push([l,d,a],[l,c,a])}t.sort((a,l)=>a[1]-l[1]||a[0]-l[0]);for(let a=0,l=t.length;a0;){const a=r.values().next().value;let[l,d,c,u,f]=a;r.delete(a);let p=l,g=d;for(o=[l,c],i.push(o);;){let m;if(r.has(u))m=u;else if(r.has(f))m=f;else break;r.delete(m),[l,d,c,u,f]=m,p!==l&&(o.push(p,g,l,g===d?d:c),p=l),g=g===d?c:d}o.push(p,g)}return new Whe(i,h(this,C_),h(this,A_),h(this,T_))},rA=function(e){const t=h(this,bc);let r=0,i=t.length-1;for(;r<=i;){const o=r+i>>1,a=t[o][0];if(a===e)return o;a=0;i--){const[o,a]=h(this,bc)[i];if(o!==e)break;if(o===e&&a===t){h(this,bc).splice(i,1);return}}},$I=function(e){const[t,r,i]=e,o=[[t,r,i]],a=q(this,Ta,rA).call(this,i);for(let l=0;l=d){if(g>c)o[u][1]=c;else{if(f===1)return[];o.splice(u,1),u--,f--}continue}o[u][2]=d,g>c&&o.push([t,c,g])}}}return o};var F_,Ev;class Whe extends Wt{constructor(t,r,i,o){super();N(this,F_);N(this,Ev);R(this,Ev,t),R(this,F_,r),this.firstPoint=i,this.lastPoint=o}toSVGPath(){const t=[];for(const r of h(this,Ev)){let[i,o]=r;t.push(`M${i} ${o}`);for(let a=2;a-1?(R(this,_o,!0),q(this,Un,iA).call(this,t),q(this,Un,cm).call(this)):h(this,nf)&&(R(this,Pv,t.anchorNode),R(this,D_,t.anchorOffset),R(this,P_,t.focusNode),R(this,R_,t.focusOffset),q(this,Un,JI).call(this),q(this,Un,cm).call(this),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}static get _keyboardManager(){const t=Rr.prototype;return Cn(this,"_keyboardManager",new uC([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:h(this,_o)?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:h(this,wd),methodOfCreation:h(this,B_)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}static initialize(t,r){var i;xi.initialize(t,r),Rr._defaultColor||(Rr._defaultColor=((i=r.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(t,r){switch(t){case Wn.HIGHLIGHT_COLOR:Rr._defaultColor=r;break;case Wn.HIGHLIGHT_THICKNESS:Rr._defaultThickness=r;break}}translateInPage(t,r){}get toolbarPosition(){return h(this,Bv)}get commentButtonPosition(){return h(this,Rv)}updateParams(t,r){switch(t){case Wn.HIGHLIGHT_COLOR:q(this,Un,nK).call(this,r);break;case Wn.HIGHLIGHT_THICKNESS:q(this,Un,rK).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Wn.HIGHLIGHT_COLOR,Rr._defaultColor],[Wn.HIGHLIGHT_THICKNESS,Rr._defaultThickness]]}get propertiesToUpdate(){return[[Wn.HIGHLIGHT_COLOR,this.color||Rr._defaultColor],[Wn.HIGHLIGHT_THICKNESS,h(this,wd)||Rr._defaultThickness],[Wn.HIGHLIGHT_FREE,h(this,_o)]]}onUpdatedColor(){var t,r;(t=this.parent)==null||t.drawLayer.updateProperties(h(this,Dl),{root:{fill:this.color,"fill-opacity":this.opacity}}),(r=h(this,E_))==null||r.updateColor(this.color),super.onUpdatedColor()}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",R(this,E_,new ST({editor:this}))]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(q(this,Un,oA).call(this))}getBaseTranslation(){return[0,0]}getRect(t,r){return super.getRect(t,r,q(this,Un,oA).call(this))}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){q(this,Un,eM).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(q(this,Un,cm).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let r=!1;this.parent&&!t?q(this,Un,eM).call(this):t&&(q(this,Un,cm).call(this,t),r=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),this.show(this._isVisible),r&&this.select()}rotate(t){var o,a,l;const{drawLayer:r}=this.parent;let i;h(this,_o)?(t=(t-this.rotation+360)%360,i=q(o=Rr,Fd,Fx).call(o,h(this,Fl).box,t)):i=q(a=Rr,Fd,Fx).call(a,[this.x,this.y,this.width,this.height],t),r.updateProperties(h(this,Dl),{bbox:i,root:{"data-main-rotation":t}}),r.updateProperties(h(this,ea),{bbox:q(l=Rr,Fd,Fx).call(l,h(this,Ga).box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();h(this,Iv)&&(t.setAttribute("aria-label",h(this,Iv)),t.setAttribute("role","mark")),h(this,_o)?t.classList.add("free"):this.div.addEventListener("keydown",q(this,Un,sK).bind(this),{signal:this._uiManager._signal});const r=R(this,qy,document.createElement("div"));return t.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=h(this,Hy),this.setDims(),xV(this,h(this,qy),["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{hovered:!0}})}pointerleave(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{hovered:!1}})}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:q(this,Un,sA).call(this,!0);break;case 1:case 3:q(this,Un,sA).call(this,!1);break}}select(){var t;super.select(),h(this,ea)&&((t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{hovered:!1,selected:!0}}))}unselect(){var t;super.unselect(),h(this,ea)&&((t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{selected:!1}}),h(this,_o)||q(this,Un,sA).call(this,!1))}get _mustFixPosition(){return!h(this,_o)}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(h(this,Dl),{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(h(this,ea),{rootClass:{hidden:!t}}))}static startHighlighting(t,r,{target:i,x:o,y:a}){const{x:l,y:d,width:c,height:u}=i.getBoundingClientRect(),f=new AbortController,p=t.combinedSignal(f),g=m=>{f.abort(),q(this,Fd,dK).call(this,t,m)};window.addEventListener("blur",g,{signal:p}),window.addEventListener("pointerup",g,{signal:p}),window.addEventListener("pointerdown",$i,{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Hd,{signal:p}),i.addEventListener("pointermove",q(this,Fd,lK).bind(this,t),{signal:p}),this._freeHighlight=new ZI({x:o,y:a},[l,d,c,u],t.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static async deserialize(t,r,i){var v,x,w,S;let o=null;if(t instanceof OG){const{data:{quadPoints:_,rect:b,rotation:C,id:T,color:F,opacity:A,popupRef:D,richText:P,contentsObj:L,creationDate:W,modificationDate:O},parent:{page:{pageNumber:U}}}=t;o=t={annotationType:jn.HIGHLIGHT,color:Array.from(F),opacity:A,quadPoints:_,boxes:null,pageIndex:U-1,rect:b.slice(0),rotation:C,annotationElementId:T,id:T,deleted:!1,popupRef:D,richText:P,comment:(L==null?void 0:L.str)||null,creationDate:W,modificationDate:O}}else if(t instanceof O3){const{data:{inkLists:_,rect:b,rotation:C,id:T,color:F,borderStyle:{rawWidth:A},popupRef:D,richText:P,contentsObj:L,creationDate:W,modificationDate:O},parent:{page:{pageNumber:U}}}=t;o=t={annotationType:jn.HIGHLIGHT,color:Array.from(F),thickness:A,inkLists:_,boxes:null,pageIndex:U-1,rect:b.slice(0),rotation:C,annotationElementId:T,id:T,deleted:!1,popupRef:D,richText:P,comment:(L==null?void 0:L.str)||null,creationDate:W,modificationDate:O}}const{color:a,quadPoints:l,inkLists:d,outlines:c,opacity:u}=t,f=await super.deserialize(t,r,i);f.color=yt.makeHexColor(...a),f.opacity=u||1,d&&R(f,wd,t.thickness),f._initialData=o,t.comment&&f.setCommentData(t);const[p,g]=f.pageDimensions,[m,y]=f.pageTranslation;if(l){const _=R(f,nf,[]);for(let b=0;b=0)R(this,Dl,r),R(this,Hy,i),this.parent.drawLayer.finalizeDraw(r,{bbox:t.box,path:{d:t.toSVGPath()}}),R(this,ea,this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:h(this,Ga).box,path:{d:h(this,Ga).toSVGPath()}},!0));else if(this.parent){const m=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(h(this,Dl),{bbox:q(p=Rr,Fd,Fx).call(p,h(this,Fl).box,(m-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(h(this,ea),{bbox:q(g=Rr,Fd,Fx).call(g,h(this,Ga).box,m),path:{d:h(this,Ga).toSVGPath()}})}const[a,l,d,c]=t.box;switch(this.rotation){case 0:this.x=a,this.y=l,this.width=d,this.height=c;break;case 90:{const[m,y]=this.parentDimensions;this.x=l,this.y=1-a,this.width=d*y/m,this.height=c*m/y;break}case 180:this.x=1-a,this.y=1-l,this.width=d,this.height=c;break;case 270:{const[m,y]=this.parentDimensions;this.x=1-l,this.y=a,this.width=d*y/m,this.height=c*m/y;break}}const{firstPoint:u}=t;R(this,Rv,[(u[0]-a)/d,(u[1]-l)/c]);const{lastPoint:f}=h(this,Ga);R(this,Bv,[(f[0]-a)/d,(f[1]-l)/c])},nK=function(t){const r=(a,l)=>{this.color=a,this.opacity=l,this.onUpdatedColor()},i=this.color,o=this.opacity;this.addCommands({cmd:r.bind(this,t,Rr._defaultOpacity),undo:r.bind(this,i,o),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)},rK=function(t){const r=h(this,wd),i=o=>{R(this,wd,o),q(this,Un,iK).call(this,o)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)},iK=function(t){h(this,_o)&&(q(this,Un,iA).call(this,{highlightOutlines:h(this,Fl).getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())},eM=function(){h(this,Dl)===null||!this.parent||(this.parent.drawLayer.remove(h(this,Dl)),R(this,Dl,null),this.parent.drawLayer.remove(h(this,ea)),R(this,ea,null))},cm=function(t=this.parent){h(this,Dl)===null&&({id:Gi(this,Dl)._,clipPathId:Gi(this,Hy)._}=t.drawLayer.draw({bbox:h(this,Fl).box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:h(this,_o)},path:{d:h(this,Fl).toSVGPath()}},!1,!0),R(this,ea,t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:h(this,_o)},bbox:h(this,Ga).box,path:{d:h(this,Ga).toSVGPath()}},h(this,_o))),h(this,qy)&&(h(this,qy).style.clipPath=h(this,Hy)))},Fd=new WeakSet,Fx=function([t,r,i,o],a){switch(a){case 90:return[1-r-o,t,o,i];case 180:return[1-t-i,1-r-o,i,o];case 270:return[r,1-t-i,o,i]}return[t,r,i,o]},sK=function(t){Rr._keyboardManager.exec(this,t)},sA=function(t){if(!h(this,Pv))return;const r=window.getSelection();t?r.setPosition(h(this,Pv),h(this,D_)):r.setPosition(h(this,P_),h(this,R_))},oA=function(){return h(this,_o)?this.rotation:0},oK=function(){if(h(this,_o))return null;const[t,r]=this.pageDimensions,[i,o]=this.pageTranslation,a=h(this,nf),l=new Float32Array(a.length*8);let d=0;for(const{x:c,y:u,width:f,height:p}of a){const g=c*t+i,m=(1-u)*r+o;l[d]=l[d+4]=g,l[d+1]=l[d+3]=m,l[d+2]=l[d+6]=g+f*t,l[d+5]=l[d+7]=m-p*r,d+=8}return l},aK=function(t){return h(this,Fl).serialize(t,q(this,Un,oA).call(this))},lK=function(t,r){this._freeHighlight.add(r)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})},dK=function(t,r){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(r,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},cK=function(t){const{color:r}=this._initialData;return this.hasEditedComment||t.color.some((i,o)=>i!==r[o])},N(Rr,Fd),ve(Rr,"_defaultColor",null),ve(Rr,"_defaultOpacity",1),ve(Rr,"_defaultThickness",12),ve(Rr,"_type","highlight"),ve(Rr,"_editorType",jn.HIGHLIGHT),ve(Rr,"_freeHighlightId",-1),ve(Rr,"_freeHighlight",null),ve(Rr,"_freeHighlightClipId","");let CT=Rr;var Vy;class uK{constructor(){N(this,Vy,Object.create(null))}updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(const[t,r]of Object.entries(e))t.startsWith("_")||this.updateProperty(t,r)}updateSVGProperty(e,t){h(this,Vy)[e]=t}toSVGProperties(){const e=h(this,Vy);return R(this,Vy,Object.create(null)),{root:e}}reset(){R(this,Vy,Object.create(null))}updateAll(e=this){this.updateProperties(e)}clone(){Hr("Not implemented")}}Vy=new WeakMap;var ma,Mv,io,Gy,Ky,kr,tM,nM,rM,FS,hK,aA,DS,Dx;const rr=class rr extends xi{constructor(t){super(t);N(this,kr);N(this,ma,null);N(this,Mv);ve(this,"_colorPicker",null);ve(this,"_drawId",null);R(this,Mv,t.mustBeCommitted||!1),this._addOutlines(t)}onUpdatedColor(){var t;(t=this._colorPicker)==null||t.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){var t,r;(r=(t=this._colorPicker)==null?void 0:t.updateOpacity)==null||r.call(t,this.opacity)}_addOutlines(t){t.drawOutlines&&(q(this,kr,tM).call(this,t),q(this,kr,FS).call(this))}static _mergeSVGProperties(t,r){const i=new Set(Object.keys(t));for(const[o,a]of Object.entries(r))i.has(o)?Object.assign(t[o],a):t[o]=a;return t}static getDefaultDrawingOptions(t){Hr("Not implemented")}static get typesMap(){Hr("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,r){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,r),this._currentParent&&(h(rr,io).updateProperty(i,r),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,r){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,r)}static get defaultPropertiesToUpdate(){const t=[],r=this._defaultDrawingOptions;for(const[i,o]of this.typesMap)t.push([i,r[o]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:r}=this;for(const[i,o]of this.constructor.typesMap)t.push([i,r[o]]);return t}_updateProperty(t,r,i){const o=this._drawingOptions,a=o[r],l=d=>{var u;o.updateProperty(r,d);const c=h(this,ma).updateProperty(r,d);c&&q(this,kr,DS).call(this,c),(u=this.parent)==null||u.drawLayer.updateProperties(this._drawId,o.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:l.bind(this,i),undo:l.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,r){const i=this.constructor.typesMap.get(this.colorType),o=this.constructor.typesMap.get(this.opacityType),a=this._drawingOptions,l=a[i],d=a[o],c=(u,f)=>{var p;a.updateProperty(i,u),a.updateProperty(o,f),h(this,ma).updateProperty(i,u),h(this,ma).updateProperty(o,f),(p=this.parent)==null||p.drawLayer.updateProperties(this._drawId,a.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:c.bind(this,t,r),undo:c.bind(this,l,d),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties(h(this,ma).getPathResizingSVGProperties(q(this,kr,aA).call(this)),{bbox:q(this,kr,Dx).call(this)}))}_onResized(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties(h(this,ma).getPathResizedSVGProperties(q(this,kr,aA).call(this)),{bbox:q(this,kr,Dx).call(this)}))}_onTranslating(t,r){var i;(i=this.parent)==null||i.drawLayer.updateProperties(this._drawId,{bbox:q(this,kr,Dx).call(this)})}_onTranslated(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties(h(this,ma).getPathTranslatedSVGProperties(q(this,kr,aA).call(this),this.parentDimensions),{bbox:q(this,kr,Dx).call(this)}))}_onStartDragging(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,h(this,Mv)&&(R(this,Mv,!1),this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){q(this,kr,rM).call(this),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(q(this,kr,FS).call(this),q(this,kr,DS).call(this,h(this,ma).box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let r=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),q(this,kr,rM).call(this)):t&&(this._uiManager.addShouldRescale(this),q(this,kr,FS).call(this,t),r=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),r&&this.select()}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties({bbox:q(this,kr,Dx).call(this)},h(this,ma).updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&q(this,kr,DS).call(this,h(this,ma).updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,r;this._isCopy&&(t=this.x,r=this.y);const i=super.render();i.classList.add("draw");const o=document.createElement("div");return i.append(o),o.setAttribute("aria-hidden","true"),o.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,r),i}static createDrawerInstance(t,r,i,o,a){Hr("Not implemented")}static startDrawing(t,r,i,o){var v;const{target:a,offsetX:l,offsetY:d,pointerId:c,pointerType:u}=o;if(Yo.isInitializedAndDifferentPointerType(u))return;const{viewport:{rotation:f}}=t,{width:p,height:g}=a.getBoundingClientRect(),m=R(rr,Gy,new AbortController),y=t.combinedSignal(m);if(Yo.setPointer(u,c),window.addEventListener("pointerup",x=>{Yo.isSamePointerIdOrRemove(x.pointerId)&&this._endDraw(x)},{signal:y}),window.addEventListener("pointercancel",x=>{Yo.isSamePointerIdOrRemove(x.pointerId)&&this._currentParent.endDrawingSession()},{signal:y}),window.addEventListener("pointerdown",x=>{Yo.isSamePointerType(x.pointerType)&&(Yo.initializeAndAddPointerId(x.pointerId),h(rr,io).isCancellable()&&(h(rr,io).removeLastElement(),h(rr,io).isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:y}),window.addEventListener("contextmenu",Hd,{signal:y}),a.addEventListener("pointermove",this._drawMove.bind(this),{signal:y}),a.addEventListener("touchmove",x=>{Yo.isSameTimeStamp(x.timeStamp)&&$i(x)},{signal:y}),t.toggleDrawing(),(v=r._editorUndoBar)==null||v.hide(),h(rr,io)){t.drawLayer.updateProperties(this._currentDrawId,h(rr,io).startNew(l,d,p,g,f));return}r.updateUIForDefaultProperties(this),R(rr,io,this.createDrawerInstance(l,d,p,g,f)),R(rr,Ky,this.getDefaultDrawingOptions()),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(h(rr,Ky).toSVGProperties(),h(rr,io).defaultSVGProperties),!0,!1)}static _drawMove(t){if(Yo.isSameTimeStamp(t.timeStamp),!h(rr,io))return;const{offsetX:r,offsetY:i,pointerId:o}=t;if(Yo.isSamePointerId(o)){if(Yo.isUsingMultiplePointers()){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,h(rr,io).add(r,i)),Yo.setTimeStamp(t.timeStamp),$i(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,R(rr,io,null),R(rr,Ky,null),Yo.clearTimeStamp()),h(rr,Gy)&&(h(rr,Gy).abort(),R(rr,Gy,null),Yo.clearPointerIds())}static _endDraw(t){const r=this._currentParent;if(r){if(r.toggleDrawing(!0),this._cleanup(!1),(t==null?void 0:t.target)===r.div&&r.drawLayer.updateProperties(this._currentDrawId,h(rr,io).end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const i=h(rr,io),o=this._currentDrawId,a=i.getLastElement();r.addCommands({cmd:()=>{r.drawLayer.updateProperties(o,i.setLastElement(a))},undo:()=>{r.drawLayer.updateProperties(o,i.removeLastElement())},mustExec:!1,type:Wn.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const r=this._currentParent;if(!r)return null;if(r.toggleDrawing(!0),r.cleanUndoStack(Wn.DRAW_STEP),!h(rr,io).isEmpty()){const{pageDimensions:[i,o],scale:a}=r,l=r.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:h(rr,io).getOutlines(i*a,o*a,a,this._INNER_MARGIN),drawingOptions:h(rr,Ky),mustBeCommitted:!t});return this._cleanup(!0),l}return r.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,r,i,o,a,l){Hr("Not implemented")}static async deserialize(t,r,i){var f,p;const{rawDims:{pageWidth:o,pageHeight:a,pageX:l,pageY:d}}=r.viewport,c=this.deserializeDraw(l,d,o,a,this._INNER_MARGIN,t),u=await super.deserialize(t,r,i);return u.createDrawingOptions(t),q(f=u,kr,tM).call(f,{drawOutlines:c}),q(p=u,kr,FS).call(p),u.onScaleChanging(),u.rotate(),u}serializeDraw(t){const[r,i]=this.pageTranslation,[o,a]=this.pageDimensions;return h(this,ma).serialize([r,i,o,a],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}};ma=new WeakMap,Mv=new WeakMap,io=new WeakMap,Gy=new WeakMap,Ky=new WeakMap,kr=new WeakSet,tM=function({drawOutlines:t,drawId:r,drawingOptions:i}){R(this,ma,t),this._drawingOptions||(this._drawingOptions=i),this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`),r>=0?(this._drawId=r,this.parent.drawLayer.finalizeDraw(r,t.defaultProperties)):this._drawId=q(this,kr,nM).call(this,t,this.parent),q(this,kr,DS).call(this,t.box)},nM=function(t,r){const{id:i}=r.drawLayer.draw(rr._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i},rM=function(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())},FS=function(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=q(this,kr,nM).call(this,h(this,ma),t)}},hK=function([t,r,i,o]){const{parentDimensions:[a,l],rotation:d}=this;switch(d){case 90:return[r,1-t,i*(l/a),o*(a/l)];case 180:return[1-t,1-r,i,o];case 270:return[1-r,t,i*(l/a),o*(a/l)];default:return[t,r,i,o]}},aA=function(){const{x:t,y:r,width:i,height:o,parentDimensions:[a,l],rotation:d}=this;switch(d){case 90:return[1-r,t,i*(a/l),o*(l/a)];case 180:return[1-t,1-r,i,o];case 270:return[r,1-t,i*(a/l),o*(l/a)];default:return[t,r,i,o]}},DS=function(t){[this.x,this.y,this.width,this.height]=q(this,kr,hK).call(this,t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()},Dx=function(){const{x:t,y:r,width:i,height:o,rotation:a,parentRotation:l,parentDimensions:[d,c]}=this;switch((a*4+l)/90){case 1:return[1-r-o,t,o,i];case 2:return[1-t-i,1-r-o,i,o];case 3:return[r,1-t-i,o,i];case 4:return[t,r-i*(d/c),o*(c/d),i*(d/c)];case 5:return[1-r,t,i*(d/c),o*(c/d)];case 6:return[1-t-o*(c/d),1-r,o*(c/d),i*(d/c)];case 7:return[r-i*(d/c),1-t-o*(c/d),i*(d/c),o*(c/d)];case 8:return[t-i,r-o,i,o];case 9:return[1-r,t-i,o,i];case 10:return[1-t,1-r,i,o];case 11:return[r-o,1-t,o,i];case 12:return[t-o*(c/d),r,o*(c/d),i*(d/c)];case 13:return[1-r-i*(d/c),t-o*(c/d),i*(d/c),o*(c/d)];case 14:return[1-t,1-r-i*(d/c),o*(c/d),i*(d/c)];case 15:return[r,1-t,i*(d/c),o*(c/d)];default:return[t,r,i,o]}},ve(rr,"_currentDrawId",-1),ve(rr,"_currentParent",null),N(rr,io,null),N(rr,Gy,null),N(rr,Ky,null),ve(rr,"_INNER_MARGIN",3);let AT=rr;var xu,so,oo,Xy,zv,ya,Co,Sd,Yy,Qy,$y,Ov,lA;class Hhe{constructor(e,t,r,i,o,a){N(this,Ov);N(this,xu,new Float64Array(6));N(this,so);N(this,oo);N(this,Xy);N(this,zv);N(this,ya);N(this,Co,"");N(this,Sd,0);N(this,Yy,new hC);N(this,Qy);N(this,$y);R(this,Qy,r),R(this,$y,i),R(this,Xy,o),R(this,zv,a),[e,t]=q(this,Ov,lA).call(this,e,t);const l=R(this,so,[NaN,NaN,NaN,NaN,e,t]);R(this,ya,[e,t]),R(this,oo,[{line:l,points:h(this,ya)}]),h(this,xu).set(l,0)}updateProperty(e,t){e==="stroke-width"&&R(this,zv,t)}isEmpty(){return!h(this,oo)||h(this,oo).length===0}isCancellable(){return h(this,ya).length<=10}add(e,t){[e,t]=q(this,Ov,lA).call(this,e,t);const[r,i,o,a]=h(this,xu).subarray(2,6),l=e-o,d=t-a;return Math.hypot(h(this,Qy)*l,h(this,$y)*d)<=2?null:(h(this,ya).push(e,t),isNaN(r)?(h(this,xu).set([o,a,e,t],2),h(this,so).push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(h(this,xu)[0])&&h(this,so).splice(6,6),h(this,xu).set([r,i,o,a,e,t],0),h(this,so).push(...Wt.createBezierPoints(r,i,o,a,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){const r=this.add(e,t);return r||(h(this,ya).length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,r,i,o){R(this,Qy,r),R(this,$y,i),R(this,Xy,o),[e,t]=q(this,Ov,lA).call(this,e,t);const a=R(this,so,[NaN,NaN,NaN,NaN,e,t]);R(this,ya,[e,t]);const l=h(this,oo).at(-1);return l&&(l.line=new Float32Array(l.line),l.points=new Float32Array(l.points)),h(this,oo).push({line:a,points:h(this,ya)}),h(this,xu).set(a,0),R(this,Sd,0),this.toSVGPath(),null}getLastElement(){return h(this,oo).at(-1)}setLastElement(e){return h(this,oo)?(h(this,oo).push(e),R(this,so,e.line),R(this,ya,e.points),R(this,Sd,0),{path:{d:this.toSVGPath()}}):h(this,Yy).setLastElement(e)}removeLastElement(){if(!h(this,oo))return h(this,Yy).removeLastElement();h(this,oo).pop(),R(this,Co,"");for(let e=0,t=h(this,oo).length;e_??NaN),p,g,m,y),points:v(d[w].map(_=>_??NaN),p,g,m,y)});const x=new this.prototype.constructor;return x.build(f,i,o,1,c,u,a),x}get box(){return h(this,xa)}updateProperty(t,r){return t==="stroke-width"?q(this,Fo,gK).call(this,r):null}updateParentDimensions([t,r],i){const[o,a]=q(this,Fo,ph).call(this);R(this,bu,t),R(this,vu,r),R(this,Lv,i);const[l,d]=q(this,Fo,ph).call(this),c=l-o,u=d-a,f=h(this,xa);return f[0]-=c,f[1]-=u,f[2]+=2*c,f[3]+=2*u,f}updateRotation(t){return R(this,I_,t),{path:{transform:this.rotationTransform}}}get viewBox(){return h(this,xa).map(Wt.svgRound).join(" ")}get defaultProperties(){const[t,r]=h(this,xa);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`}}}get rotationTransform(){const[,,t,r]=h(this,xa);let i=0,o=0,a=0,l=0,d=0,c=0;switch(h(this,I_)){case 90:o=r/t,a=-t/r,d=t;break;case 180:i=-1,l=-1,d=t,c=r;break;case 270:o=-r/t,a=t/r,c=r;break;default:return""}return`matrix(${i} ${o} ${a} ${l} ${Wt.svgRound(d)} ${Wt.svgRound(c)})`}getPathResizingSVGProperties([t,r,i,o]){const[a,l]=q(this,Fo,ph).call(this),[d,c,u,f]=h(this,xa);if(Math.abs(u-a)<=Wt.PRECISION||Math.abs(f-l)<=Wt.PRECISION){const v=t+i/2-(d+u/2),x=r+o/2-(c+f/2);return{path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`,transform:`${this.rotationTransform} translate(${v} ${x})`}}}const p=(i-2*a)/(u-2*a),g=(o-2*l)/(f-2*l),m=u/i,y=f/o;return{path:{"transform-origin":`${Wt.svgRound(d)} ${Wt.svgRound(c)}`,transform:`${this.rotationTransform} scale(${m} ${y}) translate(${Wt.svgRound(a)} ${Wt.svgRound(l)}) scale(${p} ${g}) translate(${Wt.svgRound(-a)} ${Wt.svgRound(-l)})`}}}getPathResizedSVGProperties([t,r,i,o]){const[a,l]=q(this,Fo,ph).call(this),d=h(this,xa),[c,u,f,p]=d;if(d[0]=t,d[1]=r,d[2]=i,d[3]=o,Math.abs(f-a)<=Wt.PRECISION||Math.abs(p-l)<=Wt.PRECISION){const x=t+i/2-(c+f/2),w=r+o/2-(u+p/2);for(const{line:S,points:_}of h(this,El))Wt._translate(S,x,w,S),Wt._translate(_,x,w,_);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const g=(i-2*a)/(f-2*a),m=(o-2*l)/(p-2*l),y=-g*(c+a)+t+a,v=-m*(u+l)+r+l;if(g!==1||m!==1||y!==0||v!==0)for(const{line:x,points:w}of h(this,El))Wt._rescale(x,y,v,g,m,x),Wt._rescale(w,y,v,g,m,w);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,r],i){const[o,a]=i,l=h(this,xa),d=t-l[0],c=r-l[1];if(h(this,bu)===o&&h(this,vu)===a)for(const{line:u,points:f}of h(this,El))Wt._translate(u,d,c,u),Wt._translate(f,d,c,f);else{const u=h(this,bu)/o,f=h(this,vu)/a;R(this,bu,o),R(this,vu,a);for(const{line:p,points:g}of h(this,El))Wt._rescale(p,d,c,u,f,p),Wt._rescale(g,d,c,u,f,g);l[2]*=u,l[3]*=f}return l[0]=t,l[1]=r,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`}}}get defaultSVGProperties(){const t=h(this,xa);return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Wt.svgRound(t[0])} ${Wt.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}xa=new WeakMap,I_=new WeakMap,M_=new WeakMap,El=new WeakMap,bu=new WeakMap,vu=new WeakMap,Lv=new WeakMap,Nv=new WeakMap,Zy=new WeakMap,Fo=new WeakSet,ph=function(t=h(this,Zy)){const r=h(this,M_)+t/2*h(this,Lv);return h(this,Nv)%180===0?[r/h(this,bu),r/h(this,vu)]:[r/h(this,vu),r/h(this,bu)]},fK=function(){const[t,r,i,o]=h(this,xa),[a,l]=q(this,Fo,ph).call(this,0);return[t+a,r+l,i-2*a,o-2*l]},pK=function(){const t=R(this,xa,_m.slice());for(const{line:o}of h(this,El)){if(o.length<=12){for(let d=4,c=o.length;dl!==r[d])||t.thickness!==i||t.opacity!==o||t.pageIndex!==a},ve($x,"_type","ink"),ve($x,"_editorType",jn.INK),ve($x,"_defaultDrawingOptions",null);let iM=$x;class sM extends hC{toSVGPath(){let e=super.toSVGPath();return e.endsWith("Z")||(e+="Z"),e}}const $2=8,Gw=3;var Jy,Vr,oM,vc,yK,xK,aM,dA,bK,vK,wK,lM,dM,SK;class df{static extractContoursFromText(e,{fontFamily:t,fontStyle:r,fontWeight:i},o,a,l,d){let c=new OffscreenCanvas(1,1),u=c.getContext("2d",{alpha:!1});const f=200,p=u.font=`${r} ${i} ${f}px ${t}`,{actualBoundingBoxLeft:g,actualBoundingBoxRight:m,actualBoundingBoxAscent:y,actualBoundingBoxDescent:v,fontBoundingBoxAscent:x,fontBoundingBoxDescent:w,width:S}=u.measureText(e),_=1.5,b=Math.ceil(Math.max(Math.abs(g)+Math.abs(m)||0,S)*_),C=Math.ceil(Math.max(Math.abs(y)+Math.abs(v)||f,Math.abs(x)+Math.abs(w)||f)*_);c=new OffscreenCanvas(b,C),u=c.getContext("2d",{alpha:!0,willReadFrequently:!0}),u.font=p,u.filter="grayscale(1)",u.fillStyle="white",u.fillRect(0,0,b,C),u.fillStyle="black",u.fillText(e,b*(_-1)/2,C*(3-_)/2);const T=q(this,Vr,lM).call(this,u.getImageData(0,0,b,C).data),F=q(this,Vr,wK).call(this,T),A=q(this,Vr,dM).call(this,F),D=q(this,Vr,aM).call(this,T,b,C,A);return this.processDrawnLines({lines:{curves:D,width:b,height:C},pageWidth:o,pageHeight:a,rotation:l,innerMargin:d,mustSmooth:!0,areContours:!0})}static process(e,t,r,i,o){const[a,l,d]=q(this,Vr,SK).call(this,e),[c,u]=q(this,Vr,vK).call(this,a,l,d,Math.hypot(l,d)*h(this,Jy).sigmaSFactor,h(this,Jy).sigmaR,h(this,Jy).kernelSize),f=q(this,Vr,dM).call(this,u),p=q(this,Vr,aM).call(this,c,l,d,f);return this.processDrawnLines({lines:{curves:p,width:l,height:d},pageWidth:t,pageHeight:r,rotation:i,innerMargin:o,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:e,pageWidth:t,pageHeight:r,rotation:i,innerMargin:o,mustSmooth:a,areContours:l}){i%180!==0&&([t,r]=[r,t]);const{curves:d,width:c,height:u}=e,f=e.thickness??0,p=[],g=Math.min(t/c,r/u),m=g/t,y=g/r,v=[];for(const{points:w}of d){const S=a?q(this,Vr,bK).call(this,w):w;if(!S)continue;v.push(S);const _=S.length,b=new Float32Array(_),C=new Float32Array(3*(_===2?2:_-2));if(p.push({line:C,points:b}),_===2){b[0]=S[0]*m,b[1]=S[1]*y,C.set([NaN,NaN,NaN,NaN,b[0],b[1]],0);continue}let[T,F,A,D]=S;T*=m,F*=y,A*=m,D*=y,b.set([T,F,A,D],0),C.set([NaN,NaN,NaN,NaN,T,F],0);for(let P=4;P<_;P+=2){const L=b[P]=S[P]*m,W=b[P+1]=S[P+1]*y;C.set(Wt.createBezierPoints(T,F,A,D,L,W),(P-2)*3),[T,F,A,D]=[A,D,L,W]}}if(p.length===0)return null;const x=l?new sM:new hC;return x.build(p,t,r,1,i,l?0:f,o),{outline:x,newCurves:v,areContours:l,thickness:f,width:c,height:u}}static async compressSignature({outlines:e,areContours:t,thickness:r,width:i,height:o}){let a=1/0,l=-1/0,d=0;for(const w of e){d+=w.length;for(let S=2,_=w.length;S<_;S++){const b=w[S]-w[S-2];a=Math.min(a,b),l=Math.max(l,b)}}let c;a>=-128&&l<=127?c=Int8Array:a>=-32768&&l<=32767?c=Int16Array:c=Int32Array;const u=e.length,f=$2+Gw*u,p=new Uint32Array(f);let g=0;p[g++]=f*Uint32Array.BYTES_PER_ELEMENT+(d-2*u)*c.BYTES_PER_ELEMENT,p[g++]=0,p[g++]=i,p[g++]=o,p[g++]=t?0:1,p[g++]=Math.max(0,Math.floor(r??0)),p[g++]=u,p[g++]=c.BYTES_PER_ELEMENT;for(const w of e)p[g++]=w.length-2,p[g++]=w[0],p[g++]=w[1];const m=new CompressionStream("deflate-raw"),y=m.writable.getWriter();await y.ready,y.write(p);const v=c.prototype.constructor;for(const w of e){const S=new v(w.length-2);for(let _=2,b=w.length;_{await o.ready,await o.close()}).catch(()=>{});let a=null,l=0;for await(const S of r)a||(a=new Uint8Array(new Uint32Array(S.buffer,0,4)[0])),a.set(S,l),l+=S.length;const d=new Uint32Array(a.buffer,0,a.length>>2),c=d[1];if(c!==0)throw new Error(`Invalid version: ${c}`);const u=d[2],f=d[3],p=d[4]===0,g=d[5],m=d[6],y=d[7],v=[],x=($2+Gw*m)*Uint32Array.BYTES_PER_ELEMENT;let w;switch(y){case Int8Array.BYTES_PER_ELEMENT:w=new Int8Array(a.buffer,x);break;case Int16Array.BYTES_PER_ELEMENT:w=new Int16Array(a.buffer,x);break;case Int32Array.BYTES_PER_ELEMENT:w=new Int32Array(a.buffer,x);break}l=0;for(let S=0;S0?0:4:r===1?i+6:2-i},vc=new WeakMap,yK=function(e,t,r,i,o,a,l){const d=q(this,Vr,oM).call(this,r,i,o,a);for(let c=0;c<8;c++){const u=(-c+d-l+16)%8,f=h(this,vc)[2*u],p=h(this,vc)[2*u+1];if(e[(r+f)*t+(i+p)]!==0)return u}return-1},xK=function(e,t,r,i,o,a,l){const d=q(this,Vr,oM).call(this,r,i,o,a);for(let c=0;c<8;c++){const u=(c+d+l+16)%8,f=h(this,vc)[2*u],p=h(this,vc)[2*u+1];if(e[(r+f)*t+(i+p)]!==0)return u}return-1},aM=function(e,t,r,i){const o=e.length,a=new Int32Array(o);for(let u=0;u=1&&a[p+1]===0)l+=1,y+=1,g>1&&(d=g);else{g!==1&&(d=Math.abs(g));continue}const v=[f,u],x=y===f+1,w={isHole:x,points:v,id:l,parent:0};c.push(w);let S;for(const P of c)if(P.id===d){S=P;break}S?S.isHole?w.parent=x?S.parent:d:w.parent=x?d:S.parent:w.parent=x?d:0;const _=q(this,Vr,yK).call(this,a,t,u,f,m,y,0);if(_===-1){a[p]=-l,a[p]!==1&&(d=Math.abs(a[p]));continue}let b=h(this,vc)[2*_],C=h(this,vc)[2*_+1];const T=u+b,F=f+C;m=T,y=F;let A=u,D=f;for(;;){const P=q(this,Vr,xK).call(this,a,t,A,D,m,y,1);b=h(this,vc)[2*P],C=h(this,vc)[2*P+1];const L=A+b,W=D+C;v.push(W,L);const O=A*t+D;if(a[O+1]===0?a[O]=-l:a[O]===1&&(a[O]=l),L===u&&W===f&&A===T&&D===F){a[p]!==1&&(d=Math.abs(a[p]));break}else m=A,y=D,A=L,D=W}}}return c},dA=function(e,t,r,i){if(r-t<=4){for(let T=t;Tb&&(C=T,b=F)}b>(c*_)**2?(q(this,Vr,dA).call(this,e,t,C+2,i),q(this,Vr,dA).call(this,e,C,r,i)):i.push(o,a)},bK=function(e){const t=[],r=e.length;return q(this,Vr,dA).call(this,e,0,r,t),t.push(e[r-2],e[r-1]),t.length<=4?null:t},vK=function(e,t,r,i,o,a){const l=new Float32Array(a**2),d=-2*i**2,c=a>>1;for(let y=0;y=r))for(let F=0;F=t)continue;const D=e[T*t+A],P=l[C*a+F]*u[Math.abs(D-w)];S+=D*P,_+=P}}const b=g[x]=Math.round(S/_);m[b]++}return[g,m]},wK=function(e){const t=new Uint32Array(256);for(const r of e)t[r]++;return t},lM=function(e){const t=e.length,r=new Uint8ClampedArray(t>>2);let i=-1/0,o=1/0;for(let l=0,d=r.length;ld!==0);let a=o,l=o;for(t=o;t<256;t++){const d=e[t];d>r&&(t-a>i&&(i=t-a,l=t-1),r=d,a=t)}for(t=l-1;t>=0&&!(e[t]>e[t+1]);t--);return t},SK=function(e){const t=e,{width:r,height:i}=e,{maxDim:o}=h(this,Jy);let a=r,l=i;if(r>o||i>o){let p=r,g=i,m=Math.log2(Math.max(r,i)/o);const y=Math.floor(m);m=m===y?y-1:y;for(let x=0;x{r==null||r.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:r,thickness:i,width:o,height:a}=h(this,tg),l=Math.max(o,a),d=df.processDrawnLines({lines:{curves:t.map(c=>({points:c})),thickness:i,width:o,height:a},pageWidth:l,pageHeight:l,rotation:0,innerMargin:0,mustSmooth:!1,areContours:r});return{areContours:r,outline:d.outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,r,i,o){const{x:a,y:l}=this,{outline:d}=R(this,tg,t);R(this,eg,d instanceof sM),this.description=i;let c;h(this,eg)?c=gl.getDefaultDrawingOptions():(c=gl._defaultDrawnSignatureOptions.clone(),c.updateProperties({"stroke-width":d.thickness})),this._addOutlines({drawOutlines:d,drawingOptions:c});const[,u]=this.pageDimensions;let f=r/u;f=f>=1?.5:f,this.width*=f/this.height,this.width>=1&&(f*=.9/this.width,this.width=.9),this.height=f,this.setDims(),this.x=a,this.y=l,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(o),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!o,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:r,pageHeight:i},rotation:o}=this.parent.viewport;return df.process(t,r,i,o,gl._INNER_MARGIN)}getFromText(t,r){const{rawDims:{pageWidth:i,pageHeight:o},rotation:a}=this.parent.viewport;return df.extractContoursFromText(t,r,i,o,a,gl._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:r,pageHeight:i},rotation:o}=this.parent.viewport;return df.processDrawnLines({lines:t,pageWidth:r,pageHeight:i,rotation:o,innerMargin:gl._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:r}){t?this._drawingOptions=gl.getDefaultDrawingOptions():(this._drawingOptions=gl._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":r}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:r,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":o}}=this,a=Object.assign(super.serialize(t),{isSignature:!0,areContours:h(this,eg),color:[0,0,0],thickness:h(this,eg)?0:o});return this.addComment(a),t?(a.paths={lines:r,points:i},a.uuid=h(this,e0),a.isCopy=!0):a.lines=r,h(this,wu)&&(a.accessibilityData={type:"Figure",alt:h(this,wu)}),a}static deserializeDraw(t,r,i,o,a,l){return l.areContours?sM.deserialize(t,r,i,o,a,l):hC.deserialize(t,r,i,o,a,l)}static async deserialize(t,r,i){var a;const o=await super.deserialize(t,r,i);return R(o,eg,t.areContours),o.description=((a=t.accessibilityData)==null?void 0:a.alt)||"",R(o,e0,t.uuid),o}};eg=new WeakMap,wu=new WeakMap,tg=new WeakMap,e0=new WeakMap,ve(gl,"_type","signature"),ve(gl,"_editorType",jn.SIGNATURE),ve(gl,"_defaultDrawingOptions",null);let cM=gl;var Ri,ao,ng,rf,rg,Wv,sf,t0,Su,Pl,Uv,_r,ES,PS,cA,uA,hA,hM,fA,jK;class uM extends xi{constructor(t){super({...t,name:"stampEditor"});N(this,_r);N(this,Ri,null);N(this,ao,null);N(this,ng,null);N(this,rf,null);N(this,rg,null);N(this,Wv,"");N(this,sf,null);N(this,t0,!1);N(this,Su,null);N(this,Pl,!1);N(this,Uv,!1);R(this,rf,t.bitmapUrl),R(this,rg,t.bitmapFile),this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,r){xi.initialize(t,r)}static isHandlingMimeForPasting(t){return $B.includes(t)}static paste(t,r){r.pasteEditor({mode:jn.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var t;return{type:"stamp",hasAltText:!!((t=this.altTextData)!=null&&t.altText)}}static computeTelemetryFinalData(t){const r=t.get("hasAltText");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}async mlGuessAltText(t=null,r=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:o,width:a,height:l}=t||this.copyCanvas(null,null,!0).imageData,d=await i.guess({name:"altText",request:{data:o,width:a,height:l,channels:o.length/(a*l)}});if(!d)throw new Error("No response from the AI service.");if(d.error)throw new Error("Error from the AI service.");if(d.cancel)return null;if(!d.output)throw new Error("No valid response from the AI service.");const c=d.output;return await this.setGuessedAltText(c),r&&!this.hasAltTextData()&&(this.altTextData={alt:c,decorative:!1}),c}remove(){var t;h(this,ao)&&(R(this,Ri,null),this._uiManager.imageManager.deleteId(h(this,ao)),(t=h(this,sf))==null||t.remove(),R(this,sf,null),h(this,Su)&&(clearTimeout(h(this,Su)),R(this,Su,null))),super.remove()}rebuild(){if(!this.parent){h(this,ao)&&q(this,_r,cA).call(this);return}super.rebuild(),this.div!==null&&(h(this,ao)&&h(this,sf)===null&&q(this,_r,cA).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(h(this,ng)||h(this,Ri)||h(this,rf)||h(this,rg)||h(this,ao)||h(this,t0))}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,r;return this._isCopy&&(t=this.x,r=this.y),super.render(),this.div.hidden=!0,this.createAltText(),h(this,t0)||(h(this,Ri)?q(this,_r,uA).call(this):q(this,_r,cA).call(this)),this._isCopy&&this._moveAfterPaste(t,r),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,r){const{id:i,bitmap:o}=this._uiManager.imageManager.getFromCanvas(t,r);r.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(R(this,ao,i),o&&R(this,Ri,o),R(this,t0,!1),q(this,_r,uA).call(this))}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;h(this,Su)!==null&&clearTimeout(h(this,Su)),R(this,Su,setTimeout(()=>{R(this,Su,null),q(this,_r,hM).call(this)},200))}copyCanvas(t,r,i=!1){t||(t=224);const{width:o,height:a}=h(this,Ri),l=new Lu;let d=h(this,Ri),c=o,u=a,f=null;if(r){if(o>r||a>r){const T=Math.min(r/o,r/a);c=Math.floor(o*T),u=Math.floor(a*T)}f=document.createElement("canvas");const g=f.width=Math.ceil(c*l.sx),m=f.height=Math.ceil(u*l.sy);h(this,Pl)||(d=q(this,_r,hA).call(this,g,m));const y=f.getContext("2d");y.filter=this._uiManager.hcmFilter;let v="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":rue.isDarkMode&&(v="#8f8f9d",x="#42414d");const w=15,S=w*l.sx,_=w*l.sy,b=new OffscreenCanvas(S*2,_*2),C=b.getContext("2d");C.fillStyle=v,C.fillRect(0,0,S*2,_*2),C.fillStyle=x,C.fillRect(0,0,S,_),C.fillRect(S,_,S,_),y.fillStyle=y.createPattern(b,"repeat"),y.fillRect(0,0,g,m),y.drawImage(d,0,0,d.width,d.height,0,0,g,m)}let p=null;if(i){let g,m;if(l.symmetric&&d.widtht||a>t){const x=Math.min(t/o,t/a);g=Math.floor(o*x),m=Math.floor(a*x),h(this,Pl)||(d=q(this,_r,hA).call(this,g,m))}const v=new OffscreenCanvas(g,m).getContext("2d",{willReadFrequently:!0});v.drawImage(d,0,0,d.width,d.height,0,0,g,m),p={width:g,height:m,data:v.getImageData(0,0,g,m).data}}return{canvas:f,width:c,height:u,imageData:p}}static async deserialize(t,r,i){var v;let o=null,a=!1;if(t instanceof LG){const{data:{rect:x,rotation:w,id:S,structParent:_,popupRef:b,richText:C,contentsObj:T,creationDate:F,modificationDate:A},container:D,parent:{page:{pageNumber:P}},canvas:L}=t;let W,O;L?(delete t.canvas,{id:W,bitmap:O}=i.imageManager.getFromCanvas(D.id,L),L.remove()):(a=!0,t._hasNoCanvas=!0);const U=((v=await r._structTree.getAriaAttributes(`${Yx}${S}`))==null?void 0:v.get("aria-label"))||"";o=t={annotationType:jn.STAMP,bitmapId:W,bitmap:O,pageIndex:P-1,rect:x.slice(0),rotation:w,annotationElementId:S,id:S,deleted:!1,accessibilityData:{decorative:!1,altText:U},isSvg:!1,structParent:_,popupRef:b,richText:C,comment:(T==null?void 0:T.str)||null,creationDate:F,modificationDate:A}}const l=await super.deserialize(t,r,i),{rect:d,bitmap:c,bitmapUrl:u,bitmapId:f,isSvg:p,accessibilityData:g}=t;a?(i.addMissingCanvas(t.id,l),R(l,t0,!0)):f&&i.imageManager.isValidId(f)?(R(l,ao,f),c&&R(l,Ri,c)):R(l,rf,u),R(l,Pl,p);const[m,y]=l.pageDimensions;return l.width=(d[2]-d[0])/m,l.height=(d[3]-d[1])/y,g&&(l.altTextData=g),l._initialData=o,t.comment&&l.setCommentData(t),R(l,Uv,!!o),l}serialize(t=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:h(this,ao),isSvg:h(this,Pl)});if(this.addComment(i),t)return i.bitmapUrl=q(this,_r,fA).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:o,altText:a}=this.serializeAltText(!1);if(!o&&a&&(i.accessibilityData={type:"Figure",alt:a}),this.annotationElementId){const d=q(this,_r,jK).call(this,i);return d.isSame?null:(d.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(r===null)return i;r.stamps||(r.stamps=new Map);const l=h(this,Pl)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!r.stamps.has(h(this,ao)))r.stamps.set(h(this,ao),{area:l,serialized:i}),i.bitmap=q(this,_r,fA).call(this,!1);else if(h(this,Pl)){const d=r.stamps.get(h(this,ao));l>d.area&&(d.area=l,d.serialized.bitmap.close(),d.serialized.bitmap=q(this,_r,fA).call(this,!1))}return i}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}Ri=new WeakMap,ao=new WeakMap,ng=new WeakMap,rf=new WeakMap,rg=new WeakMap,Wv=new WeakMap,sf=new WeakMap,t0=new WeakMap,Su=new WeakMap,Pl=new WeakMap,Uv=new WeakMap,_r=new WeakSet,ES=function(t,r=!1){if(!t){this.remove();return}R(this,Ri,t.bitmap),r||(R(this,ao,t.id),R(this,Pl,t.isSvg)),t.file&&R(this,Wv,t.file.name),q(this,_r,uA).call(this)},PS=function(){if(R(this,ng,null),this._uiManager.enableWaiting(!1),!!h(this,sf)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&h(this,Ri)){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&h(this,Ri)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},cA=function(){if(h(this,ao)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(h(this,ao)).then(i=>q(this,_r,ES).call(this,i,!0)).finally(()=>q(this,_r,PS).call(this));return}if(h(this,rf)){const i=h(this,rf);R(this,rf,null),this._uiManager.enableWaiting(!0),R(this,ng,this._uiManager.imageManager.getFromUrl(i).then(o=>q(this,_r,ES).call(this,o)).finally(()=>q(this,_r,PS).call(this)));return}if(h(this,rg)){const i=h(this,rg);R(this,rg,null),this._uiManager.enableWaiting(!0),R(this,ng,this._uiManager.imageManager.getFromFile(i).then(o=>q(this,_r,ES).call(this,o)).finally(()=>q(this,_r,PS).call(this)));return}const t=document.createElement("input");t.type="file",t.accept=$B.join(",");const r=this._uiManager._signal;R(this,ng,new Promise(i=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const o=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),q(this,_r,ES).call(this,o)}i()},{signal:r}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:r})}).finally(()=>q(this,_r,PS).call(this))),t.click()},uA=function(){var c;const{div:t}=this;let{width:r,height:i}=h(this,Ri);const[o,a]=this.pageDimensions,l=.75;if(this.width)r=this.width*o,i=this.height*a;else if(r>l*o||i>l*a){const u=Math.min(l*o/r,l*a/i);r*=u,i*=u}this._uiManager.enableWaiting(!1);const d=R(this,sf,document.createElement("canvas"));d.setAttribute("role","img"),this.addContainer(d),this.width=r/o,this.height=i/a,this.setDims(),(c=this._initialOptions)!=null&&c.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),q(this,_r,hM).call(this),h(this,Uv)||(this.parent.addUndoableEditor(this),R(this,Uv,!0)),this._reportTelemetry({action:"inserted_image"}),h(this,Wv)&&this.div.setAttribute("aria-description",h(this,Wv)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")},hA=function(t,r){const{width:i,height:o}=h(this,Ri);let a=i,l=o,d=h(this,Ri);for(;a>2*t||l>2*r;){const c=a,u=l;a>2*t&&(a=Math.ceil(a/2)),l>2*r&&(l=Math.ceil(l/2));const f=new OffscreenCanvas(a,l);f.getContext("2d").drawImage(d,0,0,c,u,0,0,a,l),d=f.transferToImageBitmap()}return d},hM=function(){const[t,r]=this.parentDimensions,{width:i,height:o}=this,a=new Lu,l=Math.ceil(i*t*a.sx),d=Math.ceil(o*r*a.sy),c=h(this,sf);if(!c||c.width===l&&c.height===d)return;c.width=l,c.height=d;const u=h(this,Pl)?h(this,Ri):q(this,_r,hA).call(this,l,d),f=c.getContext("2d");f.filter=this._uiManager.hcmFilter,f.drawImage(u,0,0,u.width,u.height,0,0,l,d)},fA=function(t){if(t){if(h(this,Pl)){const o=this._uiManager.imageManager.getSvgUrl(h(this,ao));if(o)return o}const r=document.createElement("canvas");return{width:r.width,height:r.height}=h(this,Ri),r.getContext("2d").drawImage(h(this,Ri),0,0),r.toDataURL()}if(h(this,Pl)){const[r,i]=this.pageDimensions,o=Math.round(this.width*r*Wg.PDF_TO_CSS_UNITS),a=Math.round(this.height*i*Wg.PDF_TO_CSS_UNITS),l=new OffscreenCanvas(o,a);return l.getContext("2d").drawImage(h(this,Ri),0,0,h(this,Ri).width,h(this,Ri).height,0,0,o,a),l.transferToImageBitmap()}return structuredClone(h(this,Ri))},jK=function(t){var l;const{pageIndex:r,accessibilityData:{altText:i}}=this._initialData,o=t.pageIndex===r,a=(((l=t.accessibilityData)==null?void 0:l.alt)||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&o&&a,isSameAltText:a}},ve(uM,"_type","stamp"),ve(uM,"_editorType",jn.STAMP);var n0,Hv,ig,sg,of,Ka,og,qv,Vv,wc,af,lo,lf,ag,Gv,Vt,lg,fi,pM,kK,$c,gM,mM,pA;const oc=class oc{constructor({uiManager:e,pageIndex:t,div:r,structTreeLayer:i,accessibilityManager:o,annotationLayer:a,drawLayer:l,textLayer:d,viewport:c,l10n:u}){N(this,fi);N(this,n0);N(this,Hv,!1);N(this,ig,null);N(this,sg,null);N(this,of,null);N(this,Ka,new Map);N(this,og,!1);N(this,qv,!1);N(this,Vv,!1);N(this,wc,null);N(this,af,null);N(this,lo,null);N(this,lf,null);N(this,ag,null);N(this,Gv,-1);N(this,Vt);const f=[...h(oc,lg).values()];if(!oc._initialized){oc._initialized=!0;for(const p of f)p.initialize(u,e)}e.registerEditorTypes(f),R(this,Vt,e),this.pageIndex=t,this.div=r,R(this,n0,o),R(this,ig,a),this.viewport=c,R(this,lo,d),this.drawLayer=l,this._structTree=i,h(this,Vt).addLayer(this)}get isEmpty(){return h(this,Ka).size===0}get isInvisible(){return this.isEmpty&&h(this,Vt).getMode()===jn.NONE}updateToolbar(e){h(this,Vt).updateToolbar(e)}updateMode(e=h(this,Vt).getMode()){switch(q(this,fi,pA).call(this),e){case jn.NONE:this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case jn.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case jn.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:t}=this.div;if(t.toggle("nonEditing",!1),e===jn.POPUP)t.toggle("commentEditing",!0);else{t.toggle("commentEditing",!1);for(const r of h(oc,lg).values())t.toggle(`${r._type}Editing`,e===r._editorType)}this.div.hidden=!1}hasTextLayer(e){var t;return e===((t=h(this,lo))==null?void 0:t.div)}setEditingState(e){h(this,Vt).setEditingState(e)}addCommands(e){h(this,Vt).addCommands(e)}cleanUndoStack(e){h(this,Vt).cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle("drawing",!e)}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}toggleAnnotationLayerPointerEvents(e=!1){var t;(t=h(this,ig))==null||t.togglePointerEvents(e)}async enable(){var r;R(this,Vv,!0),this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),(r=h(this,ag))==null||r.abort(),R(this,ag,null);const e=new Set;for(const i of h(this,fi,pM))i.enableEditing(),i.show(!0),i.annotationElementId&&(h(this,Vt).removeChangedExistingAnnotation(i),e.add(i.annotationElementId));const t=h(this,ig);if(t)for(const i of t.getEditableAnnotations()){if(i.hide(),h(this,Vt).isDeletedAnnotationElement(i.data.id)||e.has(i.data.id))continue;const o=await this.deserialize(i);o&&(this.addOrRebuild(o),o.enableEditing())}R(this,Vv,!1),h(this,Vt)._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){var i;if(R(this,qv,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),h(this,lo)&&!h(this,ag)){R(this,ag,new AbortController);const o=h(this,Vt).combinedSignal(h(this,ag));h(this,lo).div.addEventListener("pointerdown",a=>{const{clientX:d,clientY:c,timeStamp:u}=a,f=h(this,Gv);if(u-f>500){R(this,Gv,u);return}R(this,Gv,-1);const{classList:p}=this.div;p.toggle("getElements",!0);const g=document.elementsFromPoint(d,c);if(p.toggle("getElements",!1),!this.div.contains(g[0]))return;let m;const y=new RegExp(`^${Gj}[0-9]+$`);for(const x of g)if(y.test(x.id)){m=x.id;break}if(!m)return;const v=h(this,Ka).get(m);(v==null?void 0:v.annotationElementId)===null&&($i(a),v.dblclick(a))},{signal:o,capture:!0})}const e=h(this,ig),t=[];if(e){const o=new Map,a=new Map;for(const l of h(this,fi,pM)){if(l.disableEditing(),!l.annotationElementId){t.push(l);continue}if(l.serialize()!==null){o.set(l.annotationElementId,l);continue}else a.set(l.annotationElementId,l);(i=this.getEditableAnnotation(l.annotationElementId))==null||i.show(),l.remove()}for(const l of e.getEditableAnnotations()){const{id:d}=l.data;if(h(this,Vt).isDeletedAnnotationElement(d)){l.updateEdited({deleted:!0});continue}let c=a.get(d);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=o.get(d),c&&(h(this,Vt).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}q(this,fi,pA).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const o of h(oc,lg).values())r.remove(`${o._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),e==null||e.updateFakeAnnotations(t),R(this,qv,!1)}getEditableAnnotation(e){var t;return((t=h(this,ig))==null?void 0:t.getEditableAnnotation(e))||null}setActiveEditor(e){h(this,Vt).getActive()!==e&&h(this,Vt).setActiveEditor(e)}enableTextSelection(){var e;if(this.div.tabIndex=-1,(e=h(this,lo))!=null&&e.div&&!h(this,lf)){R(this,lf,new AbortController);const t=h(this,Vt).combinedSignal(h(this,lf));h(this,lo).div.addEventListener("pointerdown",q(this,fi,kK).bind(this),{signal:t}),h(this,lo).div.classList.add("highlighting")}}disableTextSelection(){var e;this.div.tabIndex=0,(e=h(this,lo))!=null&&e.div&&h(this,lf)&&(h(this,lf).abort(),R(this,lf,null),h(this,lo).div.classList.remove("highlighting"))}enableClick(){if(h(this,sg))return;R(this,sg,new AbortController);const e=h(this,Vt).combinedSignal(h(this,sg));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:e});const t=this.pointerup.bind(this);this.div.addEventListener("pointerup",t,{signal:e}),this.div.addEventListener("pointercancel",t,{signal:e})}disableClick(){var e;(e=h(this,sg))==null||e.abort(),R(this,sg,null)}attach(e){h(this,Ka).set(e.id,e);const{annotationElementId:t}=e;t&&h(this,Vt).isDeletedAnnotationElement(t)&&h(this,Vt).removeDeletedAnnotationElement(e)}detach(e){var t;h(this,Ka).delete(e.id),(t=h(this,n0))==null||t.removePointerInTextLayer(e.contentDiv),!h(this,qv)&&e.annotationElementId&&h(this,Vt).addDeletedAnnotationElement(e)}remove(e){this.detach(e),h(this,Vt).removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){var t;e.parent!==this&&(e.parent&&e.annotationElementId&&(h(this,Vt).addDeletedAnnotationElement(e),xi.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),(t=e.parent)==null||t.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),h(this,Vt).addEditor(e),this.attach(e),!e.isAttachedToDOM){const t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!h(this,Vv)),h(this,Vt).addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){var r;if(!e.isAttachedToDOM)return;const{activeElement:t}=document;e.div.contains(t)&&!h(this,of)&&(e._focusEventsAllowed=!1,R(this,of,setTimeout(()=>{R(this,of,null),e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:h(this,Vt)._signal}),t.focus())},0))),e._structTreeParentId=(r=h(this,n0))==null?void 0:r.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||(e.parent=this),e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){const t=()=>e._uiManager.rebuild(e),r=()=>{e.remove()};this.addCommands({cmd:t,undo:r,mustExec:!1})}getEditorByUID(e){for(const t of h(this,Ka).values())if(t.uid===e)return t;return null}combinedSignal(e){return h(this,Vt).combinedSignal(e)}canCreateNewEmptyEditor(){var e;return(e=h(this,fi,$c))==null?void 0:e.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await h(this,Vt).updateMode(e.mode);const{offsetX:r,offsetY:i}=q(this,fi,mM).call(this),o=h(this,Vt).getId(),a=q(this,fi,gM).call(this,{parent:this,id:o,x:r,y:i,uiManager:h(this,Vt),isCentered:!0,...t});a&&this.add(a)}async deserialize(e){var t;return await((t=h(oc,lg).get(e.annotationType??e.annotationEditorType))==null?void 0:t.deserialize(e,this,h(this,Vt)))||null}createAndAddNewEditor(e,t,r={}){const i=h(this,Vt).getId(),o=q(this,fi,gM).call(this,{parent:this,id:i,x:e.offsetX,y:e.offsetY,uiManager:h(this,Vt),isCentered:t,...r});return o&&this.add(o),o}get boundingClientRect(){return this.div.getBoundingClientRect()}addNewEditor(e={}){this.createAndAddNewEditor(q(this,fi,mM).call(this),!0,e)}setSelected(e){h(this,Vt).setSelected(e)}toggleSelected(e){h(this,Vt).toggleSelected(e)}unselect(e){h(this,Vt).unselect(e)}pointerup(e){var i;const{isMac:t}=Ds.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div||!h(this,og)||(R(this,og,!1),(i=h(this,fi,$c))!=null&&i.isDrawer&&h(this,fi,$c).supportMultipleDrawings))return;if(!h(this,Hv)){R(this,Hv,!0);return}const r=h(this,Vt).getMode();if(r===jn.STAMP||r===jn.POPUP||r===jn.SIGNATURE){h(this,Vt).unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){var i;if(h(this,Vt).getMode()===jn.HIGHLIGHT&&this.enableTextSelection(),h(this,og)){R(this,og,!1);return}const{isMac:t}=Ds.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(R(this,og,!0),(i=h(this,fi,$c))!=null&&i.isDrawer){this.startDrawingSession(e);return}const r=h(this,Vt).getActive();R(this,Hv,!r||r.isEmpty())}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),h(this,wc)){h(this,fi,$c).startDrawing(this,h(this,Vt),!1,e);return}h(this,Vt).setCurrentDrawingSession(this),R(this,wc,new AbortController);const t=h(this,Vt).combinedSignal(h(this,wc));this.div.addEventListener("blur",({relatedTarget:r})=>{r&&!this.div.contains(r)&&(R(this,af,null),this.commitOrRemove())},{signal:t}),h(this,fi,$c).startDrawing(this,h(this,Vt),!1,e)}pause(e){if(e){const{activeElement:t}=document;this.div.contains(t)&&R(this,af,t);return}h(this,af)&&setTimeout(()=>{var t;(t=h(this,af))==null||t.focus(),R(this,af,null)},0)}endDrawingSession(e=!1){return h(this,wc)?(h(this,Vt).setCurrentDrawingSession(null),h(this,wc).abort(),R(this,wc,null),R(this,af,null),h(this,fi,$c).endDrawing(e)):null}findNewParent(e,t,r){const i=h(this,Vt).findParent(t,r);return i===null||i===this?!1:(i.changeParent(e),!0)}commitOrRemove(){return h(this,wc)?(this.endDrawingSession(),!0):!1}onScaleChanging(){h(this,wc)&&h(this,fi,$c).onScaleChangingWhenDrawing(this)}destroy(){var e,t;this.commitOrRemove(),((e=h(this,Vt).getActive())==null?void 0:e.parent)===this&&(h(this,Vt).commitOrRemove(),h(this,Vt).setActiveEditor(null)),h(this,of)&&(clearTimeout(h(this,of)),R(this,of,null));for(const r of h(this,Ka).values())(t=h(this,n0))==null||t.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,h(this,Ka).clear(),h(this,Vt).removeLayer(this)}async render({viewport:e}){this.viewport=e,k0(this.div,e);for(const t of h(this,Vt).getEditors(this.pageIndex))this.add(t),t.rebuild();await h(this,Vt).findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){h(this,Vt).commitOrRemove(),q(this,fi,pA).call(this);const t=this.viewport.rotation,r=e.rotation;if(this.viewport=e,k0(this.div,{rotation:r}),t!==r)for(const i of h(this,Ka).values())i.rotate(r)}get pageDimensions(){const{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return h(this,Vt).viewParameters.realScale}};n0=new WeakMap,Hv=new WeakMap,ig=new WeakMap,sg=new WeakMap,of=new WeakMap,Ka=new WeakMap,og=new WeakMap,qv=new WeakMap,Vv=new WeakMap,wc=new WeakMap,af=new WeakMap,lo=new WeakMap,lf=new WeakMap,ag=new WeakMap,Gv=new WeakMap,Vt=new WeakMap,lg=new WeakMap,fi=new WeakSet,pM=function(){return h(this,Ka).size!==0?h(this,Ka).values():h(this,Vt).getEditors(this.pageIndex)},kK=function(e){h(this,Vt).unselectAll();const{target:t}=e;if(t===h(this,lo).div||(t.getAttribute("role")==="img"||t.classList.contains("endOfContent")||t.classList.contains("textLayerImagePlaceholder"))&&h(this,lo).div.contains(t)){const{isMac:r}=Ds.platform;if(e.button!==0||e.ctrlKey&&r)return;h(this,Vt).showAllEditors("highlight",!0,!0),h(this,lo).div.classList.add("free"),this.toggleDrawing(),CT.startHighlighting(this,h(this,Vt).direction==="ltr",{target:h(this,lo).div,x:e.x,y:e.y}),h(this,lo).div.addEventListener("pointerup",()=>{h(this,lo).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:h(this,Vt)._signal}),e.preventDefault()}},$c=function(){return h(oc,lg).get(h(this,Vt).getMode())},gM=function(e){const t=h(this,fi,$c);return t?new t.prototype.constructor(e):null},mM=function(){const{x:e,y:t,width:r,height:i}=this.boundingClientRect,o=Math.max(0,e),a=Math.max(0,t),l=Math.min(window.innerWidth,e+r),d=Math.min(window.innerHeight,t+i),c=(o+l)/2-e,u=(a+d)/2-t,[f,p]=this.viewport.rotation%180===0?[c,u]:[u,c];return{offsetX:f,offsetY:p}},pA=function(){for(const e of h(this,Ka).values())e.isEmpty()&&e.remove()},ve(oc,"_initialized",!1),N(oc,lg,new Map([XI,iM,uM,CT,cM].map(e=>[e._editorType,e])));let fM=oc;var Sc,ba,r0,z_,JT,_K,Wu,xM,CK,bM;const Bs=class Bs{constructor(){N(this,Wu);N(this,Sc,null);N(this,ba,new Map);N(this,r0,new Map)}setParent(e){if(!h(this,Sc)){R(this,Sc,e);return}if(h(this,Sc)!==e){if(h(this,ba).size>0)for(const t of h(this,ba).values())t.remove(),e.append(t);R(this,Sc,e)}}static get _svgFactory(){return Cn(this,"_svgFactory",new kT)}draw(e,t=!1,r=!1){const i=Gi(Bs,z_)._++,o=q(this,Wu,xM).call(this),a=Bs._svgFactory.createElement("defs");o.append(a);const l=Bs._svgFactory.createElement("path");a.append(l);const d=`path_${i}`;l.setAttribute("id",d),l.setAttribute("vector-effect","non-scaling-stroke"),t&&h(this,r0).set(i,l);const c=r?q(this,Wu,CK).call(this,a,d):null,u=Bs._svgFactory.createElement("use");return o.append(u),u.setAttribute("href",`#${d}`),this.updateProperties(o,e),h(this,ba).set(i,o),{id:i,clipPathId:`url(#${c})`}}drawOutline(e,t){const r=Gi(Bs,z_)._++,i=q(this,Wu,xM).call(this),o=Bs._svgFactory.createElement("defs");i.append(o);const a=Bs._svgFactory.createElement("path");o.append(a);const l=`path_${r}`;a.setAttribute("id",l),a.setAttribute("vector-effect","non-scaling-stroke");let d;if(t){const f=Bs._svgFactory.createElement("mask");o.append(f),d=`mask_${r}`,f.setAttribute("id",d),f.setAttribute("maskUnits","objectBoundingBox");const p=Bs._svgFactory.createElement("rect");f.append(p),p.setAttribute("width","1"),p.setAttribute("height","1"),p.setAttribute("fill","white");const g=Bs._svgFactory.createElement("use");f.append(g),g.setAttribute("href",`#${l}`),g.setAttribute("stroke","none"),g.setAttribute("fill","black"),g.setAttribute("fill-rule","nonzero"),g.classList.add("mask")}const c=Bs._svgFactory.createElement("use");i.append(c),c.setAttribute("href",`#${l}`),d&&c.setAttribute("mask",`url(#${d})`);const u=c.cloneNode();return i.append(u),c.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.updateProperties(i,e),h(this,ba).set(r,i),r}finalizeDraw(e,t){h(this,r0).delete(e),this.updateProperties(e,t)}updateProperties(e,t){var d;if(!t)return;const{root:r,bbox:i,rootClass:o,path:a}=t,l=typeof e=="number"?h(this,ba).get(e):e;if(l){if(r&&q(this,Wu,bM).call(this,l,r),i&&q(d=Bs,JT,_K).call(d,l,i),o){const{classList:c}=l;for(const[u,f]of Object.entries(o))c.toggle(u,f)}if(a){const u=l.firstElementChild.firstElementChild;q(this,Wu,bM).call(this,u,a)}}}updateParent(e,t){if(t===this)return;const r=h(this,ba).get(e);r&&(h(t,Sc).append(r),h(this,ba).delete(e),h(t,ba).set(e,r))}remove(e){h(this,r0).delete(e),h(this,Sc)!==null&&(h(this,ba).get(e).remove(),h(this,ba).delete(e))}destroy(){R(this,Sc,null);for(const e of h(this,ba).values())e.remove();h(this,ba).clear(),h(this,r0).clear()}};Sc=new WeakMap,ba=new WeakMap,r0=new WeakMap,z_=new WeakMap,JT=new WeakSet,_K=function(e,[t,r,i,o]){const{style:a}=e;a.top=`${100*r}%`,a.left=`${100*t}%`,a.width=`${100*i}%`,a.height=`${100*o}%`},Wu=new WeakSet,xM=function(){const e=Bs._svgFactory.create(1,1,!0);return h(this,Sc).append(e),e.setAttribute("aria-hidden",!0),e},CK=function(e,t){const r=Bs._svgFactory.createElement("clipPath");e.append(r);const i=`clip_${t}`;r.setAttribute("id",i),r.setAttribute("clipPathUnits","objectBoundingBox");const o=Bs._svgFactory.createElement("use");return r.append(o),o.setAttribute("href",`#${t}`),o.classList.add("clip"),i},bM=function(e,t){for(const[r,i]of Object.entries(t))i===null?e.removeAttribute(r):e.setAttribute(r,i)},N(Bs,JT),N(Bs,z_,0);let yM=Bs;function Z2(n){return`${(n*100).toFixed(2)}%`}var Kv,O_,L_,Xv,ju,ku,N_,eF,AK;const oj=class oj{constructor(e,t,r,i){N(this,eF);N(this,Kv,[]);N(this,O_,new Map);N(this,L_,null);N(this,Xv,0);N(this,ju,0);N(this,ku,0);R(this,Xv,e),R(this,Kv,t),R(this,ju,r.rawDims.pageWidth),R(this,ku,r.rawDims.pageHeight),R(this,L_,i)}render(){const e=document.createElement("div");e.className="textLayerImages";for(let t=0;t{var x;if(!(t.target instanceof HTMLCanvasElement))return;const r=t.target,i=h(this,O_).get(r);if(!i)return;const o=(x=h(oj,N_))==null?void 0:x.deref();if(o===r)return;o&&(o.width=0,o.height=0),R(oj,N_,new WeakRef(r));const{inverseTransform:a,x1:l,y1:d,width:c,height:u}=i,f=h(this,L_).call(this),p=Math.ceil(l*f.width),g=Math.ceil(d*f.height),m=Math.floor((l+c/h(this,ju))*f.width),y=Math.floor((d+u/h(this,ku))*f.height);r.width=m-p,r.height=y-g;const v=r.getContext("2d");v.setTransform(...a),v.translate(-p,-g),v.drawImage(f,0,0)}),e}};Kv=new WeakMap,O_=new WeakMap,L_=new WeakMap,Xv=new WeakMap,ju=new WeakMap,ku=new WeakMap,N_=new WeakMap,eF=new WeakSet,AK=function([e,t,r,i,o,a]){const l=Math.hypot((o-e)*h(this,ju),(a-t)*h(this,ku)),d=Math.hypot((r-e)*h(this,ju),(i-t)*h(this,ku));if(l{const i=setTimeout(()=>{r(n)},e);return()=>{clearTimeout(i)}},[n,e]),t}function wM(){const n=new Date,e=new Date(n);return e.setDate(e.getDate()-90),{from:e.toISOString().split("T")[0],to:n.toISOString().split("T")[0]}}function Cm(n){if(!n)return"-";try{return new Date(n).toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return n}}function Td(n){if(n==null)return"-";const e=typeof n=="string"?parseFloat(n):n;return isNaN(e)?"-":`£${e.toFixed(2)}`}function qhe(n){if(n==null)return"-";const e=typeof n=="string"?parseFloat(n):n;return isNaN(e)?"-":`${e>=0?"+":""}${e.toFixed(1)}%`}function Ex(n,e=1){if(n==null)return"-";const t=typeof n=="string"?parseFloat(n):n;return isNaN(t)?"-":t.toFixed(e)}function Vhe(n,e){try{const t=sessionStorage.getItem(n);return t===null?e:JSON.parse(t)}catch{return e}}function Ghe(n,e){try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}}function co(n,e){const[t,r]=k.useState(()=>Vhe(n,e));return k.useEffect(()=>{Ghe(n,t)},[n,t]),[t,r]}const qP={consistent:{icon:"✓",color:"#22c55e",label:"Price consistent"},amber:{icon:"?",color:"#f59e0b",label:"Small price change"},red:{icon:"!",color:"#ef4444",label:"Large price change"},acknowledged:{icon:"✓",color:"#22c55e",label:"Price acknowledged"},no_history:{icon:null,color:"#9ca3af",label:"No price history"}};function Khe(n){return n&&qP[n]||qP.no_history}function FK({isOpen:n,onClose:e,productCode:t,description:r,unit:i,supplierId:o,supplierName:a,currentPrice:l,sourceInvoiceId:d,sourceLineItemId:c,onAcknowledge:u}){const{token:f}=gn(),p=pi(),g=k.useMemo(()=>{const D=new Date,P=new Date(D);return P.setFullYear(P.getFullYear()-1),{from:P.toISOString().split("T")[0],to:D.toISOString().split("T")[0]}},[]),[m,y]=k.useState(g.from),[v,x]=k.useState(g.to),{data:w,isLoading:S,error:_}=Oe({queryKey:["line-item-history",o,t,r,i,m,v],queryFn:async()=>{const D=new URLSearchParams;D.set("supplier_id",o.toString()),t&&D.set("product_code",t),r&&D.set("description",r),i&&D.set("unit",i),m&&D.set("date_from",m),v&&D.set("date_to",v);const P=await fetch(`/api/search/line-items/history?${D}`,{headers:{Authorization:`Bearer ${f}`}});if(!P.ok)throw new Error("Failed to fetch history");return P.json()},enabled:n&&!!f}),b=Ue({mutationFn:async()=>{const D=await fetch("/api/search/line-items/acknowledge-price",{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"},body:JSON.stringify({product_code:t,description:r,supplier_id:o,new_price:l||(w==null?void 0:w.current_price),source_invoice_id:d,source_line_item_id:c})});if(!D.ok)throw new Error("Failed to acknowledge price");return D.json()},onSuccess:()=>{p.invalidateQueries({queryKey:["line-item-history"]}),p.invalidateQueries({queryKey:["search-line-items"]}),u&&u()}}),C=k.useMemo(()=>{if(!(w!=null&&w.price_history.length))return{min:0,max:100};const D=w.price_history.map(te=>typeof te.price=="string"?parseFloat(te.price):te.price),P=Math.min(...D),L=Math.max(...D),W=L-P,U=(P+L)/2*.2||1,M=Math.max(W,U),I=(P+L)/2,H=I-M/2,z=I+M/2,G=M*.1;return{min:Math.max(0,H-G),max:z+G}},[w]);if(!n)return null;const T=D=>{const P=C.max-C.min;return P===0?50:(D-C.min)/P*100},F=l??(w==null?void 0:w.current_price),A=(w==null?void 0:w.price_change_status)==="amber"||(w==null?void 0:w.price_change_status)==="red";return s.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:e,children:s.jsxs("div",{style:{backgroundColor:"white",borderRadius:"12px",width:"90%",maxWidth:"800px",maxHeight:"90vh",overflow:"auto",padding:"24px"},onClick:D=>D.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"20px"},children:[s.jsxs("div",{children:[s.jsxs("h2",{style:{margin:0,fontSize:"18px"},children:["Price History: ",r||t||"Unknown",t&&r&&s.jsxs("span",{style:{color:"#6b7280",fontWeight:"normal"},children:[" (",t,")"]})]}),s.jsxs("p",{style:{margin:"4px 0 0",color:"#6b7280"},children:["Supplier: ",a]})]}),s.jsx("button",{onClick:e,style:{padding:"4px 12px",border:"none",backgroundColor:"#f1f5f9",borderRadius:"4px",cursor:"pointer",fontSize:"16px"},children:"✕"})]}),s.jsxs("div",{style:{display:"flex",gap:"12px",alignItems:"center",marginBottom:"20px",padding:"12px",backgroundColor:"#f8fafc",borderRadius:"8px"},children:[s.jsx("label",{style:{fontSize:"14px"},children:"Date Range:"}),s.jsx("input",{type:"date",value:m,onChange:D=>y(D.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}}),s.jsx("span",{children:"to"}),s.jsx("input",{type:"date",value:v,onChange:D=>x(D.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}})]}),S&&s.jsx("p",{children:"Loading..."}),_&&s.jsxs("p",{style:{color:"red"},children:["Error: ",_.message]}),w&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{marginBottom:"24px",padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px"},children:[s.jsx("h3",{style:{margin:"0 0 16px",fontSize:"14px",fontWeight:600},children:"Price History"}),w.price_history.length===0?s.jsx("p",{style:{color:"#6b7280",textAlign:"center"},children:"No price history available for this period"}):s.jsxs("div",{children:[s.jsxs("div",{style:{height:"150px",display:"flex",alignItems:"flex-end",gap:"2px",padding:"0 0 20px",borderBottom:"1px solid #e5e7eb",position:"relative"},children:[s.jsxs("div",{style:{position:"absolute",left:0,top:0,bottom:20,width:"50px",display:"flex",flexDirection:"column",justifyContent:"space-between",fontSize:"10px",color:"#9ca3af"},children:[s.jsx("span",{children:Td(C.max)}),s.jsx("span",{children:Td(C.min)})]}),s.jsx("div",{style:{flex:1,marginLeft:"55px",display:"flex",alignItems:"flex-end",gap:"2px",height:"100%"},children:w.price_history.map((D,P)=>s.jsx("div",{style:{flex:1,maxWidth:"40px",height:`${T(D.price)}%`,backgroundColor:"#3b82f6",borderRadius:"2px 2px 0 0",cursor:"pointer",position:"relative"},title:`${Cm(D.date)}: ${Td(D.price)} (${D.invoice_number||"Invoice"})`},P))})]}),s.jsx("div",{style:{marginLeft:"55px",display:"flex",justifyContent:"space-between",fontSize:"10px",color:"#9ca3af",marginTop:"4px"},children:w.price_history.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Cm(w.price_history[0].date)}),s.jsx("span",{children:Cm(w.price_history[w.price_history.length-1].date)})]})}),s.jsx("div",{style:{marginTop:"16px",maxHeight:"150px",overflowY:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"13px"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f8fafc"},children:[s.jsx("th",{style:{padding:"8px",textAlign:"left",width:"90px"},children:"Date"}),s.jsx("th",{style:{padding:"8px",textAlign:"left",minWidth:"200px"},children:"Description"}),s.jsx("th",{style:{padding:"8px",textAlign:"left",width:"80px"},children:"Unit"}),s.jsx("th",{style:{padding:"8px",textAlign:"right",width:"80px"},children:"Qty"}),s.jsx("th",{style:{padding:"8px",textAlign:"right",width:"80px"},children:"Price"})]})}),s.jsx("tbody",{children:w.price_history.slice().reverse().map((D,P)=>s.jsxs("tr",{style:{borderBottom:"1px solid #f1f5f9"},children:[s.jsx("td",{style:{padding:"8px",whiteSpace:"nowrap"},children:Cm(D.date)}),s.jsx("td",{style:{padding:"8px",maxWidth:"300px"},children:s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w.description||"-"}),s.jsxs("a",{href:`/invoice/${D.invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none",whiteSpace:"nowrap",flexShrink:0,fontSize:"12px"},children:[D.invoice_number||"View"," ↗"]})]})}),s.jsx("td",{style:{padding:"8px"},children:i||"-"}),s.jsx("td",{style:{padding:"8px",textAlign:"right"},children:Ex(D.quantity)}),s.jsx("td",{style:{padding:"8px",textAlign:"right"},children:Td(D.price)})]},P))})]})})]})]}),s.jsxs("div",{style:{marginBottom:"24px",padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px"},children:[s.jsx("h3",{style:{margin:"0 0 12px",fontSize:"14px",fontWeight:600},children:"Stats for Period"}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"12px"},children:[s.jsx(Kw,{label:"Total Occurrences",value:String(w.total_occurrences)}),s.jsx(Kw,{label:"Total Quantity",value:Ex(w.total_quantity)}),s.jsx(Kw,{label:"Avg Qty per Invoice",value:Ex(w.avg_qty_per_invoice,2)}),s.jsx(Kw,{label:"Avg Qty per Week",value:Ex(w.avg_qty_per_week,2)}),s.jsx(Kw,{label:"Avg Qty per Month",value:Ex(w.avg_qty_per_month,2)})]})]}),F&&s.jsxs("div",{style:{padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px",backgroundColor:w.price_change_status==="red"?"#fef2f2":w.price_change_status==="amber"?"#fffbeb":"#f0fdf4"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{children:[s.jsx("span",{style:{fontWeight:600},children:"Current Price: "}),s.jsx("span",{style:{fontSize:"18px"},children:Td(F)}),w.price_history.length>1&&s.jsx("span",{style:{marginLeft:"8px",color:w.price_change_status==="red"?"#dc2626":w.price_change_status==="amber"?"#d97706":"#16a34a"},children:(()=>{var L;const D=(L=w.price_history[w.price_history.length-2])==null?void 0:L.price;if(!D)return"";const P=(F-D)/D*100;return`(${qhe(P)} from previous ${Td(D)})`})()})]}),A&&s.jsx("button",{onClick:()=>b.mutate(),disabled:b.isPending,style:{padding:"8px 16px",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",cursor:b.isPending?"not-allowed":"pointer",opacity:b.isPending?.7:1},children:b.isPending?"Acknowledging...":"Acknowledge Price Change"})]}),b.isSuccess&&s.jsx("p",{style:{marginTop:"8px",color:"#16a34a",fontSize:"14px"},children:"✓ Price change acknowledged"})]})]})]})})}function Kw({label:n,value:e}){return s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"12px",color:"#6b7280"},children:n}),s.jsx("div",{style:{fontSize:"16px",fontWeight:600},children:e})]})}function Xhe({invoiceId:n,invoiceNumber:e,supplierId:t,supplierName:r,lineItems:i=[],onClose:o,onSuccess:a}){var W;const{token:l}=gn(),d=pi(),[c,u]=k.useState("price_discrepancy"),[f,p]=k.useState("medium"),[g,m]=k.useState(""),[y,v]=k.useState(""),[x,w]=k.useState(""),[S,_]=k.useState(""),[b,C]=k.useState(new Set),[T,F]=k.useState(""),A=Ue({mutationFn:async O=>{const U=await fetch("/api/disputes",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(O)});if(!U.ok){const M=await U.json();throw new Error(M.detail||"Failed to create dispute")}return U.json()},onSuccess:()=>{d.invalidateQueries({queryKey:["disputes"]}),d.invalidateQueries({queryKey:["dispute-stats"]}),d.invalidateQueries({queryKey:["invoice",n]}),a&&a(),o()}}),D=O=>{if(O.preventDefault(),!g.trim()){alert("Please enter a dispute title");return}if(!x){alert("Please enter a disputed amount");return}const U={invoice_id:n,dispute_type:c,priority:f,title:g.trim(),disputed_amount:parseFloat(x)};y.trim()&&(U.description=y.trim()),S&&(U.expected_amount=parseFloat(S)),b.size>0&&(U.line_items=Array.from(b).map(M=>{const I=i.find(z=>z.id===M);return I?{invoice_line_item_id:I.id,product_name:I.description||I.product_code||"Unnamed item",product_code:I.product_code||void 0,quantity_ordered:I.quantity||void 0,unit_price_charged:I.unit_price||void 0,total_charged:I.amount||0}:null}).filter(M=>M!==null)),A.mutate(U)},P=O=>{const U=new Set(b);U.has(O)?U.delete(O):U.add(O),C(U);const I=i.filter(H=>U.has(H.id)).reduce((H,z)=>H+(z.amount||0),0);I>0?w(I.toFixed(2)):U.size===0&&w("")},L=i.filter(O=>{if(!T)return!0;const U=T.toLowerCase(),M=(O.description||"").toLowerCase(),I=(O.product_code||"").toLowerCase();return M.includes(U)||I.includes(U)});return s.jsx("div",{style:bn.modalOverlay,onClick:o,children:s.jsxs("div",{style:bn.modal,onClick:O=>O.stopPropagation(),children:[s.jsxs("div",{style:bn.modalHeader,children:[s.jsx("h2",{style:bn.modalTitle,children:"Create Dispute"}),s.jsx("button",{style:bn.closeBtn,onClick:o,type:"button",children:"✕"})]}),s.jsxs("form",{onSubmit:D,style:bn.form,children:[s.jsx("div",{style:bn.formRow,children:s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Invoice"}),s.jsxs("div",{style:bn.staticValue,children:["#",e||n,r&&s.jsxs("span",{style:bn.supplier,children:[" - ",r]})]})]})}),s.jsxs("div",{style:bn.formRow,children:[s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Dispute Type *"}),s.jsxs("select",{value:c,onChange:O=>u(O.target.value),style:bn.select,required:!0,children:[s.jsx("option",{value:"price_discrepancy",children:"Price Discrepancy"}),s.jsx("option",{value:"short_delivery",children:"Short Delivery"}),s.jsx("option",{value:"wrong_product",children:"Wrong Product"}),s.jsx("option",{value:"quality_issue",children:"Quality Issue"}),s.jsx("option",{value:"calculation_error",children:"Calculation Error"}),s.jsx("option",{value:"missing_items",children:"Missing Items"}),s.jsx("option",{value:"damaged_goods",children:"Damaged Goods"}),s.jsx("option",{value:"other",children:"Other"})]})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Priority *"}),s.jsxs("select",{value:f,onChange:O=>p(O.target.value),style:bn.select,required:!0,children:[s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"urgent",children:"Urgent"})]})]})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Title *"}),s.jsx("input",{type:"text",value:g,onChange:O=>m(O.target.value),style:bn.input,placeholder:"Brief summary of the issue",required:!0,maxLength:200})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Description"}),s.jsx("textarea",{value:y,onChange:O=>v(O.target.value),style:bn.textarea,placeholder:"Detailed description of the dispute (optional)...",rows:4})]}),s.jsxs("div",{style:bn.formRow,children:[s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Disputed Amount (£) *"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:x,onChange:O=>w(O.target.value),style:bn.input,placeholder:"0.00",required:!0}),s.jsx("div",{style:bn.fieldHint,children:"Auto-fills when you select line items"})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Expected Amount (£)"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:S,onChange:O=>_(O.target.value),style:bn.input,placeholder:"0.00"})]})]}),i.length>0&&s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Disputed Line Items (optional)"}),s.jsx("input",{type:"text",value:T,onChange:O=>F(O.target.value),style:bn.input,placeholder:"Search line items by description or code..."}),s.jsx("div",{style:bn.lineItemsContainer,children:L.length===0?s.jsx("div",{style:bn.noResults,children:"No items match your search"}):L.map(O=>s.jsxs("label",{style:bn.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:b.has(O.id),onChange:()=>P(O.id),style:bn.checkbox}),s.jsxs("span",{style:bn.lineItemText,children:[O.description||O.product_code||"Unnamed item",O.amount!=null&&s.jsxs("span",{style:bn.lineItemAmount,children:[" - £",Number(O.amount).toFixed(2)]})]})]},O.id))}),b.size>0&&s.jsxs("div",{style:bn.selectedSummary,children:[b.size," item(s) selected"]})]}),s.jsxs("div",{style:bn.footer,children:[s.jsx("button",{type:"button",onClick:o,style:bn.cancelBtn,disabled:A.isPending,children:"Cancel"}),s.jsx("button",{type:"submit",style:bn.submitBtn,disabled:A.isPending,children:A.isPending?"Creating...":"Create Dispute"})]}),A.isError&&s.jsxs("div",{style:bn.error,children:["Error: ",((W=A.error)==null?void 0:W.message)||"Failed to create dispute"]})]})]})})}const bn={modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3,padding:"1rem"},modal:{background:"white",borderRadius:"12px",maxWidth:"700px",width:"100%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},modalTitle:{margin:0,color:"#1a1a2e"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},form:{padding:"1.5rem",flex:1,overflow:"auto"},formRow:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1rem",marginBottom:"1rem"},formGroup:{marginBottom:"1rem"},label:{display:"block",marginBottom:"0.5rem",fontWeight:"bold",color:"#1a1a2e",fontSize:"0.9rem"},staticValue:{padding:"0.75rem",background:"#f5f5f5",borderRadius:"8px",color:"#666"},supplier:{color:"#999",fontSize:"0.9rem"},input:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box"},select:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box"},textarea:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit"},lineItemsContainer:{maxHeight:"200px",overflow:"auto",border:"1px solid #eee",borderRadius:"8px",padding:"0.5rem",marginTop:"0.5rem"},checkboxLabel:{display:"flex",alignItems:"center",padding:"0.5rem",cursor:"pointer",borderRadius:"4px"},checkbox:{marginRight:"0.75rem",cursor:"pointer"},lineItemText:{fontSize:"0.9rem",color:"#333"},lineItemAmount:{color:"#666",fontWeight:"bold"},footer:{display:"flex",justifyContent:"flex-end",gap:"1rem",marginTop:"1.5rem",paddingTop:"1rem",borderTop:"1px solid #eee"},cancelBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",color:"#666",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},submitBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"none",background:"#e94560",color:"white",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},error:{marginTop:"1rem",padding:"0.75rem",background:"#fee",color:"#c00",borderRadius:"8px",fontSize:"0.9rem"},noResults:{padding:"1rem",textAlign:"center",color:"#999",fontStyle:"italic"},selectedSummary:{marginTop:"0.5rem",padding:"0.5rem",background:"#e8f4f8",borderRadius:"4px",fontSize:"0.85rem",color:"#1565c0",fontWeight:"bold"},fieldHint:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem",fontStyle:"italic"}},Yhe=[{value:"new",label:"New"},{value:"contacted",label:"Contacted"},{value:"awaiting_credit",label:"Awaiting Credit"},{value:"awaiting_replacement",label:"Awaiting Replacement"},{value:"resolved",label:"Resolved"}],Qhe=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}],$he={new:"#e94560",contacted:"#f0ad4e",awaiting_credit:"#9b59b6",awaiting_replacement:"#8b7ec8",resolved:"#5cb85c"},Zhe={low:"#5cb85c",medium:"#5bc0de",high:"#f0ad4e",urgent:"#e94560"};function DK({disputeId:n,onClose:e,onUpdate:t}){var ee;const{token:r,user:i}=gn(),o=pi(),[a,l]=k.useState(""),[d,c]=k.useState(!1),[u,f]=k.useState(!1),[p,g]=k.useState(""),[m,y]=k.useState(""),[v,x]=k.useState(null),[w,S]=k.useState(""),[_,b]=k.useState(!1),[C,T]=k.useState(null),[F,A]=k.useState(!1),[D,P]=k.useState(""),[L,W]=k.useState(""),[O,U]=k.useState(null),{data:M}=Oe({queryKey:["settings"],queryFn:async()=>{const Z=await fetch("/api/settings",{headers:{Authorization:`Bearer ${r}`}});return Z.ok?Z.json():{}},enabled:!!r,staleTime:6e4}),{data:I,isLoading:H,error:z}=Oe({queryKey:["dispute",n],queryFn:async()=>{const Z=await fetch(`/api/disputes/${n}`,{headers:{Authorization:`Bearer ${r}`}});if(!Z.ok)throw new Error("Failed to fetch dispute");return Z.json()},enabled:!!r}),G=Ue({mutationFn:async Z=>{const ge=await fetch(`/api/disputes/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(Z)});if(!ge.ok){const Te=await ge.json();throw new Error(Te.detail||"Failed to update dispute")}return ge.json()},onSuccess:()=>{o.invalidateQueries({queryKey:["dispute",n]}),o.invalidateQueries({queryKey:["disputes"]}),o.invalidateQueries({queryKey:["dispute-stats"]}),t&&t(),l("")}}),te=Ue({mutationFn:async()=>{const Z=await fetch(`/api/disputes/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!Z.ok){const ge=await Z.json();throw new Error(ge.detail||"Failed to delete dispute")}return Z.json()},onSuccess:()=>{o.invalidateQueries({queryKey:["disputes"]}),o.invalidateQueries({queryKey:["dispute-stats"]}),t&&t(),e()}}),re=Z=>{G.mutate({status:Z.toUpperCase()})},me=Z=>{G.mutate({priority:Z.toLowerCase()})},J=()=>{if(!a.trim()){alert("Please enter a note");return}G.mutate({supplier_response:a.trim()})},ne=()=>{confirm(`Are you sure you want to permanently delete this dispute? Dispute: ${I==null?void 0:I.title} Invoice #${I==null?void 0:I.invoice_number} This action cannot be undone.`)&&te.mutate()},ye=()=>{I&&(g(I.title),y(I.description||""),f(!0))},ke=()=>{f(!1),g(""),y("")},Ye=()=>{if(!p.trim()){alert("Title cannot be empty");return}G.mutate({title:p.trim(),description:m.trim()||void 0}),f(!1)},De=async()=>{A(!0),U(null),P(""),W("");try{const Z=await fetch(`/api/disputes/${n}/draft-email`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!Z.ok){const Te=await Z.json();throw new Error(Te.detail||"Failed to draft email")}const ge=await Z.json();ge.llm_status==="success"||ge.llm_status==="cached"?(P(ge.email_subject||""),W(ge.email_body||"")):U(ge.error||"AI drafting unavailable")}catch(Z){U(Z instanceof Error?Z.message:"Failed to draft email")}finally{A(!1)}},qe=async()=>{if(!v){alert("Please select a file");return}b(!0);try{const Z=new FormData;Z.append("file",v);const ge=new URLSearchParams;ge.append("attachment_type","photo"),w.trim()&&ge.append("description",w.trim());const Te=await fetch(`/api/disputes/${n}/attachments?${ge}`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:Z});if(!Te.ok){const Be=await Te.json();throw new Error(Be.detail||"Failed to upload attachment")}o.invalidateQueries({queryKey:["dispute",n]}),t&&t(),x(null),S(""),c(!1)}catch(Z){alert(Z instanceof Error?Z.message:"Upload failed")}finally{b(!1)}},ue=Z=>{if(!Z.public_url)return;const ge=`${window.location.origin}${Z.public_url}`;navigator.clipboard.writeText(ge).then(()=>{T(Z.public_hash),setTimeout(()=>T(null),2e3)}).catch(()=>{const Te=document.createElement("textarea");Te.value=ge,document.body.appendChild(Te),Te.select(),document.execCommand("copy"),document.body.removeChild(Te),T(Z.public_hash),setTimeout(()=>T(null),2e3)})},Ze=Z=>{Z.public_url&&window.open(Z.public_url,"_blank")};return H?s.jsx("div",{style:at.modalOverlay,onClick:e,children:s.jsx("div",{style:at.modal,onClick:Z=>Z.stopPropagation(),children:s.jsx("div",{style:at.loading,children:"Loading dispute details..."})})}):z||!I?s.jsx("div",{style:at.modalOverlay,onClick:e,children:s.jsx("div",{style:at.modal,onClick:Z=>Z.stopPropagation(),children:s.jsxs("div",{style:at.error,children:["Error loading dispute: ",(z==null?void 0:z.message)||"Unknown error"]})})}):s.jsx("div",{style:at.modalOverlay,onClick:e,children:s.jsxs("div",{style:at.modal,onClick:Z=>Z.stopPropagation(),children:[s.jsxs("div",{style:at.modalHeader,children:[s.jsxs("div",{children:[s.jsxs("div",{style:at.modalSubtitle,children:[I.supplier_name," - ",s.jsxs("a",{href:`/invoice/${I.invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:at.invoiceLink,children:["Invoice #",I.invoice_number||I.invoice_id]})," - ",s.jsx("span",{style:at.disputeTypeHeader,children:I.dispute_type.replace(/_/g," ").toUpperCase()})]}),u?s.jsx("input",{type:"text",value:p,onChange:Z=>g(Z.target.value),style:{...at.modalTitle,border:"2px solid #e94560",padding:"0.5rem"},maxLength:200}):s.jsx("h2",{style:at.modalTitle,children:I.title})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[u?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:Ye,disabled:G.isPending,style:{...at.deleteBtn,background:"#5cb85c"},type:"button",children:G.isPending?"Saving...":"✓ Save"}),s.jsx("button",{onClick:ke,disabled:G.isPending,style:at.deleteBtn,type:"button",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:ye,style:{...at.deleteBtn,background:"#5bc0de"},type:"button",title:"Edit title and description",children:"✏️ Edit"}),(i==null?void 0:i.is_admin)&&s.jsx("button",{onClick:ne,disabled:te.isPending,style:at.deleteBtn,type:"button",title:"Delete dispute (Admin only)",children:te.isPending?"...":"🗑️ Delete"})]}),s.jsx("button",{style:at.closeBtn,onClick:e,type:"button",children:"✕"})]})]}),s.jsxs("div",{style:at.modalBody,children:[s.jsxs("div",{style:at.section,children:[s.jsx("div",{style:at.actionGroup,children:s.jsx("div",{style:at.buttonRow,children:Yhe.map(Z=>s.jsx("button",{onClick:()=>re(Z.value),disabled:G.isPending||I.status.toLowerCase()===Z.value,style:{...at.statusButton,...I.status.toLowerCase()===Z.value?{background:$he[Z.value]||"#999",color:"white",fontWeight:"bold"}:{}},children:Z.label},Z.value))})}),s.jsx("div",{style:at.actionGroup,children:s.jsx("div",{style:at.buttonRow,children:Qhe.map(Z=>s.jsx("button",{onClick:()=>me(Z.value),disabled:G.isPending||I.priority.toLowerCase()===Z.value,style:{...at.statusButton,...I.priority.toLowerCase()===Z.value?{background:Zhe[Z.value]||"#999",color:"white",fontWeight:"bold"}:{}},children:Z.label},Z.value))})})]}),s.jsxs("div",{style:at.section,children:[s.jsx("h3",{style:at.sectionTitle,children:"Financial Impact"}),s.jsxs("div",{style:at.financialGrid,children:[s.jsxs("div",{style:at.financialCard,children:[s.jsx("div",{style:at.financialLabel,children:"Disputed Amount"}),s.jsxs("div",{style:at.financialValue,children:["£",Number(I.disputed_amount).toFixed(2)]})]}),I.expected_amount!=null&&s.jsxs("div",{style:at.financialCard,children:[s.jsx("div",{style:at.financialLabel,children:"Expected Amount"}),s.jsxs("div",{style:at.financialValue,children:["£",Number(I.expected_amount).toFixed(2)]})]}),s.jsxs("div",{style:at.financialCard,children:[s.jsx("div",{style:at.financialLabel,children:"Difference"}),s.jsxs("div",{style:{...at.financialValue,color:"#e94560"},children:["£",Number(Math.abs(I.difference_amount)).toFixed(2)]})]})]})]}),(M==null?void 0:M.llm_enabled)&&(M==null?void 0:M.anthropic_api_key_set)&&s.jsxs("div",{style:at.section,children:[s.jsxs("div",{style:at.sectionHeader,children:[s.jsx("h3",{style:at.sectionTitle,children:"Draft Supplier Email"}),s.jsx("button",{onClick:De,disabled:F,style:{...at.secondaryBtn,background:"#7952b3",color:"white",border:"none",opacity:F?.6:1},children:F?"Drafting...":"✨ Draft Email"})]}),O&&s.jsx("div",{style:{padding:"0.5rem 0.75rem",background:"#fee",color:"#c00",borderRadius:"6px",fontSize:"0.85rem",marginBottom:"0.75rem"},children:O}),D&&s.jsxs("div",{style:{background:"#f3effc",borderRadius:"8px",padding:"1rem",border:"1px solid #d4c5f0"},children:[s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("label",{style:{...at.label,fontSize:"0.8rem",color:"#7952b3"},children:"Subject"}),s.jsx("input",{type:"text",value:D,onChange:Z=>P(Z.target.value),style:{...at.input,marginBottom:0,borderColor:"#d4c5f0"}})]}),s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("label",{style:{...at.label,fontSize:"0.8rem",color:"#7952b3"},children:"Body"}),s.jsx("textarea",{value:L,onChange:Z=>W(Z.target.value),style:{...at.textarea,minHeight:"180px",marginBottom:0,borderColor:"#d4c5f0"}})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`Subject: ${D} ${L}`)},style:{...at.secondaryBtn,fontSize:"0.85rem"},children:"Copy to Clipboard"}),s.jsx("button",{onClick:()=>{window.open(`mailto:?subject=${encodeURIComponent(D)}&body=${encodeURIComponent(L)}`)},style:{...at.primaryBtn,fontSize:"0.85rem",padding:"0.5rem 1rem"},children:"Open in Email Client"})]}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#7952b3",marginTop:"0.5rem",fontStyle:"italic"},children:"AI-generated draft — review and edit before sending"})]})]}),s.jsxs("div",{style:at.section,children:[s.jsx("h3",{style:at.sectionTitle,children:"Description"}),u?s.jsx("textarea",{value:m,onChange:Z=>y(Z.target.value),style:{...at.textarea,width:"100%",minHeight:"100px"},placeholder:"Detailed description of the dispute (optional)..."}):s.jsx("p",{style:at.description,children:I.description||"No description provided"})]}),I.line_items.length>0&&s.jsxs("div",{style:at.section,children:[s.jsxs("h3",{style:at.sectionTitle,children:["Disputed Line Items (",I.line_items.length,")"]}),s.jsx("div",{style:at.tableContainer,children:s.jsxs("table",{style:at.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:at.th,children:"Product"}),s.jsx("th",{style:at.th,children:"Qty"}),s.jsx("th",{style:at.th,children:"Unit Price"}),s.jsx("th",{style:at.th,children:"Total"})]})}),s.jsx("tbody",{children:I.line_items.map(Z=>s.jsxs("tr",{children:[s.jsxs("td",{style:at.td,children:[s.jsx("div",{children:Z.product_name}),Z.product_code&&s.jsx("div",{style:at.productCode,children:Z.product_code})]}),s.jsx("td",{style:at.td,children:Z.quantity_ordered!=null?Number(Z.quantity_ordered).toFixed(2):"-"}),s.jsx("td",{style:at.td,children:Z.unit_price_charged!=null?`£${Number(Z.unit_price_charged).toFixed(2)}`:"-"}),s.jsxs("td",{style:at.td,children:["£",Number(Z.total_charged).toFixed(2)]})]},Z.id))})]})})]}),s.jsxs("div",{style:at.section,children:[s.jsxs("div",{style:at.sectionHeader,children:[s.jsxs("h3",{style:at.sectionTitle,children:["Attachments (",I.attachments.length,")"]}),s.jsx("button",{style:at.secondaryBtn,onClick:()=>c(!d),children:d?"Cancel":"+ Upload"})]}),d&&s.jsx("div",{style:at.uploadSection,children:s.jsxs("div",{style:at.uploadForm,children:[s.jsxs("div",{style:at.formGroup,children:[s.jsx("input",{type:"file",onChange:Z=>{var ge;return x(((ge=Z.target.files)==null?void 0:ge[0])||null)},accept:"image/*,.pdf,.doc,.docx,.eml,.msg",style:at.fileInput}),v&&s.jsxs("span",{style:at.selectedFile,children:["Selected: ",v.name," (",(v.size/1024).toFixed(1)," KB)"]})]}),s.jsx("div",{style:at.formGroup,children:s.jsx("input",{type:"text",value:w,onChange:Z=>S(Z.target.value),placeholder:"Description (optional)",style:at.input})}),s.jsx("button",{onClick:qe,disabled:!v||_,style:{...at.primaryBtn,opacity:!v||_?.6:1},children:_?"Uploading...":"Upload"})]})}),I.attachments.length===0?s.jsx("p",{style:at.empty,children:"No attachments yet. Upload photos of damaged items to share with suppliers."}):s.jsx("div",{style:at.attachmentList,children:I.attachments.map(Z=>s.jsxs("div",{style:at.attachmentItem,children:[s.jsxs("div",{style:at.attachmentInfo,children:[s.jsxs("span",{style:at.attachmentName,children:[Z.file_type.startsWith("image/")?"🖼️":"📎"," ",Z.file_name]}),s.jsxs("span",{style:at.attachmentMeta,children:[(Z.file_size_bytes/1024).toFixed(1)," KB •",new Date(Z.uploaded_at).toLocaleDateString()," by ",Z.uploaded_by_username||"Unknown"]}),Z.description&&s.jsx("span",{style:at.attachmentDesc,children:Z.description})]}),s.jsx("div",{style:at.attachmentActions,children:Z.public_url&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>Ze(Z),style:at.actionBtn,title:"View in new tab",children:"View"}),s.jsx("button",{onClick:()=>ue(Z),style:{...at.actionBtn,background:C===Z.public_hash?"#5cb85c":"#e94560"},title:"Copy shareable link for email",children:C===Z.public_hash?"Copied!":"Copy Link"})]})})]},Z.id))}),I.attachments.length>0&&s.jsx("p",{style:at.attachmentHint,children:'Use "Copy Link" to get a shareable URL that can be included in emails to suppliers.'})]}),s.jsxs("div",{style:at.section,children:[s.jsx("h3",{style:at.sectionTitle,children:"Activity & Notes"}),I.activity_log.length===0?s.jsx("p",{style:at.empty,children:"No activity logged"}):s.jsx("div",{style:at.chatLog,children:I.activity_log.map(Z=>Z.activity_type==="status_change"||Z.activity_type==="priority_change"||Z.activity_type==="created"?s.jsxs("div",{style:at.logItem,children:[s.jsx("span",{style:at.logMessage,children:Z.description}),s.jsxs("span",{style:at.logMeta,children:[new Date(Z.created_at).toLocaleString()," - ",Z.created_by_username||"System"]})]},Z.id):s.jsxs("div",{style:at.chatItem,children:[s.jsx("div",{style:at.chatMessage,children:Z.description}),s.jsxs("div",{style:at.chatFooter,children:[s.jsx("span",{style:at.chatTime,children:new Date(Z.created_at).toLocaleString()}),s.jsxs("span",{style:at.chatUser,children:[" - ",Z.created_by_username||"System"]})]})]},Z.id))}),s.jsxs("div",{style:at.addNoteSection,children:[s.jsx("label",{style:at.label,children:"Add Note"}),s.jsx("textarea",{value:a,onChange:Z=>l(Z.target.value),style:at.textarea,placeholder:"Add a note about this dispute...",rows:3}),s.jsx("button",{style:at.primaryBtn,onClick:J,disabled:G.isPending||!a.trim(),children:"Add Note"})]})]}),G.isError&&s.jsxs("div",{style:at.errorBox,children:["Error: ",((ee=G.error)==null?void 0:ee.message)||"Failed to update dispute"]})]})]})})}const at={modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3,padding:"1rem"},modal:{background:"white",borderRadius:"12px",maxWidth:"900px",width:"100%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",padding:"1.5rem",borderBottom:"1px solid #eee",position:"sticky",top:0,background:"white",zIndex:1},modalTitle:{margin:0,marginTop:"0.5rem",color:"#1a1a2e",fontSize:"1.25rem"},modalSubtitle:{color:"#666",fontSize:"0.9rem"},invoiceLink:{color:"#e94560",textDecoration:"none",fontWeight:"bold"},disputeTypeHeader:{fontSize:"0.7rem",fontWeight:"bold",color:"#666",letterSpacing:"0.5px"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},deleteBtn:{background:"#dc3545",color:"white",border:"none",padding:"0.5rem 1rem",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem",fontWeight:500,transition:"background 0.2s"},modalBody:{padding:"1.5rem",flex:1,overflow:"auto"},loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px",margin:"1rem"},section:{marginBottom:"2rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},sectionTitle:{margin:0,marginBottom:"1rem",color:"#1a1a2e",fontSize:"1rem",fontWeight:"bold"},financialGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:"1rem"},financialCard:{display:"flex",flexDirection:"column",padding:"1.25rem",background:"white",border:"1px solid #e0e0e0",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.08)"},financialLabel:{fontSize:"0.75rem",color:"#666",marginBottom:"0.5rem",textTransform:"uppercase",fontWeight:"600",letterSpacing:"0.5px"},financialValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#1a1a2e"},description:{margin:0,color:"#333",lineHeight:1.6},tableContainer:{overflowX:"auto"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{textAlign:"left",padding:"0.75rem",background:"#f5f5f5",fontWeight:"bold",color:"#1a1a2e",borderBottom:"2px solid #ddd"},td:{padding:"0.75rem",borderBottom:"1px solid #eee",color:"#333"},productCode:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},empty:{padding:"1rem",textAlign:"center",color:"#999",fontStyle:"italic"},attachmentList:{display:"flex",flexDirection:"column",gap:"0.5rem"},attachmentItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem",background:"#f9f9f9",borderRadius:"8px"},attachmentName:{color:"#1a1a2e",fontWeight:"500"},attachmentMeta:{fontSize:"0.8rem",color:"#666"},chatLog:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"1.5rem",padding:"1rem",background:"#f5f5f5",borderRadius:"8px"},logItem:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.5rem 0",fontSize:"0.8rem",color:"#999"},logMessage:{color:"#666",fontSize:"0.8rem"},logMeta:{fontSize:"0.7rem",color:"#999",whiteSpace:"nowrap",marginLeft:"1rem"},chatItem:{padding:"1rem",background:"white",borderRadius:"8px",border:"1px solid #e0e0e0",boxShadow:"0 1px 3px rgba(0,0,0,0.05)"},chatMessage:{color:"#1a1a2e",fontSize:"1rem",lineHeight:1.5,marginBottom:"0.5rem"},chatFooter:{display:"flex",justifyContent:"flex-end",alignItems:"center",fontSize:"0.75rem",color:"#999"},chatUser:{fontSize:"0.75rem",color:"#999"},chatTime:{fontSize:"0.75rem",color:"#999"},addNoteSection:{marginTop:"1.5rem",paddingTop:"1.5rem",borderTop:"1px solid #eee"},buttonRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap",justifyContent:"center"},statusButton:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",cursor:"pointer",fontSize:"1rem",fontWeight:"500",transition:"all 0.2s",color:"#333"},actionGroup:{marginBottom:"1.5rem"},label:{display:"block",marginBottom:"0.5rem",fontWeight:"bold",color:"#1a1a2e",fontSize:"0.9rem"},input:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box",marginBottom:"0.75rem"},textarea:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit",marginBottom:"0.75rem"},primaryBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"none",background:"#e94560",color:"white",cursor:"pointer",fontWeight:"bold",fontSize:"1rem",whiteSpace:"nowrap"},secondaryBtn:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",color:"#666",cursor:"pointer",fontWeight:"bold",fontSize:"0.9rem"},errorBox:{marginTop:"1rem",padding:"0.75rem",background:"#fee",color:"#c00",borderRadius:"8px",fontSize:"0.9rem"},uploadSection:{padding:"1rem",background:"#f9f9f9",borderRadius:"8px",marginBottom:"1rem"},uploadForm:{display:"flex",flexDirection:"column",gap:"1rem"},formGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},fileInput:{padding:"0.5rem",border:"2px dashed #ccc",borderRadius:"8px",background:"white",cursor:"pointer"},selectedFile:{fontSize:"0.85rem",color:"#666",fontStyle:"italic"},attachmentInfo:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},attachmentDesc:{fontSize:"0.8rem",color:"#666",fontStyle:"italic"},attachmentActions:{display:"flex",gap:"0.5rem",flexShrink:0},actionBtn:{padding:"0.4rem 0.75rem",borderRadius:"6px",border:"none",background:"#e94560",color:"white",cursor:"pointer",fontSize:"0.8rem",fontWeight:"500",whiteSpace:"nowrap",transition:"background 0.2s"},attachmentHint:{marginTop:"1rem",padding:"0.75rem",background:"#e8f4f8",borderRadius:"6px",fontSize:"0.85rem",color:"#0c5460",fontStyle:"italic"}},Jhe={price_discrepancy:"Price Discrepancy",short_delivery:"Short Delivery",wrong_product:"Wrong Product",quality_issue:"Quality Issue",calculation_error:"Calculation Error",missing_items:"Missing Items",damaged_goods:"Damaged Goods",other:"Other"},efe={NEW:"#17a2b8",OPEN:"#17a2b8",CONTACTED:"#6c757d",IN_PROGRESS:"#ffc107",AWAITING_CREDIT:"#fd7e14",AWAITING_REPLACEMENT:"#fd7e14",ESCALATED:"#dc3545"};function tfe({supplierId:n,supplierName:e,creditNoteInvoiceId:t,creditNoteNumber:r,creditNoteAmount:i,onClose:o,onSuccess:a}){var _;const{token:l}=gn(),d=pi(),[c,u]=k.useState(null),[f,p]=k.useState(i?Math.abs(i).toFixed(2):""),[g,m]=k.useState(""),{data:y,isLoading:v}=Oe({queryKey:["open-disputes",n],queryFn:async()=>{const b=await fetch(`/api/disputes/supplier/${n}/open`,{headers:{Authorization:`Bearer ${l}`}});if(!b.ok)throw new Error("Failed to fetch disputes");return b.json()},enabled:!!n}),x=Ue({mutationFn:async()=>{if(!c)throw new Error("No dispute selected");const b=await fetch(`/api/disputes/${c}/link-credit-note`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({credit_note_invoice_id:t,resolved_amount:f?parseFloat(f):void 0,resolution_notes:g||void 0})});if(!b.ok){const C=await b.json();throw new Error(C.detail||"Failed to link dispute")}return b.json()},onSuccess:()=>{d.invalidateQueries({queryKey:["disputes"]}),d.invalidateQueries({queryKey:["dispute-stats"]}),d.invalidateQueries({queryKey:["open-disputes",n]}),d.invalidateQueries({queryKey:["invoice",t]}),d.invalidateQueries({queryKey:["invoices"]}),a&&a(),o()}}),w=b=>{if(b.preventDefault(),!c){alert("Please select a dispute to link");return}x.mutate()},S=b=>new Date(b).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"});return s.jsx("div",{style:kn.modalOverlay,onClick:o,children:s.jsxs("div",{style:kn.modal,onClick:b=>b.stopPropagation(),children:[s.jsxs("div",{style:kn.modalHeader,children:[s.jsx("h2",{style:kn.modalTitle,children:"Link Credit Note to Dispute"}),s.jsx("button",{style:kn.closeBtn,onClick:o,type:"button",children:"✕"})]}),s.jsxs("div",{style:kn.content,children:[s.jsxs("div",{style:kn.infoBox,children:[s.jsxs("div",{style:kn.infoRow,children:[s.jsx("span",{style:kn.infoLabel,children:"Credit Note:"}),s.jsxs("span",{style:kn.infoValue,children:["#",r||t]})]}),s.jsxs("div",{style:kn.infoRow,children:[s.jsx("span",{style:kn.infoLabel,children:"Supplier:"}),s.jsx("span",{style:kn.infoValue,children:e||"Unknown"})]}),i&&s.jsxs("div",{style:kn.infoRow,children:[s.jsx("span",{style:kn.infoLabel,children:"Amount:"}),s.jsxs("span",{style:kn.infoValue,children:["£",Math.abs(i).toFixed(2)]})]})]}),s.jsxs("div",{style:kn.section,children:[s.jsx("h3",{style:kn.sectionTitle,children:"Select Open Dispute"}),v?s.jsx("div",{style:kn.loading,children:"Loading disputes..."}):!y||y.length===0?s.jsx("div",{style:kn.emptyState,children:"No open disputes found for this supplier."}):s.jsx("div",{style:kn.disputeList,children:y.map(b=>s.jsxs("label",{style:{...kn.disputeItem,borderColor:c===b.id?"#e94560":"#eee",background:c===b.id?"#fff5f7":"white"},children:[s.jsx("input",{type:"radio",name:"dispute",value:b.id,checked:c===b.id,onChange:()=>u(b.id),style:kn.radio}),s.jsxs("div",{style:kn.disputeContent,children:[s.jsxs("div",{style:kn.disputeHeader,children:[s.jsx("span",{style:kn.disputeTitle,children:b.title}),s.jsx("span",{style:{...kn.statusBadge,background:efe[b.status]||"#6c757d"},children:b.status.replace("_"," ")})]}),s.jsxs("div",{style:kn.disputeMeta,children:[s.jsx("span",{style:kn.disputeType,children:Jhe[b.dispute_type]||b.dispute_type}),s.jsxs("span",{style:kn.disputeAmount,children:["£",b.disputed_amount.toFixed(2)]}),s.jsxs("span",{style:kn.disputeDate,children:["Opened ",S(b.opened_at)]}),b.invoice_number&&s.jsxs("span",{style:kn.invoiceRef,children:["Invoice #",b.invoice_number]})]})]})]},b.id))})]}),c&&s.jsxs("div",{style:kn.section,children:[s.jsxs("div",{style:kn.formGroup,children:[s.jsx("label",{style:kn.label,children:"Resolved Amount (£)"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:f,onChange:b=>p(b.target.value),style:kn.input,placeholder:"0.00"}),s.jsx("div",{style:kn.hint,children:"Leave as-is to use credit note amount"})]}),s.jsxs("div",{style:kn.formGroup,children:[s.jsx("label",{style:kn.label,children:"Resolution Notes (optional)"}),s.jsx("textarea",{value:g,onChange:b=>m(b.target.value),style:kn.textarea,placeholder:"Any additional notes about the resolution...",rows:3})]})]})]}),s.jsxs("div",{style:kn.footer,children:[s.jsx("button",{type:"button",onClick:o,style:kn.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:w,style:{...kn.submitBtn,opacity:!c||x.isPending?.5:1,cursor:!c||x.isPending?"not-allowed":"pointer"},disabled:!c||x.isPending,children:x.isPending?"Linking...":"Link & Resolve Dispute"})]}),x.isError&&s.jsxs("div",{style:kn.error,children:["Error: ",((_=x.error)==null?void 0:_.message)||"Failed to link dispute"]})]})})}const kn={modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3,padding:"1rem"},modal:{background:"white",borderRadius:"12px",maxWidth:"600px",width:"100%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},modalTitle:{margin:0,color:"#1a1a2e",fontSize:"1.25rem"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},content:{padding:"1.5rem",flex:1,overflow:"auto"},infoBox:{background:"#f8f9fa",padding:"1rem",borderRadius:"8px",marginBottom:"1.5rem",border:"1px solid #e9ecef"},infoRow:{display:"flex",justifyContent:"space-between",marginBottom:"0.5rem"},infoLabel:{color:"#666",fontWeight:"500"},infoValue:{fontWeight:"600",color:"#1a1a2e"},section:{marginBottom:"1.5rem"},sectionTitle:{fontSize:"1rem",fontWeight:"600",color:"#1a1a2e",marginBottom:"0.75rem"},loading:{padding:"2rem",textAlign:"center",color:"#666"},emptyState:{padding:"2rem",textAlign:"center",color:"#666",background:"#f8f9fa",borderRadius:"8px",fontStyle:"italic"},disputeList:{display:"flex",flexDirection:"column",gap:"0.75rem",maxHeight:"250px",overflow:"auto"},disputeItem:{display:"flex",alignItems:"flex-start",padding:"1rem",border:"2px solid #eee",borderRadius:"8px",cursor:"pointer",transition:"border-color 0.2s, background 0.2s"},radio:{marginRight:"1rem",marginTop:"0.25rem",cursor:"pointer"},disputeContent:{flex:1},disputeHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"0.5rem",gap:"0.5rem"},disputeTitle:{fontWeight:"600",color:"#1a1a2e",flex:1},statusBadge:{padding:"0.2rem 0.5rem",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"600",color:"white",textTransform:"uppercase",whiteSpace:"nowrap"},disputeMeta:{display:"flex",flexWrap:"wrap",gap:"0.75rem",fontSize:"0.85rem",color:"#666"},disputeType:{background:"#e9ecef",padding:"0.15rem 0.5rem",borderRadius:"4px"},disputeAmount:{fontWeight:"600",color:"#dc3545"},disputeDate:{color:"#999"},invoiceRef:{color:"#666"},formGroup:{marginBottom:"1rem"},label:{display:"block",marginBottom:"0.5rem",fontWeight:"600",color:"#1a1a2e",fontSize:"0.9rem"},input:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box"},textarea:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit"},hint:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem",fontStyle:"italic"},footer:{display:"flex",justifyContent:"flex-end",gap:"1rem",padding:"1rem 1.5rem",borderTop:"1px solid #eee",flexShrink:0},cancelBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",color:"#666",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},submitBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"none",background:"#28a745",color:"white",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},error:{margin:"0 1.5rem 1rem",padding:"0.75rem",background:"#fee",color:"#c00",borderRadius:"8px",fontSize:"0.9rem"}};function TT({isOpen:n,onClose:e,onSaved:t,poId:r,defaultSupplierId:i,defaultDate:o}){const{token:a}=gn(),[l,d]=k.useState([]),[c,u]=k.useState(i||0),[f,p]=k.useState(o||new Date().toISOString().slice(0,10)),[g,m]=k.useState("itemised"),[y,v]=k.useState("DRAFT"),[x,w]=k.useState(null),[S,_]=k.useState(""),[b,C]=k.useState(""),[T,F]=k.useState([]),[A,D]=k.useState(null),[P,L]=k.useState(""),[W,O]=k.useState([]),[U,M]=k.useState(!1),[I,H]=k.useState(!1),[z,G]=k.useState(null),[te,re]=k.useState(null),[me,J]=k.useState(!1),[ne,ye]=k.useState(!1),ke=k.useRef(null),Ye=k.useRef(null);k.useEffect(()=>{a&&fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${a}`}}).then(Q=>Q.json()).then(Q=>d(Q.suppliers||Q||[])).catch(()=>{})},[a]),k.useEffect(()=>{a&&fetch("/api/settings/",{headers:{Authorization:`Bearer ${a}`}}).then(Q=>Q.json()).then(Q=>ye(!!(Q.smtp_host&&Q.smtp_from_email))).catch(()=>ye(!1))},[a]),k.useEffect(()=>{!r||!a||(J(!0),fetch(`/api/purchase-orders/${r}`,{headers:{Authorization:`Bearer ${a}`}}).then(Q=>{if(!Q.ok)throw new Error("Failed to load");return Q.json()}).then(Q=>{u(Q.supplier_id),p(Q.order_date),m(Q.order_type),v(Q.status),w(Q.total_amount),_(Q.order_reference||""),C(Q.notes||""),D(Q.attachment_original_name||null),F((Q.line_items||[]).map((X,pe)=>({id:X.id,product_id:X.product_id,product_code:X.product_code,description:X.description,unit:X.unit,unit_price:X.unit_price,quantity:X.quantity,total:X.total,line_number:X.line_number??pe,source:X.source||"manual"})))}).catch(()=>re("Failed to load purchase order")).finally(()=>J(!1)))},[r,a]),k.useEffect(()=>{n&&!r&&(u(i||0),p(o||new Date().toISOString().slice(0,10)),m("itemised"),v("DRAFT"),w(null),_(""),C(""),F([]),D(null),re(null),L(""),O([]))},[n,r,i,o]),k.useEffect(()=>{if(ke.current&&clearTimeout(ke.current),!P||P.length<2||!a){O([]);return}return ke.current=setTimeout(()=>{const Q=new URLSearchParams({query:P});c&&Q.append("supplier_id",String(c)),fetch(`/api/purchase-orders/products/search?${Q}`,{headers:{Authorization:`Bearer ${a}`}}).then(X=>X.json()).then(O).catch(()=>{})},300),()=>{ke.current&&clearTimeout(ke.current)}},[P,c,a]);const De=()=>{F(Q=>[...Q,{description:"",unit_price:0,quantity:1,total:0,line_number:Q.length,source:"manual"}])},qe=Q=>{F(X=>[...X,{product_id:Q.id||null,product_code:Q.product_code,description:Q.name,unit:Q.unit,unit_price:Q.last_price||0,quantity:1,total:Q.last_price||0,line_number:X.length,source:"search"}]),L(""),O([])},ue=(Q,X,pe)=>{F(we=>{const Ne=[...we],st={...Ne[Q],[X]:pe};return(X==="unit_price"||X==="quantity")&&(st.total=parseFloat((st.unit_price*st.quantity).toFixed(2))),Ne[Q]=st,Ne})},Ze=Q=>{F(X=>X.filter((pe,we)=>we!==Q))},ee=k.useCallback(()=>g==="single_value"?x||0:T.reduce((Q,X)=>Q+(X.total||0),0),[g,x,T]),Z=async Q=>{if(!a||!c||!f){re("Please fill in supplier and date");return}if(g==="itemised"&&T.length===0){re("Please add at least one line item");return}if(g==="single_value"&&(!x||x<=0)){re("Please enter a valid order value");return}M(!0),re(null);const X={supplier_id:c,order_date:f,order_type:g,status:Q||y,order_reference:S||null,notes:b||null,line_items:g==="itemised"?T.map((pe,we)=>({product_id:pe.product_id||null,product_code:pe.product_code||null,description:pe.description,unit:pe.unit||null,unit_price:pe.unit_price,quantity:pe.quantity,total:pe.total,line_number:we,source:pe.source})):[]};g==="single_value"&&(X.total_amount=x);try{const pe=r?`/api/purchase-orders/${r}`:"/api/purchase-orders/",Ne=await fetch(pe,{method:r?"PUT":"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(X)});if(!Ne.ok){const st=await Ne.json().catch(()=>({}));throw new Error(st.detail||"Failed to save")}t(),e()}catch(pe){re(pe.message||"Failed to save purchase order")}finally{M(!1)}},ge=async Q=>{var we;const X=(we=Q.target.files)==null?void 0:we[0];if(!X||!r||!a)return;const pe=new FormData;pe.append("file",X);try{const Ne=await fetch(`/api/purchase-orders/${r}/attachment`,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:pe});if(!Ne.ok)throw new Error("Upload failed");const st=await Ne.json();D(st.attachment_original_name)}catch{re("Failed to upload attachment")}},Te=async()=>{if(!(!r||!a))try{await fetch(`/api/purchase-orders/${r}/attachment`,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}}),D(null)}catch{re("Failed to remove attachment")}},Be=async()=>{if(!(!r||!a)&&confirm("Delete this purchase order?"))try{const Q=await fetch(`/api/purchase-orders/${r}`,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!Q.ok){const X=await Q.json().catch(()=>({}));throw new Error(X.detail||"Delete failed")}t(),e()}catch(Q){re(Q.message||"Failed to delete")}},he=async()=>{if(a)if(r)await Z(),window.open(`/api/purchase-orders/${r}/preview?token=${encodeURIComponent(a||"")}`,"_blank");else{if(!c||!f){re("Please fill in supplier and date");return}M(!0),re(null);const Q={supplier_id:c,order_date:f,order_type:g,status:"DRAFT",order_reference:S||null,notes:b||null,line_items:g==="itemised"?T.map((X,pe)=>({product_id:X.product_id||null,product_code:X.product_code||null,description:X.description,unit:X.unit||null,unit_price:X.unit_price,quantity:X.quantity,total:X.total,line_number:pe,source:X.source})):[],...g==="single_value"?{total_amount:x}:{}};try{const X=await fetch("/api/purchase-orders/",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!X.ok)throw new Error("Failed to save");const pe=await X.json();window.open(`/api/purchase-orders/${pe.id}/preview?token=${encodeURIComponent(a||"")}`,"_blank"),t(),e()}catch(X){re(X.message||"Failed to save")}finally{M(!1)}}},He=async()=>{if(!a||!c||!f){re("Please fill in supplier and date");return}H(!0),re(null),G(null);const Q={supplier_id:c,order_date:f,order_type:g,status:y==="DRAFT"?"DRAFT":y,order_reference:S||null,notes:b||null,line_items:g==="itemised"?T.map((X,pe)=>({product_id:X.product_id||null,product_code:X.product_code||null,description:X.description,unit:X.unit||null,unit_price:X.unit_price,quantity:X.quantity,total:X.total,line_number:pe,source:X.source})):[],...g==="single_value"?{total_amount:x}:{}};try{const X=r?`/api/purchase-orders/${r}`:"/api/purchase-orders/",we=await fetch(X,{method:r?"PUT":"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!we.ok)throw new Error("Failed to save PO");const Ne=await we.json(),st=await fetch(`/api/purchase-orders/${Ne.id}/send-email`,{method:"POST",headers:{Authorization:`Bearer ${a}`}});if(!st.ok){const Re=await st.json().catch(()=>({}));throw new Error(Re.detail||"Failed to send email")}const Ve=await st.json();G(Ve.message||"Email sent successfully"),t(),setTimeout(()=>e(),1500)}catch(X){re(X.message||"Failed to send email")}finally{H(!1)}},Ge=l.find(Q=>Q.id===c),K=!!(Ge!=null&&Ge.order_email)&≠if(!n)return null;const de=!r||y==="DRAFT"||y==="PENDING",Y=ee();return s.jsx("div",{style:At.overlay,onClick:e,children:s.jsxs("div",{style:At.modal,onClick:Q=>Q.stopPropagation(),children:[s.jsxs("div",{style:At.header,children:[s.jsxs("h2",{style:At.title,children:[r?`Purchase Order #${r}`:"New Purchase Order",r&&s.jsx("span",{style:{...At.statusBadge,...nfe(y)},children:y})]}),s.jsx("button",{style:At.closeBtn,onClick:e,children:"×"})]}),s.jsx("div",{style:At.body,children:me?s.jsx("p",{children:"Loading..."}):s.jsxs(s.Fragment,{children:[te&&s.jsx("div",{style:At.error,children:te}),z&&s.jsx("div",{style:At.success,children:z}),s.jsxs("div",{style:At.fieldRow,children:[s.jsxs("div",{style:At.field,children:[s.jsx("label",{style:At.label,children:"Date"}),s.jsx("input",{type:"date",value:f,onChange:Q=>p(Q.target.value),style:At.input,disabled:!de})]}),s.jsxs("div",{style:At.field,children:[s.jsx("label",{style:At.label,children:"Supplier"}),s.jsxs("select",{value:c,onChange:Q=>u(Number(Q.target.value)),style:At.input,disabled:!de,children:[s.jsx("option",{value:0,children:"Select supplier..."}),l.map(Q=>s.jsx("option",{value:Q.id,children:Q.name},Q.id))]})]})]}),s.jsx("div",{style:At.fieldRow,children:s.jsxs("div",{style:{...At.field,flex:1},children:[s.jsx("label",{style:At.label,children:"Notes"}),s.jsx("textarea",{value:b,onChange:Q=>C(Q.target.value),style:{...At.input,minHeight:"50px",resize:"vertical"},disabled:!de,placeholder:"Optional notes..."})]})}),s.jsxs("div",{style:At.tabs,children:[s.jsx("button",{style:{...At.tab,...g==="itemised"?At.tabActive:{}},onClick:()=>de&&m("itemised"),disabled:!de,children:"Itemised Order"}),s.jsx("button",{style:{...At.tab,...g==="single_value"?At.tabActive:{}},onClick:()=>de&&m("single_value"),disabled:!de,children:"Single Value"})]}),g==="itemised"?s.jsxs(s.Fragment,{children:[T.length>0&&s.jsx("div",{style:At.tableWrap,children:s.jsxs("table",{style:At.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:At.th,children:"Product"}),s.jsx("th",{style:{...At.th,width:"90px"},children:"Price"}),s.jsx("th",{style:{...At.th,width:"70px"},children:"Qty"}),s.jsx("th",{style:{...At.th,width:"90px"},children:"Total"}),de&&s.jsx("th",{style:{...At.th,width:"36px"}})]})}),s.jsx("tbody",{children:T.map((Q,X)=>s.jsxs("tr",{children:[s.jsx("td",{style:At.td,children:Q.source==="search"?s.jsxs("span",{children:[Q.product_code?`${Q.product_code} - `:"",Q.description]}):s.jsx("input",{value:Q.description,onChange:pe=>ue(X,"description",pe.target.value),style:At.cellInput,placeholder:"Description",disabled:!de})}),s.jsx("td",{style:At.td,children:s.jsx("input",{type:"number",step:"0.01",value:Q.unit_price,onChange:pe=>ue(X,"unit_price",parseFloat(pe.target.value)||0),style:{...At.cellInput,textAlign:"right"},disabled:!de})}),s.jsx("td",{style:At.td,children:s.jsx("input",{type:"number",step:"0.001",value:Q.quantity,onChange:pe=>ue(X,"quantity",parseFloat(pe.target.value)||0),style:{...At.cellInput,textAlign:"right"},disabled:!de})}),s.jsxs("td",{style:{...At.td,textAlign:"right",fontWeight:500},children:["£",Q.total.toFixed(2)]}),de&&s.jsx("td",{style:At.td,children:s.jsx("button",{style:At.removeBtn,onClick:()=>Ze(X),children:"×"})})]},X))})]})}),de&&s.jsxs(s.Fragment,{children:[s.jsx("button",{style:At.addBtn,onClick:De,children:"+ Add Manual Item"}),s.jsxs("div",{style:At.searchSection,children:[s.jsx("label",{style:At.label,children:"Search Products (filtered to supplier)"}),s.jsx("input",{value:P,onChange:Q=>L(Q.target.value),style:At.input,placeholder:"Search by name or code..."}),W.length>0&&s.jsx("div",{style:At.searchResults,children:s.jsxs("table",{style:At.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:At.th,children:"Code"}),s.jsx("th",{style:At.th,children:"Product"}),s.jsx("th",{style:At.th,children:"Unit"}),s.jsx("th",{style:At.th,children:"Price"}),s.jsx("th",{style:At.th})]})}),s.jsx("tbody",{children:W.map((Q,X)=>s.jsxs("tr",{children:[s.jsx("td",{style:At.td,children:Q.product_code||"-"}),s.jsx("td",{style:At.td,children:Q.name}),s.jsx("td",{style:At.td,children:Q.unit||"-"}),s.jsx("td",{style:At.td,children:Q.last_price!=null?`£${Q.last_price.toFixed(2)}`:"-"}),s.jsx("td",{style:At.td,children:s.jsx("button",{style:At.addSearchBtn,onClick:()=>qe(Q),children:"Add"})})]},X))})]})})]})]})]}):s.jsxs("div",{style:{marginTop:"1rem"},children:[s.jsxs("div",{style:At.fieldRow,children:[s.jsxs("div",{style:At.field,children:[s.jsxs("label",{style:At.label,children:["Order Value (","£",")"]}),s.jsx("input",{type:"number",step:"0.01",value:x??"",onChange:Q=>w(parseFloat(Q.target.value)||null),style:At.input,disabled:!de})]}),s.jsxs("div",{style:At.field,children:[s.jsx("label",{style:At.label,children:"Order Ref"}),s.jsx("input",{value:S,onChange:Q=>_(Q.target.value),style:At.input,disabled:!de,placeholder:"Optional"})]})]}),r&&s.jsxs("div",{style:{marginTop:"0.75rem"},children:[s.jsx("label",{style:At.label,children:"Attachment"}),A?s.jsxs("div",{style:At.attachRow,children:[s.jsx("span",{children:A}),de&&s.jsx("button",{style:At.removeBtn,onClick:Te,children:"Remove"})]}):de?s.jsxs(s.Fragment,{children:[s.jsx("button",{style:At.addBtn,onClick:()=>{var Q;return(Q=Ye.current)==null?void 0:Q.click()},children:"Upload File"}),s.jsx("input",{ref:Ye,type:"file",style:{display:"none"},onChange:ge})]}):null]})]}),s.jsx("div",{style:At.totalRow,children:s.jsxs("strong",{children:["Total: ","£",Y.toFixed(2)]})})]})}),s.jsxs("div",{style:At.footer,children:[s.jsx("div",{style:{display:"flex",gap:"0.5rem"},children:r&&de&&(y==="DRAFT"||y==="PENDING")&&s.jsx("button",{style:At.deleteBtn,onClick:Be,children:"Delete"})}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsx("button",{style:At.cancelBtn,onClick:e,children:"Cancel"}),de&&s.jsxs(s.Fragment,{children:[s.jsx("button",{style:At.previewBtn,onClick:he,disabled:U||I,children:U?"Saving...":"Preview"}),K&&s.jsx("button",{style:At.emailBtn,onClick:He,disabled:U||I,children:I?"Sending...":"Save & Email"}),s.jsx("button",{style:At.draftBtn,onClick:()=>Z("DRAFT"),disabled:U||I,children:U?"Saving...":"Save Draft"}),s.jsx("button",{style:At.submitBtn,onClick:()=>Z("PENDING"),disabled:U||I,children:U?"Saving...":"Save & Submit"})]}),!de&&r&&s.jsx("button",{style:At.previewBtn,onClick:()=>window.open(`/api/purchase-orders/${r}/preview?token=${encodeURIComponent(a||"")}`,"_blank"),children:"Preview"})]})]})]})})}function nfe(n){switch(n){case"DRAFT":return{background:"#e0e0e0",color:"#555"};case"PENDING":return{background:"#e3f2fd",color:"#1565c0"};case"LINKED":return{background:"#d4edda",color:"#155724"};case"CLOSED":return{background:"#f5f5f5",color:"#666"};case"CANCELLED":return{background:"#ffebee",color:"#c62828"};default:return{}}}const At={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",maxWidth:"800px",width:"95%",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)",display:"flex",flexDirection:"column"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},title:{margin:0,color:"#1a1a2e",display:"flex",alignItems:"center",gap:"0.75rem",fontSize:"1.2rem"},statusBadge:{fontSize:"0.75rem",padding:"0.2rem 0.6rem",borderRadius:"12px",fontWeight:600},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},body:{padding:"1.5rem",overflowY:"auto",flex:1},footer:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.5rem",borderTop:"1px solid #eee",flexShrink:0},error:{background:"#ffebee",color:"#c62828",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},fieldRow:{display:"flex",gap:"1rem",marginBottom:"0.75rem"},field:{flex:1},label:{display:"block",fontSize:"0.85rem",fontWeight:600,color:"#555",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},tabs:{display:"flex",gap:"0.5rem",marginTop:"1rem",marginBottom:"0.75rem"},tab:{padding:"0.5rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"#f9f9f9",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},tabActive:{background:"#1a1a2e",color:"white",borderColor:"#1a1a2e"},tableWrap:{overflowX:"auto",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{textAlign:"left",padding:"0.5rem",borderBottom:"2px solid #eee",fontWeight:600,color:"#666",fontSize:"0.8rem"},td:{padding:"0.4rem 0.5rem",borderBottom:"1px solid #f0f0f0",verticalAlign:"middle"},cellInput:{width:"100%",padding:"0.3rem 0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.85rem",boxSizing:"border-box"},removeBtn:{background:"none",border:"none",color:"#c62828",cursor:"pointer",fontSize:"1.1rem",fontWeight:"bold",padding:"0 0.25rem"},addBtn:{background:"none",border:"1px dashed #999",borderRadius:"6px",padding:"0.4rem 0.75rem",cursor:"pointer",color:"#555",fontSize:"0.85rem",marginBottom:"0.75rem"},searchSection:{marginTop:"0.5rem",padding:"0.75rem",background:"#fafafa",borderRadius:"6px",border:"1px solid #eee"},searchResults:{marginTop:"0.5rem",maxHeight:"200px",overflowY:"auto"},addSearchBtn:{background:"#1a1a2e",color:"white",border:"none",borderRadius:"4px",padding:"0.25rem 0.5rem",cursor:"pointer",fontSize:"0.8rem"},totalRow:{textAlign:"right",marginTop:"1rem",fontSize:"1.1rem",padding:"0.75rem",background:"#f5f5f5",borderRadius:"6px"},attachRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"#f5f5f5",borderRadius:"6px",fontSize:"0.9rem"},cancelBtn:{padding:"0.5rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"white",cursor:"pointer",fontSize:"0.9rem"},draftBtn:{padding:"0.5rem 1rem",border:"1px solid #999",borderRadius:"6px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},submitBtn:{padding:"0.5rem 1rem",border:"none",borderRadius:"6px",background:"#1a1a2e",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},deleteBtn:{padding:"0.5rem 1rem",border:"1px solid #c62828",borderRadius:"6px",background:"#ffebee",color:"#c62828",cursor:"pointer",fontSize:"0.85rem"},previewBtn:{padding:"0.5rem 1rem",border:"1px solid #1565c0",borderRadius:"6px",background:"#e3f2fd",color:"#1565c0",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},emailBtn:{padding:"0.5rem 1rem",border:"1px solid #2e7d32",borderRadius:"6px",background:"#e8f5e9",color:"#2e7d32",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},success:{background:"#e8f5e9",color:"#2e7d32",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"}};function rfe({ingredientId:n,token:e,onChange:t,onDismissalsChange:r,ingredientName:i,productIngredients:o,lineItemDescription:a,scanSuggestions:l,llmSuggestions:d,llmAnalysing:c,autoApplyFlagIds:u,autoApplyNoneCategoryIds:f}){const p=pi(),[g,m]=k.useState(new Set),[y,v]=k.useState(new Set),[x,w]=k.useState(new Set),[S,_]=k.useState(new Set),[b,C]=k.useState(new Set),[T,F]=k.useState(!1),[A,D]=k.useState(!0),[P,L]=k.useState([]),[W,O]=k.useState(null),[U,M]=k.useState(""),[I,H]=k.useState(""),[z,G]=k.useState(!1),te=Rg(i||"",500),re=Rg(a||"",500),me=Rg(o||"",500),{data:J}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const ae=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():[]},enabled:!!e}),{data:ne}=Oe({queryKey:["ingredient-flags",n],queryFn:async()=>{const ae=await fetch(`/api/ingredients/${n}/flags`,{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():[]},enabled:!!e&&!!n}),{data:ye}=Oe({queryKey:["ingredient-flag-nones",n],queryFn:async()=>{const ae=await fetch(`/api/ingredients/${n}/flags/nones`,{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():{none_category_ids:[]}},enabled:!!e&&!!n}),{data:ke}=Oe({queryKey:["ingredient-flag-dismissals",n],queryFn:async()=>{const ae=await fetch(`/api/ingredients/${n}/flags/dismissals`,{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():[]},enabled:!!e&&!!n}),{data:Ye}=Oe({queryKey:["allergen-suggestions",te,re,me],queryFn:async()=>{const ae=new URLSearchParams;te&&ae.set("name",te),re&&ae.set("line_item",re),me&&ae.set("text",me);const K=await fetch(`/api/food-flags/suggest?${ae}`,{headers:{Authorization:`Bearer ${e}`}});return K.ok?K.json():[]},enabled:!!e&&(te.length>=2||re.length>=2||me.length>=5)});k.useEffect(()=>{ne&&m(new Set(ne.map(ae=>ae.food_flag_id)))},[ne]),k.useEffect(()=>{ye&&v(new Set(ye.none_category_ids))},[ye]),k.useEffect(()=>{ke&&L(ke)},[ke]),k.useEffect(()=>{n||(m(new Set),v(new Set),C(new Set),D(!0),L([]),O(null),G(!1),_(new Set))},[n]),k.useEffect(()=>{if(!n&&(J!=null&&J.length)){const ae=J.filter(K=>K.required).map(K=>K.id);ae.length>0&&C(K=>{const de=new Set(K);for(const Y of ae)de.add(Y);return de})}},[n,J]),k.useEffect(()=>{if(!(u!=null&&u.length)||!(J!=null&&J.length))return;const ae=u.filter(Y=>!g.has(Y)&&!x.has(Y));if(ae.length===0)return;const K=new Set(g),de=new Set(y);for(const Y of ae){K.add(Y);const Q=J.find(X=>X.flags.some(pe=>pe.id===Y));Q&&de.delete(Q.id)}m(K),v(de),w(Y=>new Set([...Y,...ae])),t==null||t([...K],[...de]),n&&fetch(`/api/ingredients/${n}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:[...K]})}).then(()=>{p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredients"]})}).catch(()=>{})},[u,J]),k.useEffect(()=>{var Y,Q;if(!(f!=null&&f.length)||!(J!=null&&J.length))return;const ae=f.filter(X=>!y.has(X)&&!S.has(X));if(ae.length===0)return;const K=new Set(y),de=new Set(g);for(const X of ae)(((Y=J.find(Ne=>Ne.id===X))==null?void 0:Y.flags)||[]).some(Ne=>de.has(Ne.id))||K.add(X);if(v(K),_(X=>new Set([...X,...ae])),t==null||t([...de],[...K]),n){for(const X of ae)(((Q=J.find(Ne=>Ne.id===X))==null?void 0:Q.flags)||[]).some(Ne=>de.has(Ne.id))||fetch(`/api/ingredients/${n}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:X})}).catch(()=>{});p.invalidateQueries({queryKey:["ingredient-flag-nones",n]}),p.invalidateQueries({queryKey:["ingredients"]})}},[f,J]);const De=(ae,K)=>{const de=K.replace(/\s*free$/i,"").trim().toLowerCase(),Y=ae.toLowerCase();return!!(de===Y||de+"s"===Y||de===Y+"s"||Y.endsWith("s")&&de===Y.slice(0,-1))},qe=async(ae,K)=>{const de=new Set(g),Y=new Set(y);if(de.has(ae))de.delete(ae);else{const Q=J==null?void 0:J.find(pe=>pe.id===K),X=Q==null?void 0:Q.flags.find(pe=>pe.id===ae);if(Q&&X&&J){if(Q.propagation_type==="suitable_for"){for(const pe of J)if(pe.propagation_type==="contains"){for(const we of pe.flags)if(de.has(we.id)&&De(we.name,X.name)){alert(`Cannot set "${X.name}" — this ingredient contains ${we.name}. Remove the ${we.name} flag first.`);return}}}if(Q.propagation_type==="contains"){for(const pe of J)if(pe.propagation_type==="suitable_for")for(const we of pe.flags)de.has(we.id)&&De(X.name,we.name)&&de.delete(we.id)}}de.add(ae),Y.delete(K)}if(m(de),v(Y),t==null||t([...de],[...Y]),n){F(!0);try{await fetch(`/api/ingredients/${n}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:[...de]})}),p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredients"]})}catch{}F(!1)}},ue=async ae=>{var Y;const K=new Set(y),de=new Set(g);if(K.has(ae)?K.delete(ae):(K.add(ae),(((Y=J==null?void 0:J.find(X=>X.id===ae))==null?void 0:Y.flags)||[]).forEach(X=>de.delete(X.id))),v(K),m(de),t==null||t([...de],[...K]),n){F(!0);try{await fetch(`/api/ingredients/${n}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:ae})}),p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredient-flag-nones",n]}),p.invalidateQueries({queryKey:["ingredients"]})}catch{}F(!1)}},Ze=ae=>{const K=J==null?void 0:J.find(de=>de.flags.some(Y=>Y.id===ae.flag_id));K&&qe(ae.flag_id,K.id)},ee=async ae=>{if(!U.trim())return;const K={food_flag_id:ae.flag_id,flag_name:ae.flag_name,dismissed_by_name:U.trim(),reason:I.trim()||void 0,matched_keyword:ae.matched_keywords.join(", ")};if(n)try{const Y=await fetch(`/api/ingredients/${n}/flags/dismissals`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(K)});if(Y.ok){const Q=await Y.json();K.id=Q.id}}catch{}const de=[...P,K];L(de),O(null),H(""),r==null||r(de)},Z=async ae=>{const K=P.find(Y=>Y.food_flag_id===ae);if(!K)return;if(n&&K.id)try{await fetch(`/api/ingredients/${n}/flags/dismissals/${K.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}const de=P.filter(Y=>Y.food_flag_id!==ae);L(de),r==null||r(de)},ge=async()=>{const ae=new Set(g),K=new Set(y);for(const de of He){ae.add(de.flag_id);const Y=J==null?void 0:J.find(Q=>Q.flags.some(X=>X.id===de.flag_id));Y&&K.delete(Y.id)}if(m(ae),v(K),t==null||t([...ae],[...K]),n){F(!0);try{await fetch(`/api/ingredients/${n}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:[...ae]})}),p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredients"]})}catch{}F(!1)}};if(!(J!=null&&J.length))return null;const Te=[],Be=new Set;for(const ae of Ye||[])Be.has(ae.flag_id)||(Be.add(ae.flag_id),Te.push(ae));for(const ae of l||[])if(!Be.has(ae.flag_id)){Be.add(ae.flag_id);const K="source"in ae?ae.source:"",de=K&&{contains:"product data",dietary:"product data",keyword:"product data"}[K]||"label";Te.push({...ae,matched_keywords:ae.matched_keywords.map(Y=>`${Y} (${de})`)})}for(const ae of d||[])Be.has(ae.flag_id)||(Be.add(ae.flag_id),Te.push({...ae,matched_keywords:ae.matched_keywords.map(K=>`✨ ${K}`)}));const he=new Set(P.map(ae=>ae.food_flag_id)),He=Te.filter(ae=>!g.has(ae.flag_id)&&!he.has(ae.flag_id)),Ge=J.flatMap(ae=>ae.flags.filter(K=>g.has(K.id)).map(K=>({name:K.name,code:K.code,icon:K.icon,propagation_type:ae.propagation_type})));return s.jsxs("div",{style:{borderTop:"1px solid #eee",padding:"0.75rem 1.25rem"},children:[Ge.length>0&&s.jsx("div",{style:{display:"flex",gap:"3px",flexWrap:"wrap",marginBottom:"0.5rem"},children:Ge.map(ae=>s.jsxs("span",{style:{background:ae.propagation_type==="contains"?"#dc3545":"#28a745",color:"white",padding:"1px 5px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:600},title:ae.name,children:[ae.icon?`${ae.icon} `:"",ae.code||ae.name.substring(0,3)]},ae.name))}),He.length===0&&c&&s.jsxs("div",{style:{padding:"0.3rem 0.5rem",fontSize:"0.73rem",color:"#7c3aed"},children:["✨"," AI analysing ingredients..."]}),He.length>0&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.3rem 0.5rem",background:"#fffbeb",border:"1px solid #f59e0b",borderRadius:A?"6px 6px 0 0":"6px",cursor:"pointer"},onClick:()=>D(!A),children:[s.jsxs("span",{style:{fontSize:"0.73rem",color:"#b45309",fontWeight:600},children:["⚠"," ",He.length," allergen suggestion",He.length!==1?"s":"",c&&s.jsx("span",{style:{marginLeft:"0.4rem",fontSize:"0.68rem",color:"#7c3aed"},children:"\\u2728 AI analysing..."})]}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem",alignItems:"center"},children:[s.jsx("button",{onClick:ae=>{ae.stopPropagation(),ge()},disabled:T,style:{padding:"0.15rem 0.4rem",border:"1px solid #f59e0b",borderRadius:"4px",background:"#f59e0b",color:"white",cursor:T?"default":"pointer",fontSize:"0.68rem",fontWeight:600},children:"Apply All"}),s.jsx("span",{style:{fontSize:"0.7rem",color:"#b45309"},children:A?"▲":"▼"})]})]}),A&&s.jsx("div",{style:{padding:"0.4rem 0.5rem",background:"#fffef5",border:"1px solid #f59e0b",borderTop:"none",borderRadius:"0 0 6px 6px",display:"flex",flexDirection:"column",gap:"0.3rem"},children:He.map(ae=>s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("span",{style:{fontSize:"0.73rem",color:"#555",flex:1},children:[s.jsx("strong",{children:ae.flag_name}),ae.flag_code&&s.jsxs("span",{style:{color:"#888"},children:[" (",ae.flag_code,")"]}),s.jsxs("span",{style:{color:"#999",marginLeft:"0.3rem",fontSize:"0.68rem"},children:["matched: ",ae.matched_keywords.join(", ")]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[s.jsx("button",{onClick:()=>{O(ae.flag_id),H("")},disabled:T,style:{padding:"0.1rem 0.35rem",border:"1px solid #dc3545",borderRadius:"4px",background:"white",cursor:T?"default":"pointer",fontSize:"0.68rem",color:"#dc3545"},children:"Dismiss"}),s.jsx("button",{onClick:()=>Ze(ae),disabled:T,style:{padding:"0.1rem 0.35rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:T?"default":"pointer",fontSize:"0.68rem",color:"#555"},children:"+ Apply"})]})]}),W===ae.flag_id&&s.jsxs("div",{style:{marginTop:"0.25rem",padding:"0.35rem 0.5rem",background:"#fff5f5",border:"1px solid #fca5a5",borderRadius:"4px",display:"flex",flexDirection:"column",gap:"0.25rem"},children:[s.jsx("div",{style:{display:"flex",gap:"0.3rem",alignItems:"center"},children:s.jsx("input",{type:"text",placeholder:"Your name (required)",value:U,onChange:K=>M(K.target.value),style:{flex:1,padding:"0.2rem 0.4rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.73rem"},autoFocus:!0})}),s.jsxs("div",{style:{display:"flex",gap:"0.3rem",alignItems:"center"},children:[s.jsx("input",{type:"text",placeholder:"Reason (optional)",value:I,onChange:K=>H(K.target.value),onKeyDown:K=>{K.key==="Enter"&&U.trim()&&ee(ae)},style:{flex:1,padding:"0.2rem 0.4rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.73rem"}}),s.jsx("button",{onClick:()=>ee(ae),disabled:!U.trim(),style:{padding:"0.15rem 0.4rem",border:"1px solid #dc3545",borderRadius:"4px",background:U.trim()?"#dc3545":"#f0f0f0",color:U.trim()?"white":"#999",cursor:U.trim()?"pointer":"default",fontSize:"0.68rem",fontWeight:600},children:"Confirm"}),s.jsx("button",{onClick:()=>O(null),style:{padding:"0.15rem 0.4rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.68rem",color:"#666"},children:"Cancel"})]})]})]},ae.flag_id))})]}),P.length>0&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsxs("div",{onClick:()=>G(!z),style:{padding:"0.2rem 0.5rem",background:"#f9fafb",border:"1px solid #e5e7eb",borderRadius:z?"6px 6px 0 0":"6px",cursor:"pointer",fontSize:"0.68rem",color:"#888"},children:[P.length," dismissed ",z?"▲":"▼"]}),z&&s.jsx("div",{style:{padding:"0.3rem 0.5rem",background:"#f9fafb",border:"1px solid #e5e7eb",borderTop:"none",borderRadius:"0 0 6px 6px",display:"flex",flexDirection:"column",gap:"0.2rem"},children:P.map(ae=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("span",{style:{fontSize:"0.7rem",color:"#999",textDecoration:"line-through"},children:[ae.flag_name||`Flag #${ae.food_flag_id}`,ae.dismissed_by_name&&s.jsxs("span",{style:{fontStyle:"italic",marginLeft:"0.3rem"},children:["by ",ae.dismissed_by_name]}),ae.reason&&s.jsxs("span",{style:{marginLeft:"0.3rem"},children:["— ",ae.reason]})]}),s.jsx("button",{onClick:()=>Z(ae.food_flag_id),style:{padding:"0.05rem 0.3rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.65rem",color:"#666"},children:"Undo"})]},ae.food_flag_id))})]}),s.jsx("div",{style:{display:"flex",gap:"0.35rem",flexWrap:"wrap",marginBottom:b.size>0?"0.5rem":0},children:J.map(ae=>{const K=ae.flags.filter(X=>g.has(X.id)).length,de=y.has(ae.id),Y=b.has(ae.id),Q=K>0||de;return s.jsxs("button",{onClick:()=>C(X=>{const pe=new Set(X);return pe.has(ae.id)?pe.delete(ae.id):pe.add(ae.id),pe}),style:{padding:"0.25rem 0.5rem",border:`1px solid ${Y?"#555":Q?"#ccc":ae.required?"#f59e0b":"#ddd"}`,borderRadius:"4px",background:Y?"#f0f0f0":"white",cursor:"pointer",fontSize:"0.75rem",fontWeight:Y?600:400,color:Q?"#333":ae.required?"#b45309":"#888"},children:[ae.name,K>0&&s.jsxs("span",{style:{marginLeft:"0.25rem",color:ae.propagation_type==="contains"?"#dc3545":"#28a745",fontWeight:600},children:["(",K,")"]}),de&&s.jsxs("span",{style:{marginLeft:"0.25rem",color:"#888"},children:["(","—",")"]}),!Q&&ae.required&&s.jsx("span",{style:{marginLeft:"0.25rem",color:"#f59e0b"},children:"?"})]},ae.id)})}),J.filter(ae=>b.has(ae.id)).map(ae=>{const K=y.has(ae.id);return s.jsxs("div",{style:{display:"flex",gap:"0.35rem",flexWrap:"wrap",padding:"0.5rem",background:"#fafafa",borderRadius:"6px",border:"1px solid #e0e0e0",alignItems:"center",opacity:T?.6:1,marginBottom:"0.35rem"},children:[s.jsxs("span",{style:{fontSize:"0.7rem",color:"#888",fontWeight:600,marginRight:"0.25rem"},children:[ae.name," (",ae.propagation_type,"):"]}),ae.flags.map(de=>{const Y=g.has(de.id),Q=ae.propagation_type==="contains"?"#dc3545":"#28a745";return s.jsxs("button",{onClick:()=>qe(de.id,ae.id),disabled:T||K,title:de.name,style:{padding:"0.2rem 0.5rem",border:`1.5px solid ${Y?Q:"#ccc"}`,borderRadius:"12px",background:Y?Q:"white",color:Y?"white":K?"#ccc":"#555",cursor:T||K?"default":"pointer",fontSize:"0.73rem",fontWeight:Y?600:400},children:[de.icon?`${de.icon} `:"",de.code||de.name]},de.id)}),s.jsx("button",{onClick:()=>ue(ae.id),disabled:T,style:{padding:"0.2rem 0.5rem",border:`1.5px dashed ${K?"#888":"#ccc"}`,borderRadius:"12px",background:K?"#888":"white",color:K?"white":"#888",cursor:T?"default":"pointer",fontSize:"0.73rem",fontWeight:K?600:400,marginLeft:"0.25rem"},title:"None of these apply",children:"None"})]},ae.id)})]})}function ife({imageFile:n,onCropped:e,onCancel:t}){const r=k.useRef(null),i=k.useRef(null),[o,a]=k.useState(!1),[l,d]=k.useState(!1),[c,u]=k.useState(null),[f,p]=k.useState(null),[g,m]=k.useState({width:0,height:0}),[y,v]=k.useState(0);k.useEffect(()=>{const D=new Image;return D.onload=()=>{i.current=D,a(!0)},D.src=URL.createObjectURL(n),()=>URL.revokeObjectURL(D.src)},[n]),k.useEffect(()=>{const D=i.current;if(!D||!o)return;const P=y===90||y===270,L=P?D.height:D.width,W=P?D.width:D.height,M=Math.min(700/L,500/W,1);m({width:L*M,height:W*M}),p(null)},[o,y]);const x=k.useCallback((D,P,L,W)=>{D.save(),D.translate(L/2,W/2),D.rotate(y*Math.PI/180);const O=y===90||y===270,U=O?W:L,M=O?L:W;D.drawImage(P,-U/2,-M/2,U,M),D.restore()},[y]),w=k.useCallback(()=>{const D=r.current,P=i.current;if(!D||!P)return;const L=D.getContext("2d");L&&(L.clearRect(0,0,D.width,D.height),x(L,P,D.width,D.height),f&&(L.fillStyle="rgba(0,0,0,0.4)",L.fillRect(0,0,D.width,D.height),L.clearRect(f.x,f.y,f.w,f.h),x(L,P,D.width,D.height),L.strokeStyle="#f59e0b",L.lineWidth=2,L.setLineDash([6,3]),L.strokeRect(f.x,f.y,f.w,f.h),L.setLineDash([]),L.fillStyle="rgba(0,0,0,0.4)",L.fillRect(0,0,D.width,f.y),L.fillRect(0,f.y+f.h,D.width,D.height-f.y-f.h),L.fillRect(0,f.y,f.x,f.h),L.fillRect(f.x+f.w,f.y,D.width-f.x-f.w,f.h)))},[f,x]);k.useEffect(()=>{o&&g.width>0&&w()},[o,w,g]);const S=D=>{const L=r.current.getBoundingClientRect(),W="touches"in D?D.touches[0].clientX:D.clientX,O="touches"in D?D.touches[0].clientY:D.clientY;return{x:W-L.left,y:O-L.top}},_=D=>{D.preventDefault();const P=S(D);u(P),p(null),d(!0)},b=D=>{if(!l||!c)return;D.preventDefault();const P=S(D);p({x:Math.min(c.x,P.x),y:Math.min(c.y,P.y),w:Math.abs(P.x-c.x),h:Math.abs(P.y-c.y)})},C=()=>{d(!1)},T=()=>{v(D=>(D+90)%360)},F=()=>{const D=i.current;if(!D||!f||f.w<10||f.h<10)return;const P=y===90||y===270,L=P?D.height:D.width,W=P?D.width:D.height,O=L/g.width,U=W/g.height,M=f.x*O,I=f.y*U,H=f.w*O,z=f.h*U,G=document.createElement("canvas");G.width=L,G.height=W;const te=G.getContext("2d");te.translate(L/2,W/2),te.rotate(y*Math.PI/180);const re=P?W:L,me=P?L:W;te.drawImage(D,-re/2,-me/2,re,me);const J=document.createElement("canvas");J.width=H,J.height=z,J.getContext("2d").drawImage(G,M,I,H,z,0,0,H,z),J.toBlob(ye=>{if(ye){const ke=new File([ye],n.name,{type:"image/jpeg"});e(ke)}},"image/jpeg",.92)},A=()=>{if(y===0){e(n);return}const D=i.current;if(!D){e(n);return}const P=y===90||y===270,L=P?D.height:D.width,W=P?D.width:D.height,O=document.createElement("canvas");O.width=L,O.height=W;const U=O.getContext("2d");U.translate(L/2,W/2),U.rotate(y*Math.PI/180);const M=P?W:L,I=P?L:W;U.drawImage(D,-M/2,-I/2,M,I),O.toBlob(H=>{H&&e(new File([H],n.name,{type:"image/jpeg"}))},"image/jpeg",.92)};return s.jsx("div",{style:Gf.overlay,children:s.jsxs("div",{style:Gf.modal,children:[s.jsxs("div",{style:Gf.header,children:[s.jsx("h3",{style:{margin:0,fontSize:"1rem"},children:"Select Ingredients Area"}),s.jsx("button",{onClick:t,style:Gf.closeBtn,children:"✕"})]}),s.jsxs("div",{style:{padding:"0.5rem",fontSize:"0.8rem",color:"#666",textAlign:"center",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.75rem"},children:[s.jsx("span",{children:"Draw a rectangle around the ingredients list"}),s.jsxs("button",{onClick:T,style:Gf.rotateBtn,title:"Rotate 90°",children:["↻"," Rotate"]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"0.5rem",background:"#f0f0f0"},children:o?s.jsx("canvas",{ref:r,width:g.width,height:g.height,style:{cursor:"crosshair",touchAction:"none",borderRadius:"4px"},onMouseDown:_,onMouseMove:b,onMouseUp:C,onMouseLeave:C,onTouchStart:_,onTouchMove:b,onTouchEnd:C}):s.jsx("div",{style:{padding:"2rem",color:"#888"},children:"Loading image..."})}),s.jsxs("div",{style:Gf.footer,children:[s.jsx("button",{onClick:A,style:Gf.skipBtn,children:"Use Full Image"}),s.jsx("button",{onClick:F,disabled:!f||f.w<10||f.h<10,style:{...Gf.cropBtn,opacity:f&&f.w>=10&&f.h>=10?1:.4,cursor:f&&f.w>=10&&f.h>=10?"pointer":"default"},children:"Crop & Scan"})]})]})})}const Gf={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100},modal:{background:"white",borderRadius:"10px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.1rem",cursor:"pointer",color:"#888"},footer:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"0.75rem 1rem",borderTop:"1px solid #eee"},skipBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",color:"#333",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},cropBtn:{padding:"0.5rem 1rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",fontWeight:600,fontSize:"0.85rem"},rotateBtn:{padding:"0.3rem 0.6rem",background:"white",color:"#555",border:"1px solid #ccc",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",whiteSpace:"nowrap"}},sfe={g:{g:1,kg:.001},kg:{g:1e3,kg:1},oz:{g:28.3495,kg:.0283495},ml:{ml:1,ltr:.001},cl:{ml:10,ltr:.01},ltr:{ml:1e3,ltr:1},each:{each:1}};function ofe(n,e,t,r,i){var u;if(!e||!t)return"";const o=(u=sfe[t])==null?void 0:u[r];if(!o)return t!==r?`Cannot convert ${t} → ${r}`:"";const a=n*e*o,l=i?i/a:null;let c=`${n>1?`${n} × ${e}${t} = `:""}${a.toFixed(a%1?2:0)} ${r}`;return l&&(c+=` → £${l.toFixed(4)} per ${r}`,r==="g"?c+=` (£${(l*1e3).toFixed(2)}/kg)`:r==="ml"&&(c+=` (£${(l*1e3).toFixed(2)}/ltr)`)),c}function J2(n){const e=n.match(/(\d+)\s*[x\u00d7]\s*(\d+(?:\.\d+)?)\s*(g|kg|ml|ltr|l|oz|cl|gm|gms)\b/i);if(e){let r=e[3].toLowerCase();return r==="l"&&(r="ltr"),(r==="gm"||r==="gms")&&(r="g"),{qty:parseInt(e[1]),size:e[2],type:r}}const t=n.match(/(\d+(?:\.\d+)?)\s*(g|kg|ml|ltr|l|oz|cl|gm|gms|gram|grams|kilo|kilos|kilogram|litre|litres|liter)\b/i);if(t){let r=t[2].toLowerCase();return(r==="l"||r==="litre"||r==="litres"||r==="liter")&&(r="ltr"),(r==="gm"||r==="gms"||r==="gram"||r==="grams")&&(r="g"),(r==="kilo"||r==="kilos"||r==="kilogram")&&(r="kg"),{qty:1,size:t[1],type:r}}return null}const afe=[{key:"brakes",namePattern:/brakes/i,label:"Fetch Brakes",color:"#f59e0b",endpoint:"/api/food-flags/brakes-lookup",paramName:"product_code"}];function VP(n){return n&&afe.find(e=>e.namePattern.test(n))||null}const lfe=new Set(["brakes","brake","bidfood","the","a","an","and","or","of","for","with","in","per","pack","pkt","case","cs","box","bag","tub","tin","jar","btl","bottle","x","pk","ea","each"]);function ON(n){return new Set(n.toLowerCase().replace(/[^a-z0-9%]+/g," ").split(/\s+/).filter(e=>e.length>=2&&!lfe.has(e)))}function dfe(n,e){const t=ON(n),r=ON(e);if(t.size===0||r.size===0)return 0;let i=0;for(const a of t){if(r.has(a)){i++;continue}for(const l of r)if(a.length>=4&&l.length>=4&&(a.includes(l)||l.includes(a))){i+=.5;break}}const o=Math.min(t.size,r.size);return Math.round(i/o*100)}function A0({open:n,onClose:e,onSaved:t,editingIngredient:r,prePopulateName:i,preSelectLineItem:o}){var gi;const{token:a}=gn(),l=pi(),d=je=>je==="each"?"count":["g","kg","oz"].includes(je)?"weight":["ml","ltr","cl"].includes(je)?"volume":"unknown",[c,u]=k.useState(""),[f,p]=k.useState(""),[g,m]=k.useState("g"),[y,v]=k.useState("100"),[x,w]=k.useState(""),[S,_]=k.useState(""),[b,C]=k.useState([]),[T,F]=k.useState(""),[A,D]=k.useState(""),[P,L]=k.useState(null),[W,O]=k.useState(1),[U,M]=k.useState(""),[I,H]=k.useState("g"),[z,G]=k.useState(""),[te,re]=k.useState([]),[me,J]=k.useState([]),[ne,ye]=k.useState(!1),[ke,Ye]=k.useState(!1),[De,qe]=k.useState(""),[ue,Ze]=k.useState(null),[ee,Z]=k.useState(!1),[ge,Te]=k.useState(null),[Be,he]=k.useState(!1),[He,Ge]=k.useState(!1),[ae,K]=k.useState(null),[de,Y]=k.useState(!1),[Q,X]=k.useState(""),[pe,we]=k.useState([]),[Ne,st]=k.useState([]),[Ve,Re]=k.useState(null),[Le,rt]=k.useState([]),[$e,ce]=k.useState(null),[Je,jt]=k.useState(!1),[ct,Se]=k.useState([]),ot=Rg(De,1e3),[ut,Ot]=k.useState(!1),[An,on]=k.useState(null),[Ke,Rt]=k.useState(null),[vt,Cr]=k.useState(!1),Qt=Rg(c,1200),{data:Ci}=Oe({queryKey:["ingredient-categories"],queryFn:async()=>{const je=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${a}`}});if(!je.ok)throw new Error("Failed to fetch categories");return je.json()},enabled:!!a&&n}),{data:Lr}=Oe({queryKey:["suppliers"],queryFn:async()=>{const je=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${a}`}});if(!je.ok)return[];const bt=await je.json();return bt.suppliers||bt||[]},enabled:!!a&&n}),{data:Gs}=Oe({queryKey:["ingredient-sources",r==null?void 0:r.id],queryFn:async()=>{const je=await fetch(`/api/ingredients/${r.id}/sources`,{headers:{Authorization:`Bearer ${a}`}});return je.ok?je.json():[]},enabled:!!a&&n&&!!r}),Ai=Rg(T,300),{data:Ks,isLoading:un}=Oe({queryKey:["ing-modal-li-search",Ai,A],queryFn:async()=>{const je=new URLSearchParams;Ai&&je.set("q",Ai),A&&je.set("supplier_id",A),je.set("limit","100");const bt=await fetch(`/api/search/line-items?${je}`,{headers:{Authorization:`Bearer ${a}`}});return bt.ok?bt.json():{items:[],total_count:0}},enabled:!!a&&n&&Ai.length>=2}),{data:Fr}=Oe({queryKey:["settings-llm-check"],queryFn:async()=>{const je=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${a}`}});return je.ok?je.json():{llm_enabled:!1}},enabled:!!a&&n,staleTime:6e4}),zi=(Fr==null?void 0:Fr.llm_enabled)??!1;k.useEffect(()=>{if(!zi||!ot||ot.trim().length<10){Se([]);return}let je=!1;return(async()=>{var yn;jt(!0);try{const tn=await fetch("/api/food-flags/analyse-label",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({ingredients_text:ot})});if(tn.ok&&!je){const ci=await tn.json();((yn=ci.suggestions)==null?void 0:yn.length)>0?Se(ci.suggestions.map(hn=>({flag_id:hn.flag_id,flag_name:hn.flag_name,flag_code:hn.flag_code,category_name:hn.category_name,matched_keywords:[hn.status==="may_contain"?`may contain: ${hn.reason}`:hn.reason]}))):Se([])}}catch{}je||jt(!1)})(),()=>{je=!0}},[zi,ot,a]),k.useEffect(()=>{if(!zi||r||!Qt||Qt.trim().length<3){Rt(null);return}let je=!1;return(async()=>{Cr(!0);try{const yn=await fetch(`/api/ingredients/ai-estimate-yield?name=${encodeURIComponent(Qt.trim())}`,{headers:{Authorization:`Bearer ${a}`}});if(yn.ok&&!je){const tn=await yn.json();(tn.llm_status==="success"||tn.llm_status==="cached")&&tn.yield_percent?Rt({percent:tn.yield_percent,reason:tn.reason||""}):Rt(null)}}catch{}je||Cr(!1)})(),()=>{je=!0}},[zi,r,Qt,a]);const aa=je=>P!=null&&je.product_code===P.product_code&&je.description===P.description&&je.supplier_id===P.supplier_id,Oi=k.useMemo(()=>{const je=parseFloat(U);if(!je||!I||!P)return"";const bt=P.most_recent_price!=null?Number(P.most_recent_price):null;return ofe(W,je,I,g,bt)},[W,U,I,g,P]),Vd=()=>{u(""),p(""),m("g"),v("100"),w(""),_(""),C([]),F(""),D(""),L(null),O(1),M(""),H("g"),G(""),re([]),J([]),ye(!1),Ye(!1),qe(""),Ze(null),Z(!1),Te(null),he(!1),Ge(!1),K(null),Y(!1),X(""),we([]),st([]),Re(null),rt([]),ce(null),jt(!1),Se([]),Rt(null),Cr(!1)},Gn=()=>{Vd(),e()},Dr=k.useMemo(()=>VP(P==null?void 0:P.supplier_name),[P==null?void 0:P.supplier_name]),xr=k.useMemo(()=>!Ve||Ve==="NOT FOUND"||!(P!=null&&P.description)?null:dfe(Ve,P.description),[Ve,P==null?void 0:P.description]),Ss=async(je,bt,yn=!1)=>{var tn,ci,hn;Y(!0);try{const Ti=new URLSearchParams({[bt.paramName]:je});yn&&Ti.set("force","true");const js=await fetch(`${bt.endpoint}?${Ti}`,{headers:{Authorization:`Bearer ${a}`}});if(js.ok){const Ar=await js.json();if(Ar.found){Ye(!0),Re(Ar.product_name||null);let fs=Ar.ingredients_text||"";((tn=Ar.contains_allergens)==null?void 0:tn.length)>0?fs+=` Contains: ${Ar.contains_allergens.join(", ")}`:fs&&(fs+=` Contains: None of the 14 Food Allergens`),((ci=Ar.suitable_for)==null?void 0:ci.length)>0&&(fs+=` Suitable for: ${Ar.suitable_for.join(", ")}`),qe(fs),Ze({raw_text:Ar.ingredients_text||"",suggested_flags:Ar.suggested_flags||[]});const Qs=(Ar.suggested_flags||[]).filter(Lo=>Lo.source==="contains"||Lo.source==="dietary").map(Lo=>Lo.flag_id);Qs.length>0&&we(Qs),((hn=Ar.none_category_ids)==null?void 0:hn.length)>0&&st(Ar.none_category_ids)}else Re("NOT FOUND")}}catch{}Y(!1)},rs=async je=>{Z(!0),Ze(null);try{const bt=new FormData;bt.append("file",je);const yn=new FileReader;yn.onload=hn=>{var Ti;return Te((Ti=hn.target)==null?void 0:Ti.result)},yn.readAsDataURL(je);const tn=r?`/api/food-flags/scan-label/${r.id}`:"/api/food-flags/scan-label",ci=await fetch(tn,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:bt});if(ci.ok){const hn=await ci.json();Ze(hn),hn.raw_text&&qe(hn.raw_text)}}catch{}Z(!1)},Xs=async je=>{if(!(!P||!a))try{const bt={supplier_id:P.supplier_id,pack_quantity:W||1,unit_size:parseFloat(U)||null,unit_size_type:I||null,apply_to_existing:!0};P.product_code?bt.product_code=P.product_code:P.description&&(bt.description_pattern=P.description.substring(0,100).toLowerCase().trim()),P.most_recent_price&&(bt.latest_unit_price=P.most_recent_price),P.most_recent_invoice_id&&(bt.invoice_id=P.most_recent_invoice_id);const yn=await fetch(`/api/ingredients/${je}/sources`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(bt)});if(!yn.ok){const tn=await yn.json().catch(()=>({}));G(tn.detail||"Saved but source mapping failed")}}catch{G("Saved but source mapping failed (network error)")}},Jt=async je=>{if(te.length>0)try{await fetch(`/api/ingredients/${je}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:te})})}catch{}for(const bt of me)try{await fetch(`/api/ingredients/${je}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:bt})})}catch{}if(Le.length>0)try{await fetch(`/api/ingredients/${je}/flags/dismissals/batch`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({dismissals:Le})})}catch{}};k.useEffect(()=>{var je,bt;if(n)if(Ot(!1),on(null),r)u(r.name),p(((je=r.category_id)==null?void 0:je.toString())||""),m(r.standard_unit),v(r.yield_percent.toString()),w(((bt=r.manual_price)==null?void 0:bt.toString())||""),_(r.notes||""),ye(r.is_free||!1),Ye(r.is_prepackaged||!1),qe(r.product_ingredients||""),Te(r.has_label_image?`/api/ingredients/${r.id}/label-image?token=${encodeURIComponent(a||"")}`:null),F(r.name);else{const yn=i||"";if(u(yn),F((o==null?void 0:o.description)||yn),o){if(L(o),o.most_recent_pack_quantity&&o.most_recent_unit_size)O(o.most_recent_pack_quantity),M(Number(o.most_recent_unit_size).toString()),H(o.most_recent_unit_size_type||"g");else{const ci=J2(o.description||"");ci?(O(ci.qty),M(ci.size),H(ci.type)):o.description&&(Ot(!0),fetch(`/api/ingredients/ai-pack-size?description=${encodeURIComponent(o.description)}`,{headers:{Authorization:`Bearer ${a}`}}).then(hn=>hn.ok?hn.json():null).then(hn=>{hn!=null&&hn.pack_quantity&&(hn!=null&&hn.unit_size)&&(O(hn.pack_quantity),M(String(hn.unit_size)),H(hn.unit_size_type||"g"),on(hn.source))}).catch(()=>{}).finally(()=>Ot(!1)))}VP(o.supplier_name)&&o.product_code&&(X(o.product_code),ce(o.product_code))}}},[n]),k.useEffect(()=>{if($e&&a&&Dr){const je=$e;ce(null),Ss(je,Dr)}},[$e,a,Dr]),k.useEffect(()=>{if(!c||c.length<3||!a||!n){C([]);return}const je=setTimeout(async()=>{try{const bt=await fetch(`/api/ingredients/check-duplicate?name=${encodeURIComponent(c)}`,{headers:{Authorization:`Bearer ${a}`}});if(bt.ok){const yn=await bt.json();C(yn.filter(tn=>r?tn.id!==r.id:!0))}}catch{}},500);return()=>clearTimeout(je)},[c,a,r==null?void 0:r.id,n]);const Ys=Ue({mutationFn:async je=>{const bt=await fetch("/api/ingredients",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(je)});if(!bt.ok){const yn=await bt.json().catch(()=>({}));throw new Error(yn.detail||"Failed to create")}return bt.json()},onSuccess:async je=>{P&&await Xs(je.id),await Jt(je.id),l.invalidateQueries({queryKey:["ingredients"]}),l.invalidateQueries({queryKey:["ingredient-sources"]}),t==null||t({id:je.id,name:je.name,standard_unit:je.standard_unit}),Gn()}}),Ft=Ue({mutationFn:async({id:je,data:bt})=>{const yn=await fetch(`/api/ingredients/${je}`,{method:"PATCH",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(bt)});if(!yn.ok)throw new Error("Failed to update");return yn.json()},onSuccess:async(je,bt)=>{P&&await Xs(bt.id),l.invalidateQueries({queryKey:["ingredients"]}),l.invalidateQueries({queryKey:["ingredient-sources"]}),t==null||t({id:bt.id,name:c,standard_unit:g}),Gn()}}),Ea=()=>{const je={name:c,category_id:f?parseInt(f):null,standard_unit:g,yield_percent:parseFloat(y),manual_price:!P&&x?parseFloat(x):null,notes:S||null,is_free:ne,is_prepackaged:ke,product_ingredients:ke&&De||null};r?Ft.mutate({id:r.id,data:je}):Ys.mutate(je)},zn=je=>{if(L(je),w(""),je.most_recent_pack_quantity&&je.most_recent_unit_size)O(je.most_recent_pack_quantity),M(Number(je.most_recent_unit_size).toString()),H(je.most_recent_unit_size_type||g);else{const yn=J2(je.description||"");yn?(O(yn.qty),M(yn.size),H(yn.type)):(O(1),M(""),H(g))}const bt=VP(je.supplier_name);bt&&je.product_code&&(X(je.product_code),Ss(je.product_code,bt))};return n?s.jsxs("div",{style:cr.overlay,children:[s.jsxs("div",{style:{...cr.modal,width:"850px"},children:[s.jsxs("div",{style:cr.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:r?"Edit Ingredient":"Create Ingredient"}),s.jsx("button",{onClick:Gn,style:cr.closeBtn,children:"✕"})]}),s.jsxs("div",{style:{...cr.modalBody,display:"flex",gap:"1.5rem"},children:[s.jsxs("div",{style:{flex:"0 0 280px"},children:[s.jsx("label",{style:cr.label,children:"Name *"}),s.jsx("input",{value:c,onChange:je=>u(je.target.value),style:cr.input,placeholder:"e.g. Butter, Minced Beef 80/20"}),b.length>0&&s.jsxs("div",{style:cr.warning,children:["Similar ingredients exist: ",b.map(je=>`${je.name} (${Math.round(je.similarity*100)}%)`).join(", ")]}),s.jsxs("div",{style:{display:"flex",marginTop:"0.6rem",borderRadius:"6px",overflow:"hidden",border:"1px solid #ddd"},children:[s.jsx("button",{type:"button",onClick:()=>Ye(!1),style:{flex:1,padding:"0.4rem 0.5rem",border:"none",background:ke?"#f5f5f5":"#1a1a2e",color:ke?"#888":"white",fontSize:"0.72rem",fontWeight:600,cursor:"pointer",letterSpacing:"0.03em"},children:"RAW INGREDIENT"}),s.jsx("button",{type:"button",onClick:()=>Ye(!0),style:{flex:1,padding:"0.4rem 0.5rem",border:"none",borderLeft:"1px solid #ddd",background:ke?"#6366f1":"#f5f5f5",color:ke?"white":"#888",fontSize:"0.72rem",fontWeight:600,cursor:"pointer",letterSpacing:"0.03em"},children:"PACKAGED PRODUCT"})]}),s.jsx("label",{style:cr.label,children:"Category"}),s.jsxs("select",{value:f,onChange:je=>p(je.target.value),style:cr.input,children:[s.jsx("option",{value:"",children:"None"}),Ci==null?void 0:Ci.map(je=>s.jsx("option",{value:je.id,children:je.name},je.id))]}),s.jsxs("div",{style:cr.row,children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("label",{style:cr.label,children:"Standard Unit"}),s.jsxs("select",{value:g,onChange:je=>{const bt=je.target.value;m(bt);const yn=d(bt),tn=d(I);yn!==tn&&(H(bt),bt==="each"&&M("1"))},style:cr.input,children:[s.jsx("option",{value:"g",children:"g (grams)"}),s.jsx("option",{value:"kg",children:"kg (kilograms)"}),s.jsx("option",{value:"ml",children:"ml (millilitres)"}),s.jsx("option",{value:"ltr",children:"ltr (litres)"}),s.jsx("option",{value:"each",children:"each"})]})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("label",{style:cr.label,children:"Yield %"}),s.jsx("input",{type:"number",value:y,onChange:je=>v(je.target.value),style:cr.input,min:"1",max:"100",step:"0.5"}),vt&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#7952b3",marginTop:"0.25rem"},children:"Estimating yield..."}),Ke&&!vt&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#7952b3",marginTop:"0.25rem"},children:["Typical yield: ~",Ke.percent,"%"," ",s.jsx("button",{type:"button",onClick:()=>v(Ke.percent.toString()),style:{background:"none",border:"none",color:"#7952b3",textDecoration:"underline",cursor:"pointer",fontSize:"0.75rem",padding:0},children:"Apply"}),Ke.reason&&s.jsxs("span",{style:{color:"#999",marginLeft:"0.25rem"},children:["(",Ke.reason,")"]})]})]})]}),!P&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{style:cr.label,children:["Manual Price (per ",g,", optional)"]}),s.jsx("input",{type:"number",value:x,onChange:je=>w(je.target.value),style:cr.input,step:"0.0001",placeholder:"Only if no line item linked"})]}),P&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.4rem 0.6rem",background:"#e8f5e9",borderRadius:"6px",fontSize:"0.8rem",color:"#2e7d32"},children:"Price from supplier source"}),s.jsx("label",{style:cr.label,children:"Notes"}),s.jsx("textarea",{value:S,onChange:je=>_(je.target.value),style:{...cr.input,minHeight:"50px"},placeholder:"Optional notes..."}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.4rem",marginTop:"0.5rem",fontSize:"0.82rem",color:"#555",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:ne,onChange:je=>ye(je.target.checked)}),"Free item (no cost — e.g. water, tap water)"]}),ke&&s.jsxs("div",{style:{marginTop:"0.5rem",padding:"0.5rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsx("label",{style:{...cr.label,marginTop:0},children:"Product Ingredients"}),s.jsx("textarea",{value:De,onChange:je=>qe(je.target.value),style:{...cr.input,minHeight:"60px",fontSize:"0.8rem"},placeholder:"Ingredients list from product label..."}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem",marginTop:"0.35rem"},children:[s.jsxs("label",{style:{padding:"0.3rem 0.6rem",border:"1px solid #6366f1",borderRadius:"4px",background:ee?"#e0e0e0":"#6366f1",color:"white",cursor:ee?"default":"pointer",fontSize:"0.75rem",fontWeight:600,display:"inline-flex",alignItems:"center",gap:"0.25rem"},children:[ee?"Scanning...":"📷 Scan Label",s.jsx("input",{type:"file",accept:"image/*",capture:"environment",style:{display:"none"},onChange:je=>{var yn;const bt=(yn=je.target.files)==null?void 0:yn[0];bt&&K(bt),je.target.value=""},disabled:ee})]}),ge&&s.jsxs("button",{onClick:()=>he(!0),style:{padding:"0.3rem 0.6rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem",color:"#555"},children:["🖼"," View Label"]})]}),ee&&s.jsx("div",{style:{marginTop:"0.35rem",fontSize:"0.75rem",color:"#6366f1"},children:"Analysing label image..."})]})]}),s.jsxs("div",{style:{flex:1,borderLeft:"1px solid #eee",paddingLeft:"1.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,marginBottom:"0.5rem",color:"#555"},children:"Link to Supplier Line Item"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#888",marginBottom:"0.5rem"},children:"Optional — search invoiced items to auto-map pricing"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"0.5rem"},children:[s.jsx("input",{value:T,onChange:je=>{F(je.target.value),L(null),G("")},style:{...cr.input,flex:2},placeholder:"Search line items..."}),s.jsxs("select",{value:A,onChange:je=>D(je.target.value),style:{...cr.input,flex:1,minWidth:"120px"},children:[s.jsx("option",{value:"",children:"All Suppliers"}),Lr==null?void 0:Lr.map(je=>s.jsx("option",{value:je.id,children:je.name},je.id))]})]}),r&&Gs&&Gs.length>0&&!P&&s.jsxs("div",{style:{border:"1px solid #c8e6c9",borderRadius:"6px",marginBottom:"0.5rem",background:"#f1f8e9"},children:[s.jsx("div",{style:{padding:"0.3rem 0.5rem",fontSize:"0.7rem",fontWeight:600,color:"#558b2f",borderBottom:"1px solid #c8e6c9"},children:"Linked Sources"}),Gs.map(je=>s.jsxs("div",{style:{padding:"0.3rem 0.5rem",fontSize:"0.78rem",display:"flex",justifyContent:"space-between",alignItems:"center",borderBottom:"1px solid #e8f5e9"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#666",fontSize:"0.73rem",marginRight:"0.3rem"},children:je.supplier_name}),je.product_code&&s.jsx("span",{style:{color:"#888",fontSize:"0.68rem",marginRight:"0.25rem"},children:je.product_code}),je.description_pattern||"-"]}),s.jsxs("span",{style:{fontSize:"0.73rem",color:"#666"},children:[je.latest_unit_price!=null?`£${Number(je.latest_unit_price).toFixed(2)}`:"",je.pack_quantity?` (${je.pack_quantity}x${je.unit_size||"?"}${je.unit_size_type||""})`:""]})]},je.id))]}),Ai.length>=2&&s.jsx("div",{style:{maxHeight:"180px",overflow:"auto",border:"1px solid #e0e0e0",borderRadius:"6px",marginBottom:"0.5rem"},children:un?s.jsx("div",{style:{padding:"0.75rem",color:"#888",textAlign:"center",fontSize:"0.85rem"},children:"Searching..."}):Ks!=null&&Ks.items.length?s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.78rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:cr.liTh,children:"Supplier"}),s.jsx("th",{style:cr.liTh,children:"Description"}),s.jsx("th",{style:{...cr.liTh,textAlign:"right"},children:"Unit Price"}),s.jsx("th",{style:{...cr.liTh,textAlign:"center"}})]})}),s.jsx("tbody",{children:Ks.items.map((je,bt)=>s.jsxs("tr",{style:{borderBottom:"1px solid #f0f0f0",background:aa(je)?"#e8f5e9":void 0},children:[s.jsx("td",{style:{padding:"0.3rem 0.5rem",fontSize:"0.73rem",color:"#666"},children:je.supplier_name||"-"}),s.jsxs("td",{style:{padding:"0.3rem 0.5rem"},children:[je.product_code&&s.jsx("span",{style:{color:"#888",fontSize:"0.68rem",marginRight:"0.25rem"},children:je.product_code}),je.description]}),s.jsx("td",{style:{padding:"0.3rem 0.5rem",textAlign:"right",whiteSpace:"nowrap"},children:je.most_recent_price!=null?`£${Number(je.most_recent_price).toFixed(2)}`:"-"}),s.jsx("td",{style:{padding:"0.35rem 0.5rem",textAlign:"center"},children:s.jsx("button",{onClick:()=>zn(je),style:{background:"none",border:"none",cursor:"pointer",fontSize:"1rem",padding:"0.15rem 0.3rem",borderRadius:"4px",color:aa(je)?"#2e7d32":je.ingredient_id!=null?"#22c55e":J2(je.description||"")?"#f59e0b":"#ef4444"},title:aa(je)?"Selected":je.ingredient_id!=null?`Mapped to ${je.ingredient_name}`:J2(je.description||"")?"Pack info detected":"No pack info — manual entry needed",children:"⚖"})})]},`${je.product_code||""}-${je.supplier_id}-${bt}`))})]}):s.jsx("div",{style:{padding:"0.75rem",color:"#888",textAlign:"center",fontSize:"0.85rem"},children:"No line items found"})}),P&&P.most_recent_line_number!=null&&s.jsx("div",{style:{marginTop:"0.5rem",borderRadius:"6px",overflow:"hidden",border:"1px solid #e0e0e0",cursor:"pointer"},onClick:()=>Ge(!0),title:"Click to enlarge",children:s.jsx("img",{src:`/api/invoices/${P.most_recent_invoice_id}/line-items/${P.most_recent_line_number}/preview?token=${encodeURIComponent(a||"")}`,alt:"Invoice line item",style:{width:"100%",height:"auto",display:"block"},onError:je=>{je.target.parentElement.style.display="none"}})}),P&&s.jsxs("div",{style:{background:"#f8f9fa",padding:"0.6rem",borderRadius:"6px",marginTop:"0.25rem"},children:[s.jsxs("div",{style:{fontSize:"0.8rem",fontWeight:600,marginBottom:"0.35rem"},children:["✓"," ",P.description,s.jsxs("button",{onClick:()=>{L(null),G("")},style:{background:"none",border:"none",cursor:"pointer",color:"#c62828",fontSize:"0.75rem",marginLeft:"0.5rem"},children:["✕"," remove"]})]}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#666",marginBottom:"0.35rem"},children:[P.supplier_name,P.most_recent_price!=null?` — £${Number(P.most_recent_price).toFixed(2)}`:""]}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"flex-end"},children:[s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{fontSize:"0.65rem",fontWeight:600,color:"#888",marginBottom:"0.15rem"},children:["Contains",ut&&s.jsx("span",{style:{marginLeft:"3px",color:"#7952b3"},children:"..."}),An==="ai"&&s.jsx("span",{style:{marginLeft:"3px"},title:"Deduced by AI",children:"✨"})]}),s.jsx("input",{type:"number",value:U,onChange:je=>M(je.target.value),style:cr.input,step:"0.1",min:"0",placeholder:"Size"})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:600,color:"#888",marginBottom:"0.15rem"},children:"Unit"}),s.jsxs("select",{value:I,onChange:je=>{const bt=je.target.value;H(bt);const yn=d(bt),tn=d(g);yn!==tn&&(m(bt==="cl"?"ml":bt==="oz"?"g":bt),bt==="each"&&M("1"))},style:cr.input,children:[s.jsx("option",{value:"each",children:"each"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"}),s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"oz",children:"oz"}),s.jsx("option",{value:"cl",children:"cl"})]})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:600,color:"#888",marginBottom:"0.15rem"},children:"Pack of"}),s.jsx("input",{type:"number",value:W,onChange:je=>O(parseInt(je.target.value)||1),style:cr.input,min:"1",step:"1"})]})]}),Oi&&s.jsx("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:"#e8f5e9",borderRadius:"4px",fontSize:"0.8rem",color:"#2e7d32",fontWeight:500},children:Oi})]}),P&&Dr&&s.jsxs("div",{style:{marginTop:"0.5rem",padding:"0.5rem",background:"#fefce8",borderRadius:"6px",border:`1px solid ${Dr.color}33`},children:[s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"stretch"},children:[P.most_recent_line_number!=null&&s.jsx("div",{style:{flex:"0 0 auto",maxWidth:"120px",borderRadius:"4px",overflow:"hidden",border:"1px solid #e0e0e0"},children:s.jsx("img",{src:`/api/invoices/${P.most_recent_invoice_id}/line-items/${P.most_recent_line_number}/preview/field/product_code?token=${encodeURIComponent(a||"")}`,alt:"Product code from invoice",style:{width:"100%",height:"auto",display:"block"},onError:je=>{je.target.parentElement.style.display="none"}})}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},children:[de&&s.jsx("div",{style:{fontSize:"0.72rem",color:Dr.color},children:"Fetching product data..."}),s.jsxs("div",{style:{display:"flex",gap:"0.3rem",alignItems:"center"},children:[s.jsx("input",{value:Q,onChange:je=>X(je.target.value),style:{...cr.input,flex:1,fontSize:"0.75rem",padding:"0.25rem 0.4rem"},placeholder:"Product code",onKeyDown:je=>{je.key==="Enter"&&Q.trim()&&Ss(Q.trim(),Dr,!0)}}),s.jsx("button",{onClick:()=>{Q.trim()&&Ss(Q.trim(),Dr,!0)},disabled:!Q.trim()||de,style:{padding:"0.25rem 0.5rem",border:`1px solid ${Dr.color}`,borderRadius:"4px",background:de?"#e0e0e0":Dr.color,color:"white",cursor:de?"default":"pointer",fontSize:"0.7rem",fontWeight:600,whiteSpace:"nowrap"},children:Dr.label})]})]})]}),Ve==="NOT FOUND"&&s.jsx("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:"#fdecea",border:"1px solid #ef9a9a",borderRadius:"4px",fontSize:"0.72rem",color:"#c62828"},children:"Product not found on Brakes website — SKU may be incorrect"}),Ve&&Ve!=="NOT FOUND"&&s.jsxs("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:xr!==null&&xr<30?"#fdecea":xr!==null&&xr<60?"#fffbeb":"#e8f5e9",border:`1px solid ${xr!==null&&xr<30?"#ef9a9a":xr!==null&&xr<60?"#f59e0b55":"#a5d6a7"}`,borderRadius:"4px",fontSize:"0.72rem",color:xr!==null&&xr<30?"#c62828":xr!==null&&xr<60?"#b45309":"#2e7d32"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem",marginBottom:pe.length>0||Ne.length>0?"0.2rem":0},children:[s.jsxs("span",{style:{flex:1},children:[s.jsx("span",{style:{fontWeight:600},children:"Matched: "}),Ve]}),xr!==null&&s.jsxs("span",{style:{fontWeight:700,fontSize:"0.68rem",padding:"0.1rem 0.35rem",borderRadius:"3px",background:xr<30?"#c6282822":xr<60?"#b4530922":"#2e7d3222",whiteSpace:"nowrap"},children:[xr,"% match"]})]}),xr!==null&&xr<30&&s.jsx("div",{style:{fontSize:"0.68rem",fontStyle:"italic",marginBottom:"0.15rem"},children:"Product name doesn't match line item — verify SKU is correct"}),pe.length>0&&(ue==null?void 0:ue.suggested_flags)&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontWeight:600},children:"Auto-flagged: "}),ue.suggested_flags.filter(je=>pe.includes(je.flag_id)).map(je=>je.flag_name).join(", ")]}),Ne.length>0&&s.jsxs("span",{children:[pe.length>0?" | ":"",s.jsx("span",{style:{fontWeight:600},children:"None of 14 allergens: "}),"allergen categories set to None"]})]})]}),z&&s.jsx("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:"#fdecea",borderRadius:"4px",fontSize:"0.8rem",color:"#c62828"},children:z})]})]}),s.jsx(rfe,{ingredientId:(r==null?void 0:r.id)??null,token:a||"",onChange:(je,bt)=>{re(je),J(bt)},onDismissalsChange:je=>rt(je),ingredientName:c,productIngredients:ke?De:void 0,lineItemDescription:(P==null?void 0:P.description)||void 0,scanSuggestions:ue==null?void 0:ue.suggested_flags,llmSuggestions:zi?ct:void 0,llmAnalysing:zi?Je:!1,autoApplyFlagIds:pe,autoApplyNoneCategoryIds:Ne}),s.jsxs("div",{style:cr.modalFooter,children:[s.jsx("button",{onClick:Gn,style:cr.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:Ea,disabled:!c||Ys.isPending||Ft.isPending,style:cr.primaryBtn,children:Ys.isPending||Ft.isPending?"Saving...":P?r?"Save & Map":"Create & Map":"Save"})]}),(Ys.error||Ft.error)&&s.jsx("div",{style:{padding:"0 1.25rem 0.75rem"},children:s.jsx("div",{style:cr.errorMsg,children:(gi=Ys.error||Ft.error)==null?void 0:gi.message})})]}),ae&&s.jsx(ife,{imageFile:ae,onCropped:je=>{K(null),rs(je)},onCancel:()=>K(null)}),Be&&ge&&s.jsx("div",{onClick:()=>he(!1),style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1200,cursor:"pointer"},children:s.jsxs("div",{onClick:je=>je.stopPropagation(),style:{position:"relative",maxWidth:"90vw",maxHeight:"90vh"},children:[s.jsx("button",{onClick:()=>he(!1),style:{position:"absolute",top:"-12px",right:"-12px",width:"28px",height:"28px",borderRadius:"50%",background:"white",border:"1px solid #ccc",cursor:"pointer",fontSize:"0.9rem",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",zIndex:1},children:"✕"}),s.jsx("img",{src:ge,alt:"Product label",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"}})]})}),He&&(P==null?void 0:P.most_recent_line_number)!=null&&s.jsx("div",{onClick:()=>Ge(!1),style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1200,cursor:"pointer"},children:s.jsxs("div",{onClick:je=>je.stopPropagation(),style:{position:"relative",maxWidth:"95vw",maxHeight:"90vh"},children:[s.jsx("button",{onClick:()=>Ge(!1),style:{position:"absolute",top:"-12px",right:"-12px",width:"28px",height:"28px",borderRadius:"50%",background:"white",border:"1px solid #ccc",cursor:"pointer",fontSize:"0.9rem",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",zIndex:1},children:"✕"}),s.jsx("img",{src:`/api/invoices/${P.most_recent_invoice_id}/line-items/${P.most_recent_line_number}/preview?token=${encodeURIComponent(a||"")}`,alt:"Invoice line item",style:{maxWidth:"95vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"}})]})})]}):null}const cr={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"500px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},row:{display:"flex",gap:"0.75rem"},warning:{background:"#fff3cd",color:"#856404",padding:"0.5rem 0.75rem",borderRadius:"6px",fontSize:"0.8rem",marginTop:"0.35rem"},errorMsg:{padding:"0.75rem 1.25rem",color:"#dc3545",fontSize:"0.85rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},liTh:{padding:"0.35rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.7rem",fontWeight:600,color:"#555",position:"sticky",top:0}};Bu.workerSrc="/pdf.worker.min.mjs";const cfe=({style:n})=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",style:{width:"18px",height:"18px",...n},children:s.jsx("path",{d:"M12 3c-1.27 0-2.4.8-2.82 2H3v2h1.95L2 14c-.47 2 1 4 4 4s4.5-2 4-4L7.05 7H9.18c.35.99 1.17 1.74 2.18 1.94V19H7v2h10v-2h-4.18V8.94c1.01-.2 1.83-.95 2.18-1.94h2.13L14 14c-.47 2 1 4 4 4s4.5-2 4-4l-2.95-7H21V5h-6.18C14.4 3.8 13.27 3 12 3zm0 2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM6 10.45L7.5 14h-3L6 10.45zm12 0L19.5 14h-3L18 10.45z"})}),LN={upload:{label:"Upload",color:"#6c757d",icon:"📤"},email:{label:"Email",color:"#3498db",icon:"📧"},api:{label:"API",color:"#9b59b6",icon:"🔌"}},ufe=({source:n,sourceReference:e})=>{const{label:t,color:r,icon:i}=LN[n]||LN.upload;return s.jsxs("span",{style:{background:r,color:"white",padding:"0.4rem 0.6rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",display:"inline-flex",alignItems:"center",gap:"0.25rem"},title:e||void 0,children:[i," ",t]})},hfe=n=>n.ingredient_id?"#28a745":n.pack_quantity?n.portions_per_unit===null?"#ffc107":n.cost_per_portion!==null?"#28a745":"#ffc107":"#dc3545",EK=.02,ffe=n=>n?n.split(` `)[0].trim():"";function bx(n,e){if(!n)return"red";if(e==="CONFIRMED")return"none";const t=new Date(n),r=new Date;if(r.setHours(0,0,0,0),t.setHours(0,0,0,0),t>r)return"future";const i=r.getTime()-t.getTime(),o=Math.floor(i/(1e3*60*60*24));if(o>7){const a=t.getMonth()===r.getMonth(),l=t.getFullYear()===r.getFullYear();return!a||!l?o<=45?"amber":"red":"amber"}return"none"}const pfe={none:{},amber:{backgroundColor:"#fff3cd",borderColor:"#ffc107"},red:{backgroundColor:"#f8d7da",borderColor:"#dc3545"},future:{backgroundColor:"#ffe0cc",borderColor:"#e85d04",outline:"2px solid #e85d04"}};function NN(n){const e=n.split("-");if(e.length!==3)return null;const[t,r,i]=e,o=parseInt(i,10),a=parseInt(r,10);if(o<1||o>12||a<1||a>31)return null;const l=`${t}-${String(o).padStart(2,"0")}-${String(a).padStart(2,"0")}`,d=new Date(l);return isNaN(d.getTime())?null:l}function WN(n){const e=n.split("-");if(e.length!==3)return null;const[t,r,i]=e,o=new Date;o.setHours(0,0,0,0);const a=o.getFullYear();if(parseInt(t,10)<=a||Math.floor((new Date(n).getTime()-o.getTime())/(1e3*60*60*24))<=60)return null;for(const d of[a,a-1]){const c=`${d}-${r}-${i}`,u=new Date(c);if(!isNaN(u.getTime())&&u<=o)return{date:c,year:d}}return null}function gfe({lineItems:n,invoiceTotal:e,netTotal:t}){if(n.length===0)return s.jsxs("div",{style:{marginTop:"1rem",padding:"1rem",background:"#fef2f2",borderRadius:"6px",border:"1px solid #fca5a5"},children:[s.jsx("div",{style:{color:"#dc2626",fontWeight:"600",marginBottom:"0.5rem"},children:"⚠️ No Line Items"}),s.jsx("div",{style:{color:"#991b1b",fontSize:"0.9rem"},children:'This invoice has no line items. It will NOT be included in GP calculations. Use the "Edit Line Items" button above to manually add line items.'}),s.jsxs("div",{style:{marginTop:"0.5rem",color:"#991b1b",fontSize:"0.9rem"},children:[s.jsx("strong",{children:"Invoice Total:"})," £",e.toFixed(2)]})]});const r=n.reduce((f,p)=>f+(p.amount||0),0),i=n.filter(f=>!f.is_non_stock).reduce((f,p)=>f+(p.amount||0),0),o=n.filter(f=>f.is_non_stock).reduce((f,p)=>f+(p.amount||0),0),l=Math.abs((t??e)-r),d=l<=EK,c=d,u=o>0;return s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:c?"#d4edda":"#fff3cd",borderRadius:"6px",border:`1px solid ${c?"#c3e6cb":"#ffeeba"}`},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{style:{fontWeight:"500"},children:["Line Items Total: ",s.jsxs("strong",{children:["£",r.toFixed(2)]})]}),s.jsxs("span",{style:{fontWeight:"500"},children:["Invoice Net: ",s.jsxs("strong",{children:["£",(t??e).toFixed(2)]}),t&&s.jsxs("span",{style:{fontSize:"0.85rem",color:"#666"},children:[" (Gross: £",e.toFixed(2),")"]})]})]}),u&&s.jsxs("div",{style:{marginTop:"0.5rem",padding:"0.5rem",background:"rgba(255,255,255,0.5)",borderRadius:"4px"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"0.9rem"},children:[s.jsxs("span",{children:[s.jsx("strong",{children:"Stock Items:"})," £",i.toFixed(2)]}),s.jsxs("span",{style:{color:"#856404"},children:[s.jsx("strong",{children:"Non-Stock:"})," £",o.toFixed(2)]})]}),s.jsx("div",{style:{marginTop:"0.25rem",fontSize:"0.8rem",color:"#155724"},children:"GP will be calculated using stock items only"})]}),d?s.jsx("div",{style:{marginTop:"0.5rem",fontSize:"0.85rem",color:"#155724"},children:"✓ Totals match"}):s.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.85rem",color:c?"#155724":"#856404"},children:[c?"✓ ":"⚠ ","Difference: £",l.toFixed(2)]})]})}function mfe(){var Z1,J1,ew,nx,EC,tw;const{id:n}=G_(),{token:e,user:t}=gn(),r=go(),i=pi(),[o,a]=k.useState(""),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState(""),[g,m]=k.useState("food"),[y,v]=k.useState(""),[x,w]=k.useState("invoice"),[S,_]=k.useState(""),[b,C]=k.useState(!1),[T,F]=k.useState(!1),[A,D]=k.useState(!1),[P,L]=k.useState(!1),[W,O]=k.useState(null),[U,M]=k.useState(!1),[I,H]=k.useState(null),[z,G]=k.useState(!1),[te,re]=k.useState(!1),[me,J]=k.useState(!1),[ne,ye]=k.useState(null),[ke,Ye]=k.useState(""),[De,qe]=k.useState(null),[ue,Ze]=k.useState(!1),[ee,Z]=k.useState(""),[ge,Te]=k.useState(null),[Be,he]=k.useState({}),[He,Ge]=k.useState(!1),[ae,K]=k.useState(null),[de,Y]=k.useState(null),[Q,X]=k.useState({}),[pe,we]=k.useState(null),[Ne,st]=k.useState(""),[Ve,Re]=k.useState(!1),[Le,rt]=k.useState(null),[$e,ce]=k.useState(!1),[Je,jt]=k.useState([]),[ct,Se]=k.useState(1),[ot,ut]=k.useState(0),[Ot,An]=k.useState(1),on=k.useRef(null),Ke=k.useRef(null),Rt=k.useRef(null),vt=k.useRef(null),[Cr,Qt]=k.useState(""),[Ci,Lr]=k.useState(!1),[Gs,Ai]=k.useState(!1),[Ks,un]=k.useState(!1),[Fr,zi]=k.useState([]),[aa,Oi]=k.useState(!1),[Vd,Gn]=k.useState(!1),[Dr,xr]=k.useState([]),[Ss,rs]=k.useState(!1),[Xs,Jt]=k.useState([]),[Ys,Ft]=k.useState([]),[Ea,zn]=k.useState(!1),[gi,je]=k.useState(""),[bt,yn]=k.useState("asc"),[tn,ci]=k.useState(""),[hn,Ti]=k.useState(""),[js,Ar]=k.useState(""),[fs,Qs]=k.useState(""),[Lo,xn]=k.useState(1),Pa=k.useRef(null),[nn,Zl]=k.useState(null),[qu,$s]=k.useState(""),[Gd,mo]=k.useState([]),[Bc,Kd]=k.useState(!1),[Zs,Ra]=k.useState(null),[Xd,No]=k.useState(""),[Js,Ba]=k.useState(""),[Ic,al]=k.useState(!1),[ie,nt]=k.useState(!1),[$,ze]=k.useState(""),[Qe,pt]=k.useState({}),[kt,Ht]=k.useState(null),[Gt,Er]=k.useState(!1),[ar,Kn]=k.useState([]),[is,On]=k.useState(!1),[sn,ps]=k.useState(null),[It,Tn]=k.useState([]),[Dt,Ln]=k.useState(null),[Fi,Zr]=k.useState(new Set),[ll,Wo]=k.useState(!1),[Mc,H0]=k.useState(null),[Ia,q0]=k.useState(null),[A1,V0]=k.useState(null),{data:_e,isLoading:T1,refetch:G0}=Oe({queryKey:["invoice",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch invoice");return B.json()},staleTime:3e4,refetchOnWindowFocus:!1}),Mf=_e?`/api/invoices/${n}/file?token=${encodeURIComponent(e||"")}#toolbar=0&navpanes=0&view=FitH`:null,{data:Yt,refetch:zc}=Oe({queryKey:["invoice-line-items",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/line-items`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch line items");return B.json()}}),{data:Vu}=Oe({queryKey:["invoice-stock-history",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/stock-history`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch stock history");return B.json()},enabled:!!n}),{data:Li}=Oe({queryKey:["invoice-duplicates",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/duplicates`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch duplicates");return B.json()},enabled:!!(_e!=null&&_e.duplicate_status)}),{data:ks}=Oe({queryKey:["invoice-ocr-data",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/ocr-data`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch OCR data");return B.json()}}),{data:ui}=Oe({queryKey:["settings"],queryFn:async()=>{const B=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch settings");return B.json()},staleTime:6e4});k.useEffect(()=>{if(!Yt||!S||!e)return;const B=Yt.filter(Ae=>!Ae.ingredient_id&&!Ae.product_code&&Ae.description);if(B.length===0){pt({});return}const oe=B.map(Ae=>({description:Ae.description.split(` `)[0].trim(),price:Ae.unit_price??void 0})),be=Array.from(new Map(oe.map(Ae=>[Ae.description.toLowerCase(),Ae])).values());be.length!==0&&fetch("/api/ingredients/sources/alias-suggestions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({supplier_id:parseInt(S),items:be})}).then(Ae=>Ae.ok?Ae.json():[]).then(Ae=>{const it={};for(const en of Ae)it[en.description.toLowerCase()]=en;pt(it)}).catch(()=>pt({}))},[Yt,S,e]);const la=B=>{var er,lr,Kt,Fn,Jr,ei,Ui;if(!((ei=(Jr=(Fn=(Kt=(lr=(er=ks==null?void 0:ks.raw_json)==null?void 0:er.documents)==null?void 0:lr[0])==null?void 0:Kt.fields)==null?void 0:Fn[B])==null?void 0:Jr.bounding_regions)!=null&&ei[0]))return null;const oe=ks.raw_json.documents[0].fields[B].bounding_regions[0],be=oe.polygon,Ae=oe.page_number||1;if(!be||be.length<4)return null;const it=(Ui=ks.raw_json.pages)==null?void 0:Ui[Ae-1],en=(it==null?void 0:it.width)||8.5,rn=(it==null?void 0:it.height)||11,Nn=be.map(Uo=>Uo[0]),Qn=be.map(Uo=>Uo[1]),gr=Math.min(...Nn),br=Math.max(...Nn),mr=Math.min(...Qn),Wi=Math.max(...Qn);return{x:gr/en*100,y:mr/rn*100,width:(br-gr)/en*100,height:(Wi-mr)/rn*100,pageNumber:Ae}},F1=B=>{var er,lr,Kt,Fn,Jr,ei,Ui,Uo,da;if(!((Uo=(Ui=(ei=(Jr=(Fn=(Kt=(lr=(er=ks==null?void 0:ks.raw_json)==null?void 0:er.documents)==null?void 0:lr[0])==null?void 0:Kt.fields)==null?void 0:Fn.Items)==null?void 0:Jr.value)==null?void 0:ei[B])==null?void 0:Ui.bounding_regions)!=null&&Uo[0]))return null;const oe=ks.raw_json.documents[0].fields.Items.value[B].bounding_regions[0],be=oe.polygon,Ae=oe.page_number||1;if(!be||be.length<4)return null;const it=(da=ks.raw_json.pages)==null?void 0:da[Ae-1],en=(it==null?void 0:it.width)||8.5,rn=(it==null?void 0:it.height)||11,Nn=be.map(zf=>zf[0]),Qn=be.map(zf=>zf[1]),gr=Math.min(...Nn),br=Math.max(...Nn),mr=Math.min(...Qn),Wi=Math.max(...Qn);return{x:gr/en*100,y:mr/rn*100,width:(br-gr)/en*100,height:(Wi-mr)/rn*100,pageNumber:Ae}},D1=(B,oe)=>{var ei;if(!((ei=_e==null?void 0:_e.image_path)!=null&&ei.toLowerCase().endsWith(".pdf"))||Je.length===0)return null;const be=Je[B.pageNumber-1];if(!be)return null;const{padX:Ae=60,padY:it=20,strokeColor:en="#007bff"}=oe||{},rn=B.x/100*be.width,Nn=B.y/100*be.height,Qn=B.width/100*be.width,gr=B.height/100*be.height,br=Math.max(0,rn-Ae),mr=Math.max(0,Nn-it),Wi=Math.min(be.width,rn+Qn+Ae),er=Math.min(be.height,Nn+gr+it),lr=Wi-br,Kt=er-mr,Fn=document.createElement("canvas");Fn.width=lr,Fn.height=Kt;const Jr=Fn.getContext("2d");return Jr?(Jr.drawImage(be.canvas,br,mr,lr,Kt,0,0,lr,Kt),Jr.strokeStyle=en,Jr.lineWidth=3,Jr.strokeRect(rn-br-4,Nn-mr-4,Qn+8,gr+8),Fn.toDataURL()):null},E1=B=>{if(!B||!on.current||Je.length===0)return 2;const oe=Je[B.pageNumber-1];if(!oe)return 2;const be=on.current.clientWidth-32,Ae=on.current.clientHeight-32,it=B.width/100*oe.displayWidth,en=B.height/100*oe.displayHeight,rn=.8,Nn=be*rn/it,Qn=Ae*rn/en,gr=Math.min(Nn,Qn);return Math.max(2,Math.min(gr,8))},P1=(B,oe)=>{!B||!on.current||Je.length===0||!Je[B.pageNumber-1]||(Se(oe),ut(B.pageNumber),setTimeout(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!on.current)return;const Ae=on.current;Ae.offsetHeight;const it=Ae.querySelectorAll("[data-page-container]"),en=it[B.pageNumber-1];if(!en){console.warn("Could not find page element for scrolling",{totalPages:Je.length,targetPage:B.pageNumber,foundElements:it.length});return}const rn=Ae.getBoundingClientRect(),Nn=en.getBoundingClientRect(),Qn=Nn.width,gr=Nn.height,br=(B.x+B.width/2)/100*Qn,mr=(B.y+B.height/2)/100*gr,Wi=Nn.left-rn.left+Ae.scrollLeft,er=Nn.top-rn.top+Ae.scrollTop,lr=Wi+br,Kt=er+mr,Fn=Ae.clientWidth,Jr=Ae.clientHeight,ei=Math.max(0,lr-Fn/2),Ui=Math.max(0,Kt-Jr/2);Ae.scrollTo({left:ei,top:Ui,behavior:"auto"})})})},100))},Oc=()=>{Se(1),ut(0),on.current&&on.current.scrollTo({left:0,top:0,behavior:"smooth"})},Lc=B=>{if(ae===B)K(null),Oc();else{K(B),Y(null);const oe=la(B),be=E1(oe);P1(oe,be)}},fC=(B,oe)=>{de===B?Y(null):(Y(B),K(null),Oc())},{data:Yd}=Oe({queryKey:["suppliers"],queryFn:async()=>{const B=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${e}`}});return B.ok?B.json():[]}}),{data:Ni,refetch:K0}=Oe({queryKey:["po-match",n],queryFn:async()=>{const B=await fetch(`/api/purchase-orders/matching/for-invoice?invoice_id=${n}`,{headers:{Authorization:`Bearer ${e}`}});return B.ok?B.json():{matches:[],linked_po:null}},enabled:!!(_e!=null&&_e.supplier_id)});k.useEffect(()=>{var B,oe,be;_e&&(a(_e.invoice_number||""),d(_e.invoice_date||""),u(((B=_e.total)==null?void 0:B.toString())||""),p(((oe=_e.net_total)==null?void 0:oe.toString())||""),m(_e.category||"food"),v(_e.order_number||""),w(_e.document_type||"invoice"),_(((be=_e.supplier_id)==null?void 0:be.toString())||""),Qt(_e.notes||""))},[_e]),k.useEffect(()=>{if(!_e||_e.status!=="PENDING")return;const B=setInterval(async()=>{try{const oe=await fetch(`/api/invoices/${n}`,{headers:{Authorization:`Bearer ${e}`}});oe.ok&&(await oe.json()).status!=="PENDING"&&(clearInterval(B),window.location.reload())}catch{}},2e3);return()=>clearInterval(B)},[_e==null?void 0:_e.status,n,e]),k.useEffect(()=>{(async()=>{var be;if(!(!_e||!e||!((be=_e.image_path)!=null&&be.toLowerCase().endsWith(".pdf"))||!Ke.current))try{const Ae=`/api/invoices/${n}/file?token=${encodeURIComponent(e)}`,en=await(await fetch(Ae)).arrayBuffer(),rn=await kG({data:en}).promise,Nn=rn.numPages,Qn=Ke.current.clientWidth-112,gr=1500,br=[];for(let mr=1;mr<=Nn;mr++){const Wi=await rn.getPage(mr),er=Wi.getViewport({scale:1}),lr=Qn/er.width,Kt=er.width*lr,Fn=er.height*lr,Jr=gr/er.width,ei=Wi.getViewport({scale:Jr}),Ui=document.createElement("canvas");Ui.width=ei.width,Ui.height=ei.height;const Uo=Ui.getContext("2d");if(Uo){const da=(ui==null?void 0:ui.pdf_preview_show_annotations)===!1?Ru.DISABLE:Ru.ENABLE;await Wi.render({canvasContext:Uo,viewport:ei,canvas:Ui,annotationMode:da}).promise}br.push({width:ei.width,height:ei.height,displayWidth:Kt,displayHeight:Fn,canvas:Ui})}jt(br)}catch(Ae){console.error("Error rendering PDF:",Ae)}})()},[_e,e,n,ui==null?void 0:ui.pdf_preview_show_annotations]);const Gu=Ue({mutationFn:async B=>{var be,Ae;const oe=await fetch(`/api/invoices/${n}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(B)});if(!oe.ok){const it=await oe.json().catch(()=>({})),en=((be=it.detail)==null?void 0:be.message)||it.detail||"Failed to update",rn=new Error(en);throw rn.code=(Ae=it.detail)==null?void 0:Ae.error,rn}return oe.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["invoice",n]}),i.invalidateQueries({queryKey:["invoices"]}),i.invalidateQueries({queryKey:["invoice-line-items",n]})}}),pC=Ue({mutationFn:async()=>{const B=await fetch(`/api/invoices/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to delete");return B.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["invoices"]}),r("/invoices")}}),Jl=Ue({mutationFn:async({itemId:B,data:oe})=>{const be=await fetch(`/api/invoices/${n}/line-items/${B}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(oe)});if(!be.ok)throw new Error("Failed to update");return be.json()},onSuccess:()=>{zc(),i.invalidateQueries({queryKey:["invoice",n]}),Te(null),he({}),Y(null)}}),gC=Ue({mutationFn:async B=>{const oe=await fetch(`/api/invoices/${n}/line-items`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(B)});if(!oe.ok)throw new Error("Failed to create line item");return oe.json()},onSuccess:()=>{zc(),i.invalidateQueries({queryKey:["invoice",n]}),Te(null),he({})}}),mC=Ue({mutationFn:async B=>{const oe=await fetch(`/api/invoices/${n}/line-items/${B}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!oe.ok)throw new Error("Failed to delete line item");return oe.json()},onSuccess:()=>{zc(),i.invalidateQueries({queryKey:["invoice",n]}),Te(null)}}),yC=Ue({mutationFn:async({itemId:B,portionDesc:oe})=>{const be=await fetch(`/api/invoices/${n}/line-items/${B}/save-definition`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({portion_description:oe||null})});if(!be.ok){const Ae=await be.json();throw new Error(Ae.detail||"Failed to save definition")}return be.json()}}),X0=Ue({mutationFn:async B=>{const oe=await fetch("/api/suppliers/",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:B})});if(!oe.ok)throw new Error("Failed to create supplier");return oe.json()},onSuccess:B=>{i.invalidateQueries({queryKey:["suppliers"]}),_(B.id.toString()),D(!1),Z("")}}),Y0=Ue({mutationFn:async({supplierId:B,alias:oe,invoiceId:be})=>{const Ae=await fetch(`/api/suppliers/${B}/aliases`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({alias:oe,invoice_id:be})});if(!Ae.ok)throw new Error("Failed to add alias");return Ae.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["suppliers"]}),i.invalidateQueries({queryKey:["invoice",n]})}}),xC=Ue({mutationFn:async({sourceId:B,alias:oe})=>{const be=await fetch(`/api/ingredients/sources/${B}/aliases`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({alias:oe})});if(!be.ok)throw new Error("Failed to add alias");return be.json()},onSuccess:(B,oe)=>{pt(be=>{const Ae={...be};return delete Ae[oe.alias.toLowerCase()],Ae}),Ht(null),i.invalidateQueries({queryKey:["invoice-line-items",n]})}}),bC=async B=>{try{if(!(await fetch(`/api/purchase-orders/${B}/link`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({invoice_id:parseInt(n)})})).ok)throw new Error("Failed to link PO");K0()}catch{}},R1=async B=>{try{if(!(await fetch(`/api/purchase-orders/${B}/unlink`,{method:"POST",headers:{Authorization:`Bearer ${e}`}})).ok)throw new Error("Failed to unlink PO");K0()}catch{}},B1=()=>{ee.trim()&&X0.mutate(ee.trim())},I1=()=>{Z((_e==null?void 0:_e.vendor_name)||""),D(!0)},vC=async(B="REVIEWED")=>{await Gu.mutateAsync({invoice_number:o||null,invoice_date:l||null,total:c?parseFloat(c):null,net_total:f?parseFloat(f):null,supplier_id:S?parseInt(S):null,category:g,order_number:y||null,document_type:x,status:B})};k.useEffect(()=>{if(!_e)return;const B=setTimeout(()=>{var be,Ae,it;(o!==(_e.invoice_number||"")||l!==(_e.invoice_date||"")||c!==(((be=_e.total)==null?void 0:be.toString())||"")||f!==(((Ae=_e.net_total)==null?void 0:Ae.toString())||"")||S!==(((it=_e.supplier_id)==null?void 0:it.toString())||"")||g!==(_e.category||"food")||y!==(_e.order_number||"")||x!==(_e.document_type||"invoice"))&&Gu.mutate({invoice_number:o||null,invoice_date:l||null,total:c?parseFloat(c):null,net_total:f?parseFloat(f):null,supplier_id:S?parseInt(S):null,category:g,order_number:y||null,document_type:x})},1e3);return()=>clearTimeout(B)},[o,l,c,f,S,g,y,x]);const M1=async()=>{if(_e!=null&&_e.has_open_disputes&&!window.confirm(`This invoice has ${_e.dispute_count} open dispute(s). You can still confirm — the invoice will appear in reports while the dispute is tracked separately. Continue?`))return;if(l&&bx(l,"PENDING")==="future"){const oe=new Date(l).toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"});if(!window.confirm(`⚠ Invoice date is in the future: ${oe} This is almost certainly a day/month format error (e.g. 6 April entered as 4 June). Please double-check the date on the document before confirming. Confirm anyway?`))return}const B=(Yt||[]).filter(oe=>{const be=Vu==null?void 0:Vu[oe.id.toString()];return(be==null?void 0:be.has_history)&&be.previously_non_stock&&!oe.is_non_stock});if(B.length>0){xr(B.map(oe=>({description:oe.description,amount:oe.amount}))),Gn(!0);return}if(!l){alert(`Cannot confirm invoice without a date. Please set the invoice date before confirming. Invoices without dates cannot be found in date-filtered views.`);return}await z1()},z1=async()=>{try{await vC("CONFIRMED"),r("/invoices")}catch(B){const oe=B instanceof Error?B.message:"Failed to confirm invoice";alert(oe)}},wC=()=>{pC.mutate()},SC=async()=>{if(window.confirm(`Mark this invoice as sent to Dext without actually sending? This will also trigger Nextcloud archival if configured.`)){M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/mark-dext-sent`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const be=await B.json();throw new Error(be.detail||"Failed to mark as sent")}const oe=await B.json();H({type:"success",message:oe.message+(oe.archival_status?` ${oe.archival_status}`:"")}),i.invalidateQueries({queryKey:["invoice",n]})}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}}},jC=async()=>{if(window.confirm(`Reprocess existing OCR data? This will: - Re-identify supplier - Re-detect document type - Re-create line items with product definitions - Re-run duplicate detection Existing line items will be replaced.`)){M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/reprocess`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const be=await B.json();throw new Error(be.detail||"Failed to reprocess")}const oe=await B.json();H({type:"success",message:`${oe.message} Supplier ID: ${oe.supplier_id||"None"} Document Type: ${oe.document_type} Line Items: ${oe.line_items_count} Duplicate Status: ${oe.duplicate_status||"None"}`}),window.location.reload()}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}}},O1=async()=>{Oi(!0),zi([]),un(!0);try{const B=await fetch(`/api/invoices/${n}/parse-dates`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to parse dates");const oe=await B.json();zi(oe.found_dates||[])}catch(B){console.error("Failed to fetch parsed dates:",B)}finally{Oi(!1)}},Q0=B=>{d(B),un(!1)},L1=async()=>{zn(!0),Jt([]),Ft([]),rs(!0);try{const B=await fetch(`/api/invoices/${n}/parse-invoice-number`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to search for invoice number");const oe=await B.json();Jt(oe.candidates||[]),Ft(oe.supplier_examples||[])}catch(B){console.error("Failed to fetch invoice number candidates:",B)}finally{zn(!1)}},N1=B=>{a(B),rs(!1)},W1=async()=>{if(window.confirm(`Re-send invoice to Azure for OCR extraction? This will: - Fully re-extract data from Azure - Update all invoice fields - Re-create line items with product definitions - Re-run duplicate detection Existing data will be replaced.`)){M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/resend-to-azure`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const Ae=await B.json();throw new Error(Ae.detail||"Failed to resend to Azure")}const oe=await B.json();H({type:"success",message:`${oe.message} The page will reload automatically when processing completes.`});const be=setInterval(async()=>{try{const Ae=await fetch(`/api/invoices/${n}`,{headers:{Authorization:`Bearer ${e}`}});Ae.ok&&(await Ae.json()).status!=="PENDING"&&(clearInterval(be),window.location.reload())}catch{}},2e3);setTimeout(()=>clearInterval(be),12e4)}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}}},kC=async()=>{M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/regenerate-highlights`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const en=await B.json();throw new Error(en.detail||"Failed to regenerate highlights")}const oe=await B.json(),be=oe.non_stock_count||0,Ae=oe.has_notes;let it="";be>0?it=`PDF highlights regenerated successfully. Highlighted ${be} non-stock item(s).`:it="PDF highlights cleared (no non-stock items marked).",Ae&&(it+=` Notes overlay added.`),H({type:"success",message:it}),i.invalidateQueries({queryKey:["invoice",n]})}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}},U1=B=>{Te(B.id),he({product_code:B.product_code,description:B.description,unit:B.unit,quantity:B.quantity,unit_price:B.unit_price,tax_rate:B.tax_rate,amount:B.amount,is_non_stock:B.is_non_stock}),Y(B.id),K(null),Oc()},_C=B=>{B===-1?gC.mutate(Be):Jl.mutate({itemId:B,data:Be}),Te(null),he({}),Y(null)},CC=()=>{Te(null),he({}),Y(null)},$0=()=>{Te(-1),he({product_code:"",description:"",unit:"",quantity:null,unit_price:null,tax_rate:"",amount:null,is_non_stock:!1,line_number:(tx.length||0)+1})},pD=B=>{window.confirm("Are you sure you want to delete this line item? This action cannot be undone.")&&mC.mutate(B)},ed=B=>{ge!==B.id&&U1(B)},AC=()=>{if(!Yd)return[];const B=[];for(const oe of Yd)if(oe.name&&B.push(...oe.name.toLowerCase().split(/\s+/)),oe.aliases)for(const be of oe.aliases)be&&B.push(...be.toLowerCase().split(/\s+/));return[...new Set(B)].filter(oe=>oe.length>1)},H1=B=>{if(!B)return"";let oe=B;oe=oe.replace(/\b\d+\s*x\s*\d+(\.\d+)?\s*(g|kg|ml|ltr|l|oz|cl)?\b/gi,""),oe=oe.replace(/\b(qty|quantity)\s*:?\s*\d+\b/gi,""),oe=oe.replace(/\bcase\s*(of\s*)?\d+\b/gi,""),oe=oe.replace(/\([A-Z]{1,3}-?[A-Z0-9]{1,5}\)/gi,""),oe=oe.replace(/\[[A-Z0-9-]+\]/gi,""),oe=oe.replace(/\b(case|qty|un|pack|box|each|per|unit|pkt|bag|bottle|tin|can|carton|tray|portion|portions)\b/gi,""),oe=oe.replace(/\b\d+(\.\d+)?\s*(g|kg|ml|ltr|l|oz|cl|lb)?\b/gi,""),oe=oe.replace(/[^\w\s]/g," "),oe=oe.replace(/\b(the|a|an|in|on|at|by|for|with|to|of|and|or|is|it|as|be|are|was|been|being|have|has|had|do|does|did|will|would|could|should|may|might|this|that|these|those|from|into|through|during|before|after|above|below|between|under|over)\b/gi,"");const be=AC();if(be.length>0){const Ae=new RegExp(`\\b(${be.map(it=>it.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`,"gi");oe=oe.replace(Ae,"")}return oe.split(/\s+/).filter(Ae=>Ae.length>1).join(" ").trim()},TC=B=>{ye(B);const oe=H1(B.description||"");Ye(oe),qe(null),re(!0),oe&&J0(oe)},Z0=B=>{_e!=null&&_e.supplier_id&&q0({isOpen:!0,productCode:B.product_code,description:B.description,unit:B.unit,supplierId:_e.supplier_id,supplierName:_e.supplier_name||"Unknown",currentPrice:B.unit_price||void 0,sourceInvoiceId:_e.id,sourceLineItemId:B.id})},J0=async B=>{if(!(!B||B.length<2)){Ze(!0);try{const oe=await fetch("/api/invoices/line-items/search",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({query:B,exclude_invoice_id:n?parseInt(n):null})});oe.ok&&qe(await oe.json())}finally{Ze(!1)}}},ex=async B=>{if(Yt)try{const oe=Yt.map(be=>fetch(`/api/invoices/${n}/line-items/${be.id}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({is_non_stock:!B})}));await Promise.all(oe),await zc(),i.invalidateQueries({queryKey:["invoice",n]}),J(!1)}catch(oe){console.error("Failed to bulk update stock status:",oe)}},q1=async B=>{var oe;Er(!0),Kn([]);try{const be=await fetch(`/api/ingredients/ai-match?description=${encodeURIComponent(B)}`,{headers:{Authorization:`Bearer ${e}`}});if(be.ok){const Ae=await be.json();((oe=Ae.ranked)==null?void 0:oe.length)>0&&Kn(Ae.ranked)}}catch{}Er(!1)},V1=async()=>{On(!0),Ln(null),ps(null),Tn([]),Zr(new Set);try{const B=await fetch(`/api/invoices/${n}/ai-assist`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){let be="AI analysis failed";try{be=(await B.json()).detail||be}catch{}throw new Error(be)}const oe=await B.json();oe.suggestions&&ps(oe.suggestions),oe.reconciliation_matches&&Tn(oe.reconciliation_matches),oe.error&&Ln(oe.error)}catch(B){Ln(B instanceof Error?B.message:"AI analysis failed")}finally{On(!1)}},G1=async(B,oe,be)=>{if(!Yt)return;const Ae=Yt[B];if(Ae)try{await Jl.mutateAsync({itemId:Ae.id,data:{[oe]:be}}),Zr(it=>new Set([...it,`${B}-${oe}`]))}catch(it){console.error("Failed to apply AI correction:",it)}},K1=async B=>{try{await Gu.mutateAsync({supplier_id:B})}catch(oe){console.error("Failed to apply AI supplier match:",oe)}},X1=async B=>{Zl(B),Wo(!1),H0(null),X({pack_quantity:B.pack_quantity,unit_size:B.unit_size,unit_size_type:B.unit_size_type,portions_per_unit:B.portions_per_unit,unit_price:B.unit_price}),st(""),Re(!1),rt(null),nt(!1),al(!1),$s(""),mo([]),Ra(B.ingredient_id||null),No(B.ingredient_name||""),Ba(B.ingredient_unit||""),B.unit_size&&B.unit_size_type&&Ku(B.ingredient_unit||void 0,{pack_quantity:B.pack_quantity,unit_size:B.unit_size,unit_size_type:B.unit_size_type,unit_price:B.unit_price}),ce(!0);try{const oe=await fetch(`/api/invoices/${n}/line-items/${B.id}/definition`,{headers:{Authorization:`Bearer ${e}`}});if(oe.ok){const be=await oe.json();rt(be),st((be==null?void 0:be.portion_description)||"")}}catch{}if(ce(!1),B.description&&!B.ingredient_id&&Y1(B.description),!B.pack_quantity&&!B.unit_size){Wo(!0);try{const oe=await fetch(`/api/invoices/${n}/line-items/${B.id}/ai-pack-size`,{headers:{Authorization:`Bearer ${e}`}});if(oe.ok){const be=await oe.json();be.pack_quantity&&be.unit_size&&(H0(be.source),X(Ae=>({...Ae,pack_quantity:be.pack_quantity,unit_size:be.unit_size,unit_size_type:be.unit_size_type})),Ku(B.ingredient_unit||void 0,{pack_quantity:be.pack_quantity,unit_size:be.unit_size,unit_size_type:be.unit_size_type,unit_price:B.unit_price}))}}catch{}Wo(!1)}},Y1=async B=>{if(!B||B.length<2){mo([]);return}Kd(!0);try{const oe=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(B)}`,{headers:{Authorization:`Bearer ${e}`}});if(oe.ok){const be=await oe.json();mo(be)}}catch{}Kd(!1)},Q1=B=>{Ra(B.id),No(B.name),Ba(B.standard_unit),$s(""),mo([]),Q.unit_size_type||X(oe=>({...oe,unit_size_type:B.standard_unit})),Ku(B.standard_unit)},Ku=(B,oe)=>{var lr;const be=oe?{...Q,...oe}:Q,Ae=B||Js||be.unit_size_type,it=be.pack_quantity||1,en=be.unit_size,rn=be.unit_size_type,Nn=be.unit_price;if(!en||!rn||!Ae){ze("");return}const gr=(lr={g:{g:1,kg:.001},kg:{g:1e3,kg:1},oz:{g:28.3495,kg:.0283495},ml:{ml:1,ltr:.001},cl:{ml:10,ltr:.01},ltr:{ml:1e3,ltr:1},each:{each:1}}[rn])==null?void 0:lr[Ae];if(!gr){ze(rn!==Ae?`Cannot convert ${rn} → ${Ae}`:`${en}${rn}`);return}const br=it*en*gr,mr=Nn?Nn/br:null;let er=`${it>1?`${it} × ${en}${rn} = `:""}${br.toFixed(br%1?2:0)} ${Ae}`;mr&&(er+=` → £${mr.toFixed(4)} per ${Ae}`,Ae==="g"&&mr?er+=` (£${(mr*1e3).toFixed(2)}/kg)`:Ae==="ml"&&mr&&(er+=` (£${(mr*1e3).toFixed(2)}/ltr)`)),ze(er)},FC=B=>{zc(),dl()},dl=()=>{Zl(null),X({}),st(""),Re(!1),rt(null),Ra(null),No(""),Ba(""),al(!1),$s(""),mo([]),ze("")},DC=async B=>{if(await Jl.mutateAsync({itemId:B,data:Q}),Zs)try{if(await fetch(`/api/invoices/${n}/line-items/${B}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_id:Zs})}),_e!=null&&_e.supplier_id){const oe={supplier_id:_e.supplier_id,pack_quantity:Q.pack_quantity||1,unit_size:Q.unit_size||null,unit_size_type:Q.unit_size_type||Js||null},be=nn;be!=null&&be.product_code?oe.product_code=be.product_code:be!=null&&be.description&&(oe.description_pattern=be.description.substring(0,100).toLowerCase().trim()),Q.unit_price&&(oe.latest_unit_price=Q.unit_price),n&&(oe.invoice_id=parseInt(n));const Ae=await fetch(`/api/ingredients/${Zs}/sources`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(oe)});if(!Ae.ok){const it=await Ae.json().catch(()=>({}));console.warn("Source creation failed:",Ae.status,it)}}}catch(oe){console.error("Failed to set ingredient mapping:",oe)}if(Ve)try{await yC.mutateAsync({itemId:B,portionDesc:Ne})}catch(oe){console.error("Failed to save definition:",oe)}dl(),zc()},tx=k.useMemo(()=>{if(!Yt)return[];let B=Yt.map(oe=>({...oe,_originalIndex:oe.line_number}));if(hn){const oe=hn.toLowerCase();B=B.filter(be=>{const Ae=(be.product_code||"").toLowerCase(),it=(be.description||"").toLowerCase();return Ae.includes(oe)||it.includes(oe)})}return tn&&(B=B.filter(oe=>tn==="consistent"?oe.price_change_status==="consistent":tn==="amber"?oe.price_change_status==="amber":tn==="red"?oe.price_change_status==="red":tn==="no_history"?oe.price_change_status==="no_history":!0)),js&&(B=B.filter(oe=>{const be=oe.portions_per_unit!=null&&oe.portions_per_unit>0;return js==="yes"?be:js==="no"?!be:!0})),fs==="missing"&&(B=B.filter(oe=>{const be=oe.quantity==null||oe.quantity===0,Ae=oe.unit_price==null||oe.unit_price===0,it=oe.amount==null||oe.amount===0;return be||Ae||it})),gi&&B.sort((oe,be)=>{let Ae=null,it=null;switch(gi){case"code":Ae=oe.product_code||"",it=be.product_code||"";break;case"description":Ae=oe.description||"",it=be.description||"";break;case"unit":Ae=oe.unit||"",it=be.unit||"";break;case"quantity":Ae=oe.quantity||0,it=be.quantity||0;break;case"unit_price":Ae=oe.unit_price||0,it=be.unit_price||0;break;case"price_change":Ae=oe.price_change_percent||0,it=be.price_change_percent||0;break;case"amount":Ae=oe.amount||0,it=be.amount||0;break}return typeof Ae=="string"?bt==="asc"?Ae.localeCompare(it):it.localeCompare(Ae):bt==="asc"?Ae-it:it-Ae}),B},[Yt,gi,bt,tn,hn,js,fs]);k.useEffect(()=>{const B=Pa.current;if(!B)return;const oe=()=>{const be=B.querySelectorAll("tr[data-page]");if(be.length===0)return;const Ae=B.getBoundingClientRect().top+50;for(const rn of be)if(rn.getBoundingClientRect().top>=Ae-10){const Qn=parseInt(rn.getAttribute("data-page")||"1",10);xn(Qn);return}const it=be[be.length-1],en=parseInt(it.getAttribute("data-page")||"1",10);xn(en)};return B.addEventListener("scroll",oe),oe(),()=>B.removeEventListener("scroll",oe)},[tx]);const qn=k.useMemo(()=>{if(!Yt)return{total:0,withPortions:0,withoutPortions:0,missingData:0,nonStock:0,priceCalcErrors:0,totalsMatch:!0,totalDifference:0,lineItemsTotal:0,stockItemsTotal:0,nonStockItemsTotal:0,stockItemsGross:0};const B=Yt.filter(Kt=>Kt.portions_per_unit!=null&&Kt.portions_per_unit>0).length,oe=Yt.filter(Kt=>{const Fn=Kt.quantity==null||Kt.quantity===0,Jr=Kt.unit_price==null||Kt.unit_price===0,ei=Kt.amount==null||Kt.amount===0;return Fn||Jr||ei}).length,be=Yt.filter(Kt=>Kt.is_non_stock).length,Ae=Yt.filter(Kt=>{const Fn=Kt.quantity!=null&&Kt.quantity!==0,Jr=Kt.unit_price!=null&&Kt.unit_price!==0,ei=Kt.amount!=null&&Kt.amount!==0,Ui=(Kt.quantity||0)*(Kt.unit_price||0),Uo=Kt.amount||0,da=Math.abs(Ui-Uo)>.02;return Jr&&(!Fn||!ei)||ei&&(!Fn||!Jr)||Fn&&Jr&&ei&&da}).length,it=Yt.reduce((Kt,Fn)=>Kt+(Fn.amount||0),0),en=Yt.filter(Kt=>!Kt.is_non_stock).reduce((Kt,Fn)=>Kt+(Fn.amount||0),0),rn=Yt.filter(Kt=>Kt.is_non_stock).reduce((Kt,Fn)=>Kt+(Fn.amount||0),0),Nn=parseFloat(c)||0,Qn=parseFloat(f)||Nn,gr=Qn>0?Nn/Qn:1,br=en,mr=en*gr,er=Math.abs(Qn-it),lr=er<=EK;return{total:Yt.length,withPortions:B,withoutPortions:Yt.length-B,missingData:oe,nonStock:be,priceCalcErrors:Ae,totalsMatch:lr,totalDifference:er,lineItemsTotal:it,stockItemsTotal:en,stockItemsNet:br,nonStockItemsTotal:rn,stockItemsGross:mr}},[Yt,c,f]),Qd=k.useMemo(()=>!Yt||Yt.length===0||!qn.totalsMatch||qn.priceCalcErrors>0,[Yt,qn.totalsMatch,qn.priceCalcErrors]),Nc=k.useMemo(()=>Yt?{consistent:Yt.filter(B=>B.price_change_status==="consistent").length,amber:Yt.filter(B=>B.price_change_status==="amber").length,red:Yt.filter(B=>B.price_change_status==="red").length,no_history:Yt.filter(B=>B.price_change_status==="no_history").length,withPortions:Yt.filter(B=>B.portions_per_unit!=null&&B.portions_per_unit>0).length,withoutPortions:Yt.filter(B=>!(B.portions_per_unit!=null&&B.portions_per_unit>0)).length,missingData:Yt.filter(B=>{const oe=B.quantity==null||B.quantity===0,be=B.unit_price==null||B.unit_price===0,Ae=B.amount==null||B.amount===0;return oe||be||Ae}).length}:{consistent:0,amber:0,red:0,no_history:0,withPortions:0,withoutPortions:0,missingData:0},[Yt]),Xu=B=>{gi===B?yn(bt==="asc"?"desc":"asc"):(je(B),yn("asc"))};if(T1)return s.jsx("div",{style:fe.loading,children:"Loading invoice..."});if(!_e)return s.jsx("div",{style:fe.error,children:"Invoice not found"});const $1=_e.ocr_confidence?(Number(_e.ocr_confidence)*100).toFixed(0):null,Yu=(Z1=_e==null?void 0:_e.image_path)==null?void 0:Z1.toLowerCase().endsWith(".pdf");return s.jsxs("div",{style:fe.pageContainer,children:[(_e==null?void 0:_e.ocr_raw_text)&&_e.ocr_raw_text.startsWith("Error:")&&s.jsxs("div",{style:fe.errorBanner,children:[s.jsx("div",{style:fe.errorBannerIcon,children:"⚠️"}),s.jsxs("div",{style:fe.errorBannerContent,children:[s.jsx("strong",{children:"OCR Processing Error"}),s.jsx("p",{children:_e.ocr_raw_text.replace("Error: ","")}),_e.ocr_raw_text.includes("quota exceeded")&&s.jsxs("p",{style:{marginTop:"0.5rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:"Next steps:"}),' Check your Azure subscription budget limits in the Azure portal. Once resolved, use the "Reprocess" button below to retry OCR extraction.']}),_e.ocr_raw_text.includes("authentication failed")&&s.jsxs("p",{style:{marginTop:"0.5rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:"Next steps:"})," Verify your Azure API credentials in Settings → Azure Configuration."]})]})]}),_e.status==="PENDING"&&s.jsxs("div",{style:{display:"flex",gap:"1rem",padding:"1rem 1.5rem",marginBottom:"1.5rem",background:"#d4edda",border:"2px solid #28a745",borderRadius:"8px",color:"#155724",alignItems:"center"},children:[s.jsx("div",{style:{fontSize:"1.5rem",flexShrink:0},children:"⚙"}),s.jsxs("div",{children:[s.jsx("strong",{children:"Processing Invoice"}),s.jsx("p",{style:{margin:"0.25rem 0 0"},children:"Azure OCR extraction is in progress. The page will reload automatically when complete."})]})]}),s.jsxs("div",{style:fe.topRow,children:[s.jsxs("div",{style:fe.imageSection,ref:Ke,children:[s.jsxs("h3",{children:["Invoice ",Yu?"Document":"Image"]}),Mf?Yu?s.jsx("div",{style:fe.pdfScrollContainer,ref:on,children:Je.length>0?Je.map((B,oe)=>{const be=oe+1,Ae=ae?la(ae):null,it=de!==null&&Yt?(()=>{const en=Yt.find(rn=>rn.id===de);return en?F1(en.line_number):null})():null;return s.jsxs("div",{style:fe.pdfPageWrapper,children:[s.jsxs("div",{"data-page-container":!0,style:{...fe.pdfPageContainer,position:"relative",width:B.displayWidth*(ot===be?ct:1),height:B.displayHeight*(ot===be?ct:1),margin:"0 auto"},children:[s.jsx("img",{src:B.canvas.toDataURL(),alt:`Page ${be}`,style:{width:"100%",height:"100%",display:"block"}}),Ae&&Ae.pageNumber===be&&(()=>{const rn=Math.max(1,2/ct);return s.jsx("div",{ref:vt,style:{...fe.highlightOverlay,left:`${Ae.x-.5}%`,top:`${Ae.y-.5}%`,width:`${Ae.width+.5*2}%`,height:`${Ae.height+.5*2}%`,border:`${rn}px solid #ffc107`},onClick:()=>{K(null),Oc()}})})(),it&&it.pageNumber===be&&(()=>{const rn=Math.max(1,2/ct);return s.jsx("div",{style:{...fe.highlightOverlay,left:`${it.x-.5}%`,top:`${it.y-.5}%`,width:`${it.width+.5*2}%`,height:`${it.height+.5*2}%`,border:`${rn}px solid #ffc107`},onClick:()=>{Y(null),Oc()}})})()]}),Je.length>1&&s.jsxs("div",{style:fe.pageLabel,children:["Page ",be," of ",Je.length]})]},oe)}):s.jsx("div",{style:fe.imagePlaceholder,children:"Rendering PDF..."})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:fe.imageZoomControls,children:[s.jsx("button",{onClick:()=>An(Math.min(Ot+.5,5)),style:fe.zoomBtn,title:"Zoom In",children:"+"}),s.jsxs("span",{style:fe.zoomLabel,children:[Math.round(Ot*100),"%"]}),s.jsx("button",{onClick:()=>An(Math.max(Ot-.5,1)),style:fe.zoomBtn,title:"Zoom Out",children:"−"}),Ot>1&&s.jsx("button",{onClick:()=>An(1),style:fe.zoomResetBtnSmall,title:"Reset Zoom",children:"Reset"})]}),s.jsx("div",{style:{...fe.imageScrollContainer,cursor:Ot>1?"grab":"default"},ref:Rt,onWheel:B=>{if(B.ctrlKey||B.metaKey){B.preventDefault();const oe=B.deltaY>0?-.1:.1;An(Math.max(1,Math.min(5,Ot+oe)))}},children:s.jsxs("div",{style:{...fe.imageContainer,width:`${Ot*100}%`,height:"auto"},children:[s.jsx("img",{src:Mf,alt:"Invoice",style:{...fe.image,width:"100%",height:"auto"}}),ae&&la(ae)&&(()=>{const B=la(ae),oe=.5;return s.jsx("div",{style:{...fe.highlightOverlay,left:`${B.x-oe}%`,top:`${B.y-oe}%`,width:`${B.width+oe*2}%`,height:`${B.height+oe*2}%`,border:"2px solid #ffc107"},onClick:()=>K(null)})})()]})})]}):s.jsxs("div",{style:fe.imagePlaceholder,children:["Loading ",Yu?"document":"image","..."]}),Yu&&ct>1&&s.jsxs("button",{onClick:Oc,style:fe.zoomResetBtn,children:["Reset Zoom (",ct,"x)"]}),Yu&&Mf&&s.jsx("a",{href:`/api/invoices/${n}/file?token=${encodeURIComponent(e||"")}`,target:"_blank",rel:"noopener noreferrer",style:fe.openPdfLink,children:"Open PDF in new tab"}),$1&&s.jsxs("div",{style:fe.confidenceBadge,children:["OCR Confidence: ",$1,"%"]})]}),s.jsxs("div",{style:fe.formSection,children:[_e.duplicate_status&&s.jsx("div",{style:{...fe.duplicateWarning,background:_e.duplicate_status==="firm_duplicate"?"#f8d7da":"#fff3cd",borderColor:_e.duplicate_status==="firm_duplicate"?"#f5c6cb":"#ffeeba",color:_e.duplicate_status==="firm_duplicate"?"#721c24":"#856404"},onClick:()=>F(!0),children:_e.duplicate_status==="firm_duplicate"?"⚠️ DUPLICATE: This invoice matches an existing record. Click to compare.":"⚠️ Possible duplicate detected. Click to compare."}),(Ni==null?void 0:Ni.linked_po)&&s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.75rem 1rem",marginBottom:"1rem",background:"#d4edda",border:"1px solid #c3e6cb",borderRadius:"8px",color:"#155724",fontSize:"0.9rem"},children:[s.jsxs("div",{children:[s.jsxs("strong",{children:["Linked to PO-",Ni.linked_po.po_id]})," ","(",Ni.linked_po.total_amount!=null?`£${Ni.linked_po.total_amount.toFixed(2)}`:"N/A",", ",Ni.linked_po.order_date?new Date(Ni.linked_po.order_date+"T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}):"",")"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>V0(Ni.linked_po.po_id),style:{padding:"0.3rem 0.6rem",border:"1px solid #155724",borderRadius:"4px",background:"white",color:"#155724",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},children:"View PO"}),s.jsx("button",{onClick:()=>R1(Ni.linked_po.po_id),style:{padding:"0.3rem 0.6rem",border:"1px solid #856404",borderRadius:"4px",background:"#fff3cd",color:"#856404",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},children:"Unlink"})]})]}),!(Ni!=null&&Ni.linked_po)&&(Ni==null?void 0:Ni.matches)&&Ni.matches.length>0&&s.jsxs("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",background:"#e3f2fd",border:"1px solid #bbdefb",borderRadius:"8px",fontSize:"0.9rem",color:"#1565c0"},children:[s.jsxs("div",{style:{fontWeight:600,marginBottom:"0.5rem"},children:["This supplier has ",Ni.matches.length," pending Purchase Order",Ni.matches.length>1?"s":""]}),Ni.matches.map((B,oe)=>{const be=oe===0&&B.confidence>=.8,Ae=!be&&B.confidence>=.8;return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.4rem 0.5rem",marginBottom:"0.25rem",background:"rgba(255,255,255,0.6)",borderRadius:"4px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsxs("span",{style:{fontWeight:500},children:["PO-",B.po_id,":"]}),s.jsx("span",{children:B.total_amount!=null?`£${B.total_amount.toFixed(2)}`:"N/A"}),s.jsxs("span",{style:{color:"#666"},children:["(",B.order_date?new Date(B.order_date+"T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}):"No date",")"]}),be&&s.jsx("span",{style:{background:"#4caf50",color:"white",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.75rem",fontWeight:600},children:"Suggested match"}),Ae&&s.jsx("span",{style:{background:"#ff9800",color:"white",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.75rem",fontWeight:600},children:"Potential match"})]}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem"},children:[s.jsx("button",{onClick:()=>V0(B.po_id),style:{padding:"0.2rem 0.5rem",border:"1px solid #1565c0",borderRadius:"4px",background:"white",color:"#1565c0",cursor:"pointer",fontSize:"0.8rem"},children:"View"}),s.jsx("button",{onClick:()=>bC(B.po_id),style:{padding:"0.2rem 0.5rem",border:"none",borderRadius:"4px",background:"#1565c0",color:"white",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},children:"Link"})]})]},B.po_id)})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"20px"},children:[s.jsx("h3",{style:{margin:0},children:"Invoice Details"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[_e.source&&_e.source!=="upload"&&s.jsx(ufe,{source:_e.source,sourceReference:_e.source_reference}),s.jsxs("span",{style:{padding:"0.4rem 0.8rem",borderRadius:"4px",fontSize:"0.85rem",fontWeight:"600",background:_e.status==="CONFIRMED"?"#22c55e":_e.status==="REVIEWED"?"#8b5cf6":_e.status==="PROCESSED"?"#3b82f6":"#f59e0b",color:"white"},children:[_e.status.toUpperCase(),_e.document_type==="delivery_note"&&" (DN)"]})]})]}),s.jsxs("div",{style:fe.form,children:[s.jsxs("div",{style:fe.label,children:[s.jsx("span",{children:"Supplier"}),s.jsxs("div",{style:fe.supplierRow,children:[s.jsxs("select",{value:S,onChange:B=>_(B.target.value),style:{...fe.input,flex:1,...(_e==null?void 0:_e.supplier_match_type)==="fuzzy"&&S?{border:"2px solid #f0ad4e",background:"#fff8e6"}:{}},children:[s.jsx("option",{value:"",children:"-- Select Supplier --"}),Yd==null?void 0:Yd.map(B=>s.jsx("option",{value:B.id,children:B.name},B.id))]}),la("VendorName")&&s.jsx("button",{type:"button",onClick:()=>Lc("VendorName"),style:{...fe.eyeBtn,...ae==="VendorName"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"}),s.jsx("button",{type:"button",onClick:I1,style:fe.createSupplierBtn,title:"Create new supplier",children:"+ New"})]}),(_e==null?void 0:_e.supplier_match_type)==="fuzzy"&&S&&_e.vendor_name&&s.jsxs("div",{style:fe.fuzzyMatchWarning,children:[s.jsxs("span",{children:['Fuzzy match from "',_e.vendor_name,'" - please verify']}),s.jsx("button",{type:"button",onClick:()=>Y0.mutate({supplierId:parseInt(S),alias:_e.vendor_name,invoiceId:_e.id}),style:fe.addAliasBtn,disabled:Y0.isPending,title:"Add this name as an alias so future invoices match exactly",children:Y0.isPending?"Adding...":"+ Add as alias"})]}),(_e==null?void 0:_e.vendor_name)&&!S&&s.jsxs("div",{style:fe.extractedHintRow,children:[s.jsxs("span",{style:fe.extractedHint,children:["Extracted: ",_e.vendor_name]}),s.jsxs("button",{type:"button",onClick:I1,style:fe.createFromExtractedBtn,children:['Create "',_e.vendor_name,'"']})]})]}),s.jsxs("div",{style:fe.row,children:[s.jsxs("label",{style:{...fe.label,flex:1},children:["Invoice Date",(()=>{const B=bx(l||null,(_e==null?void 0:_e.status)||"");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"date",value:l,onChange:oe=>d(oe.target.value),style:{...fe.input,...pfe[B]}}),la("InvoiceDate")&&s.jsx("button",{type:"button",onClick:()=>Lc("InvoiceDate"),style:{...fe.eyeBtn,...ae==="InvoiceDate"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"}),(_e==null?void 0:_e.status)!=="CONFIRMED"&&s.jsx("button",{type:"button",onClick:O1,style:{background:"none",border:"none",cursor:"pointer",padding:"2px 4px",fontSize:"1rem",color:!l||B!=="none"?"#007bff":"#ccc",display:"flex",alignItems:"center"},title:"Find dates in document",children:"🔍"})]}),B!=="none"&&s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:B==="future"?s.jsx("button",{type:"button",onClick:O1,style:{background:"none",border:"none",padding:0,cursor:"pointer",fontSize:"0.8rem",color:"#e85d04",fontWeight:600,textDecoration:"underline",textDecorationStyle:"dotted"},title:"Click to fix date",children:"⚠ Date is in the future — likely a day/month swap — click to fix"}):s.jsx("span",{style:{fontSize:"0.8rem",color:B==="red"?"#dc3545":"#856404"},children:l?"Date differs from today by more than 7 days":"No date set"})})]})})()]}),s.jsxs("label",{style:{...fe.label,flex:1},children:["Document Type",s.jsxs("select",{value:x,onChange:B=>w(B.target.value),style:fe.input,children:[s.jsx("option",{value:"invoice",children:"Invoice"}),s.jsx("option",{value:"credit_note",children:"Credit Note"}),s.jsx("option",{value:"delivery_note",children:"Delivery Note"})]})]})]}),s.jsxs("div",{style:fe.row,children:[s.jsxs("label",{style:{...fe.label,flex:1},children:["Invoice Number",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"text",value:o,onChange:B=>a(B.target.value),style:fe.input,placeholder:"e.g., INV-12345"}),la("InvoiceId")&&s.jsx("button",{type:"button",onClick:()=>Lc("InvoiceId"),style:{...fe.eyeBtn,...ae==="InvoiceId"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"}),(_e==null?void 0:_e.status)!=="CONFIRMED"&&s.jsx("button",{type:"button",onClick:L1,style:{background:"none",border:"none",cursor:"pointer",padding:"2px 4px",fontSize:"1rem",color:o?"#ccc":"#007bff",display:"flex",alignItems:"center"},title:"Search OCR for invoice number",children:"🔍"})]})]}),s.jsxs("label",{style:{...fe.label,flex:1},children:["Order/PO Number",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"text",value:y,onChange:B=>v(B.target.value),style:fe.input,placeholder:"e.g., PO-12345"}),la("PurchaseOrder")&&s.jsx("button",{type:"button",onClick:()=>Lc("PurchaseOrder"),style:{...fe.eyeBtn,...ae==="PurchaseOrder"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})]})]})]}),s.jsxs("div",{style:fe.row,children:[s.jsxs("label",{style:{...fe.label,flex:1},children:["Net Total (£)",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"number",step:"0.01",value:f,onChange:B=>p(B.target.value),style:fe.input,placeholder:"Exc. VAT"}),la("SubTotal")&&s.jsx("button",{type:"button",onClick:()=>Lc("SubTotal"),style:{...fe.eyeBtn,...ae==="SubTotal"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})]})]}),s.jsxs("label",{style:{...fe.label,flex:1},children:["Gross Total (£)",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"number",step:"0.01",value:c,onChange:B=>u(B.target.value),style:fe.input,placeholder:"Inc. VAT"}),la("InvoiceTotal")&&s.jsx("button",{type:"button",onClick:()=>Lc("InvoiceTotal"),style:{...fe.eyeBtn,...ae==="InvoiceTotal"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})]})]})]}),s.jsxs("label",{style:fe.label,children:[s.jsxs("span",{children:["Invoice Notes"," ",s.jsx("small",{style:{color:"#666",fontSize:"0.85em"},children:"(Optional, included in Dext etc.)"})]}),s.jsx("textarea",{value:Cr,onChange:B=>Qt(B.target.value),onBlur:async()=>{try{await fetch(`/api/invoices/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({notes:Cr})})}catch(B){console.error("Failed to save notes:",B)}},placeholder:"Add notes about this invoice...",rows:3,style:{...fe.input,resize:"vertical",fontFamily:"inherit"}})]})]}),s.jsxs("div",{style:{marginTop:"20px",display:"flex",gap:"10px"},children:[(_e==null?void 0:_e.document_type)==="credit_note"&&(_e==null?void 0:_e.supplier_id)&&(_e!=null&&_e.linked_dispute_id?s.jsx("button",{onClick:()=>O(_e.linked_dispute_id),style:{padding:"0.75rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold",fontSize:"0.9rem",whiteSpace:"nowrap"},title:"View the dispute resolved by this credit note",children:"✓ Resolved Dispute"}):s.jsx("button",{onClick:()=>Ai(!0),style:{padding:"0.75rem 1rem",background:"#28a745",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold",fontSize:"0.9rem",whiteSpace:"nowrap"},title:"Link this credit note to an open dispute",children:"Link Dispute"})),s.jsx("button",{onClick:M1,style:{...fe.confirmBtn,flex:1,opacity:Qd||Gu.isPending?.5:1,cursor:Qd||Gu.isPending?"not-allowed":"pointer"},disabled:Qd||Gu.isPending,title:Qd?"Fix line item validation errors before confirming":"",children:_e!=null&&_e.dext_sent_at||_e!=null&&_e.supplier_skip_dext?"CONFIRM":"CONFIRM & DEXT"})]}),Yt&&Yt.length>0&&s.jsxs("div",{style:{margin:"20px 0",display:"flex",gap:"8px"},children:[s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`2px solid ${qn.totalsMatch?"#c3e6cb":"#dc2626"}`,background:qn.totalsMatch?"#d4edda":"#fef2f2",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:qn.totalsMatch?"✓":"⛔"}),s.jsx("div",{style:{fontWeight:"600",color:qn.totalsMatch?"#155724":"#dc2626",marginBottom:"2px"},children:"Items Total"}),s.jsx("div",{style:{fontSize:"0.7rem",color:qn.totalsMatch?"#155724":"#dc2626"},children:qn.totalsMatch?"Matches":"Doesn't match"})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`2px solid ${qn.priceCalcErrors===0?"#c3e6cb":"#dc2626"}`,background:qn.priceCalcErrors===0?"#d4edda":"#fef2f2",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:qn.priceCalcErrors===0?"✓":"⛔"}),s.jsx("div",{style:{fontWeight:"600",color:qn.priceCalcErrors===0?"#155724":"#dc2626",marginBottom:"2px"},children:"QTY/Price"}),s.jsx("div",{style:{fontSize:"0.7rem",color:qn.priceCalcErrors===0?"#155724":"#dc2626"},children:qn.priceCalcErrors===0?"All OK":`${qn.priceCalcErrors} error${qn.priceCalcErrors!==1?"s":""}`})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${qn.withoutPortions===0?"#c3e6cb":"#ffc107"}`,background:qn.withoutPortions===0?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:"📦"}),s.jsx("div",{style:{fontWeight:"600",color:qn.withoutPortions===0?"#155724":"#856404",marginBottom:"2px"},children:"Portions"}),s.jsxs("div",{style:{fontSize:"0.7rem",color:qn.withoutPortions===0?"#155724":"#856404"},children:[qn.withPortions," / ",qn.total]})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${qn.missingData===0?"#c3e6cb":"#ffc107"}`,background:qn.missingData===0?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:qn.missingData===0?"✓":"⚠"}),s.jsx("div",{style:{fontWeight:"600",color:qn.missingData===0?"#155724":"#856404",marginBottom:"2px"},children:"Missing Data"}),s.jsxs("div",{style:{fontSize:"0.7rem",color:qn.missingData===0?"#155724":"#856404"},children:[qn.missingData," item",qn.missingData!==1?"s":""]})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${qn.nonStock===0?"#c3e6cb":"#ffc107"}`,background:qn.nonStock===0?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:"🚫"}),s.jsx("div",{style:{fontWeight:"600",color:qn.nonStock===0?"#155724":"#856404",marginBottom:"2px"},children:"Non-Stock"}),s.jsxs("div",{style:{fontSize:"0.7rem",color:qn.nonStock===0?"#155724":"#856404"},children:[qn.nonStock," item",qn.nonStock!==1?"s":""]})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${_e.supplier_skip_dext||_e.dext_sent_at?"#c3e6cb":"#ffc107"}`,background:_e.supplier_skip_dext||_e.dext_sent_at?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:_e.supplier_skip_dext?"−":_e.dext_sent_at?"✓":"⚠"}),s.jsx("div",{style:{fontWeight:"600",color:_e.supplier_skip_dext||_e.dext_sent_at?"#155724":"#856404",marginBottom:"2px"},children:"Dext Status"}),s.jsx("div",{style:{fontSize:"0.7rem",color:_e.supplier_skip_dext||_e.dext_sent_at?"#155724":"#856404"},children:_e.supplier_skip_dext?"N/A (Skipped)":_e.dext_sent_at?new Date(_e.dext_sent_at).toLocaleDateString():"Not sent"})]})]}),_e.disputes&&_e.disputes.length>0&&s.jsx("div",{style:{marginTop:"15px",display:"flex",flexDirection:"column",gap:"10px"},children:_e.disputes.map(B=>{const oe=["NEW","CONTACTED","AWAITING_CREDIT","AWAITING_REPLACEMENT"].includes(B.status);return s.jsxs("div",{onClick:()=>O(B.id),style:{padding:"12px",background:oe?"#fff3cd":"#d1ecf1",border:`2px solid ${oe?"#ffc107":"#17a2b8"}`,borderRadius:"8px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:"pointer"},children:[s.jsxs("div",{children:[s.jsxs("div",{style:{fontWeight:"bold",color:"#1a1a2e",marginBottom:"4px"},children:[oe?"⚠️":"ℹ️"," ",B.status.replace(/_/g," ")]}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666"},children:["#",B.id," - ",B.dispute_type.replace(/_/g," ").toUpperCase()," - ",B.title]})]}),s.jsx("span",{style:{padding:"6px 12px",background:"#e94560",color:"white",borderRadius:"4px",fontSize:"0.85rem",fontWeight:"bold",whiteSpace:"nowrap"},children:"View"})]},B.id)})}),s.jsxs("div",{style:{marginTop:"15px",display:"flex",flexDirection:"column",alignItems:"center",gap:"10px"},children:[s.jsxs("div",{style:{display:"flex",gap:"10px"},children:[(_e.status==="CONFIRMED"||_e.status==="REVIEWED")&&(ui==null?void 0:ui.dext_manual_send_enabled)&&!_e.supplier_skip_dext&&s.jsx("button",{onClick:()=>Lr(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:Qd?"not-allowed":"pointer",minWidth:"130px",whiteSpace:"nowrap",opacity:Qd?.5:1},disabled:Qd,title:Qd?"Fix line item validation errors before sending to Dext":"",children:_e.dext_sent_at?"Resend to Dext":"Send to Dext"}),s.jsx("button",{onClick:()=>C(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",minWidth:"110px",whiteSpace:"nowrap"},children:"Delete Invoice"}),s.jsx("button",{onClick:()=>L(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#f0ad4e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",minWidth:"110px",whiteSpace:"nowrap"},children:"Log Dispute"}),(ui==null?void 0:ui.llm_enabled)&&(ui==null?void 0:ui.anthropic_api_key_set)&&s.jsx("button",{onClick:V1,disabled:is,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:sn?"#6f42c1":"#7952b3",color:"white",border:"none",borderRadius:"4px",cursor:is?"wait":"pointer",minWidth:"120px",whiteSpace:"nowrap",opacity:is?.7:1},children:is?"Analysing...":sn?"✨ AI Results":"✨ AI Assist"}),s.jsx("button",{onClick:()=>G(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#6c757d",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",minWidth:"120px",whiteSpace:"nowrap"},children:"View OCR Data"})]}),(t==null?void 0:t.is_admin)&&s.jsxs("div",{style:{display:"flex",gap:"10px"},children:[!_e.supplier_skip_dext&&s.jsx("button",{onClick:SC,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"140px",whiteSpace:"nowrap"},children:U?"Processing...":"Mark Dext Sent"}),s.jsx("button",{onClick:jC,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#ffc107",color:"#000",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"130px",whiteSpace:"nowrap"},children:U?"Processing...":"Reprocess OCR"}),s.jsx("button",{onClick:W1,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#fd7e14",color:"white",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"150px",whiteSpace:"nowrap"},children:U?"Processing...":"Resend to Azure"}),s.jsx("button",{onClick:kC,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#6f42c1",color:"white",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"160px",whiteSpace:"nowrap"},title:"Regenerate PDF highlight annotations for non-stock items",children:U?"Processing...":"Regen Highlights"})]}),I&&s.jsxs("div",{style:{marginTop:"10px",padding:"12px",borderRadius:"4px",background:I.type==="success"?"#d4edda":"#f8d7da",color:I.type==="success"?"#155724":"#721c24",border:`1px solid ${I.type==="success"?"#c3e6cb":"#f5c6cb"}`,fontSize:"0.85rem",whiteSpace:"pre-wrap",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[s.jsx("span",{children:I.message}),s.jsx("button",{onClick:()=>H(null),style:{background:"transparent",border:"none",fontSize:"1.2rem",cursor:"pointer",marginLeft:"10px",color:"inherit"},children:"×"})]})]})]})]}),(sn||Dt||It.length>0)&&s.jsxs("div",{style:{background:"#f8f5ff",border:"1px solid #d4c5f9",borderRadius:"8px",padding:"1rem",marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[s.jsxs("h3",{style:{margin:0,color:"#5a32a3",fontSize:"1rem"},children:["✨"," AI Analysis"]}),s.jsx("button",{onClick:()=>{ps(null),Tn([]),Ln(null)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",color:"#999"},children:"✕"})]}),Dt&&s.jsx("div",{style:{background:"#f8d7da",color:"#721c24",padding:"0.5rem 0.75rem",borderRadius:"4px",fontSize:"0.85rem",marginBottom:"0.5rem"},children:Dt}),(sn==null?void 0:sn.supplier_match)&&!_e.supplier_id&&s.jsxs("div",{style:{background:"#d1ecf1",padding:"0.5rem 0.75rem",borderRadius:"4px",marginBottom:"0.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{style:{fontSize:"0.85rem",color:"#0c5460"},children:["Supplier: ",s.jsx("strong",{children:sn.supplier_match.name})," (",(sn.supplier_match.confidence*100).toFixed(0),"% confident) — ",sn.supplier_match.reason]}),s.jsx("button",{onClick:()=>K1(sn.supplier_match.id),style:{padding:"0.25rem 0.75rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},children:"Accept"})]}),(sn==null?void 0:sn.total_mismatch_analysis)&&s.jsxs("div",{style:{background:"#fff3cd",padding:"0.5rem 0.75rem",borderRadius:"4px",marginBottom:"0.5rem",fontSize:"0.85rem",color:"#856404"},children:[s.jsx("strong",{children:"Total mismatch:"})," ",sn.total_mismatch_analysis]}),(sn==null?void 0:sn.vat_treatment)&&s.jsxs("div",{style:{background:"#e2e3e5",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.5rem",fontSize:"0.85rem",color:"#383d41"},children:["VAT treatment: ",s.jsx("strong",{children:sn.vat_treatment})]}),(sn==null?void 0:sn.line_item_corrections)&&sn.line_item_corrections.length>0&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Line Item Corrections"}),sn.line_item_corrections.filter(B=>!Fi.has(`${B.idx}-${B.field}`)).map((B,oe)=>s.jsxs("div",{style:{background:"#ffe6e6",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#721c24"},children:["Line ",B.idx+1,": ",s.jsx("strong",{children:B.field})," ",B.current," ","→"," ",B.suggested," — ",B.reason]}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem"},children:[s.jsx("button",{onClick:()=>G1(B.idx,B.field,B.suggested),style:{padding:"0.2rem 0.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Apply"}),s.jsx("button",{onClick:()=>Zr(be=>new Set([...be,`${B.idx}-${B.field}`])),style:{padding:"0.2rem 0.5rem",background:"#6c757d",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Dismiss"})]})]},oe))]}),(sn==null?void 0:sn.subtotal_flags)&&sn.subtotal_flags.length>0&&Yt&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Subtotal / Fee Rows"}),sn.subtotal_flags.map(B=>{var be;const oe=Yt[B];return oe?s.jsxs("div",{style:{background:"#fff3cd",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#856404"},children:["Line ",B+1,': "',(be=oe.description)==null?void 0:be.substring(0,50),'" — appears to be a subtotal or fee, not a product']}),!oe.is_non_stock&&s.jsx("button",{onClick:()=>Jl.mutate({itemId:oe.id,data:{is_non_stock:!0}}),style:{padding:"0.2rem 0.5rem",background:"#f0ad4e",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Mark Non-Stock"})]},B):null})]}),(sn==null?void 0:sn.description_recommendations)&&sn.description_recommendations.length>0&&Yt&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Description Recommendations"}),sn.description_recommendations.filter(B=>B.recommendation!=="keep").map((B,oe)=>{const be=Yt[B.idx];return!be||!be.description_alt?null:s.jsxs("div",{style:{background:"#d1ecf1",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#0c5460"},children:["Line ",B.idx+1,": Swap description recommended — ",B.reason]}),s.jsx("button",{onClick:()=>Jl.mutate({itemId:be.id,data:{description:be.description_alt,description_alt:be.description}}),style:{padding:"0.2rem 0.5rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Swap"})]},oe)})]}),(sn==null?void 0:sn.pack_size_suggestions)&&sn.pack_size_suggestions.length>0&&Yt&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Pack Size (from description)"}),sn.pack_size_suggestions.map((B,oe)=>{var en;const be=Yt[B.idx];if(!be)return null;const Ae=B.pack_quantity>1?`${B.pack_quantity} × ${B.unit_size}${B.unit_size_type}`:`${B.unit_size}${B.unit_size_type}`,it=be.pack_quantity&&be.unit_size;return s.jsxs("div",{style:{background:it?"#e8e8e8":"#e8daef",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:it?"#666":"#4a235a"},children:["Line ",B.idx+1,': "',(en=be.description)==null?void 0:en.substring(0,40),'" → ',s.jsx("strong",{children:Ae}),it&&" (already set)"]}),!it&&s.jsx("button",{onClick:()=>Jl.mutate({itemId:be.id,data:{pack_quantity:B.pack_quantity,unit_size:B.unit_size,unit_size_type:B.unit_size_type}}),style:{padding:"0.2rem 0.5rem",background:"#7d3c98",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Apply"})]},oe)})]}),It.length>0&&Yt&&s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Ingredient Matches (from supplier history)"}),It.map((B,oe)=>{var Ae;const be=Yt[B.idx];return be?s.jsxs("div",{style:{background:"#d4edda",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#155724"},children:["Line ",B.idx+1,' "',(Ae=be.description)==null?void 0:Ae.substring(0,40),'" ',"→"," ",s.jsx("strong",{children:B.ingredient_name})," (",(B.confidence*100).toFixed(0),"%) — ",B.reason]}),s.jsx("button",{onClick:()=>Jl.mutate({itemId:be.id,data:{ingredient_id:B.ingredient_id}}),style:{padding:"0.2rem 0.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Map"})]},oe):null})]})]}),s.jsxs("div",{style:fe.lineItemsSection,children:[s.jsxs("div",{style:{marginBottom:"10px"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"10px"},children:[s.jsx("h3",{style:{margin:"0"},children:"Line Items"}),s.jsx("button",{onClick:()=>{if(He){if(ge!==null&&!window.confirm("You have unsaved changes. Are you sure you want to exit edit mode?"))return;Te(null),he({}),Ge(!1)}else Ge(!0),(!Yt||Yt.length===0)&&$0()},style:{...fe.editBtn,background:He?"#dc3545":"#f0f0f0",color:He?"white":"#333",border:He?"none":"1px solid #ddd",padding:"0.5rem 1rem",fontSize:"0.85rem"},children:He?"✕ Exit Edit Mode":"✏️ Edit Line Items"})]}),Yt&&Yt.length>0&&s.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center"},children:[s.jsx("input",{type:"text",placeholder:"Search by code or description...",value:hn,onChange:B=>Ti(B.target.value),style:{flex:1,padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db",fontSize:"0.9rem"}}),s.jsxs("label",{style:{fontSize:"0.9rem",color:"#6b7280"},children:["Price:",s.jsxs("select",{value:tn,onChange:B=>ci(B.target.value),style:{marginLeft:"5px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db"},children:[s.jsx("option",{value:"",children:"All"}),s.jsx("option",{value:"consistent",disabled:Nc.consistent===0,children:"✓ Consistent"}),s.jsx("option",{value:"amber",disabled:Nc.amber===0,children:"? Changed"}),s.jsx("option",{value:"red",disabled:Nc.red===0,children:"! Large change"}),s.jsx("option",{value:"no_history",disabled:Nc.no_history===0,children:"No history"})]})]}),s.jsxs("label",{style:{fontSize:"0.9rem",color:"#6b7280"},children:["Portions:",s.jsxs("select",{value:js,onChange:B=>Ar(B.target.value),style:{marginLeft:"5px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db"},children:[s.jsx("option",{value:"",children:"All"}),s.jsx("option",{value:"yes",disabled:Nc.withPortions===0,children:"📦 Yes"}),s.jsx("option",{value:"no",disabled:Nc.withoutPortions===0,children:"○ No"})]})]}),s.jsxs("label",{style:{fontSize:"0.9rem",color:"#6b7280"},children:["Data:",s.jsxs("select",{value:fs,onChange:B=>Qs(B.target.value),style:{marginLeft:"5px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db"},children:[s.jsx("option",{value:"",children:"All"}),s.jsx("option",{value:"missing",disabled:Nc.missingData===0,children:"⚠ Missing key data"})]})]}),(gi||tn||hn||js||fs)&&s.jsx("button",{onClick:()=>{je(""),ci(""),Ti(""),Ar(""),Qs("")},style:{padding:"4px 10px",fontSize:"0.85rem",color:"#6b7280",background:"#f3f4f6",border:"1px solid #d1d5db",borderRadius:"4px",cursor:"pointer"},children:"Clear"})]})]}),Yt&&Yt.length>0||He?s.jsx("div",{style:fe.lineItemsTableContainer,ref:Pa,children:s.jsxs("table",{style:fe.lineItemsTable,children:[s.jsxs("thead",{style:fe.stickyThead,children:[s.jsxs("tr",{children:[s.jsx("th",{style:{...fe.th,width:"30px"}}),s.jsxs("th",{style:{...fe.th,width:"80px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("code"),children:["Code ",gi==="code"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,minWidth:"240px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("description"),children:["Description ",gi==="description"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,width:"50px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("unit"),children:["Unit ",gi==="unit"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,width:"50px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("quantity"),children:["Qty ",gi==="quantity"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,width:"110px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("unit_price"),children:["Price ",gi==="unit_price"&&(bt==="asc"?"↑":"↓")]}),s.jsx("th",{style:{...fe.th,width:"50px"},children:"Tax"}),s.jsxs("th",{style:{...fe.th,width:"70px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("amount"),children:["Total ",gi==="amount"&&(bt==="asc"?"↑":"↓")]}),s.jsx("th",{style:{...fe.th,textAlign:"center",width:"60px",cursor:"pointer",userSelect:"none"},onClick:()=>J(!0),title:"Click to mark all items as stock or non-stock",children:"Stock"}),s.jsx("th",{style:{...fe.th,textAlign:"center",width:"40px"},title:"Cost Breakdown"}),s.jsx("th",{style:{...fe.th,width:"70px"}})]}),_e&&_e.total_pages&&_e.total_pages>1&&!gi&&!hn&&!tn&&!js&&!fs&&s.jsx("tr",{children:s.jsxs("th",{colSpan:11,style:fe.stickyPageIndicatorCell,children:["Page ",Lo," of ",_e.total_pages]})})]}),s.jsxs("tbody",{children:[[...tx,...ge===-1?[{id:-1,product_code:Be.product_code||"",description:Be.description||"",description_alt:null,unit:Be.unit||"",quantity:Be.quantity??null,order_quantity:null,unit_price:Be.unit_price??null,tax_rate:Be.tax_rate||"",tax_amount:null,amount:Be.amount??null,line_number:Be.line_number||0,is_non_stock:Be.is_non_stock||!1,raw_content:null,pack_quantity:null,unit_size:null,unit_size_type:null,portions_per_unit:null,cost_per_item:null,cost_per_portion:null,ocr_warnings:null,price_change_status:null,price_change_percent:null,previous_price:null,future_price:null,future_change_percent:null,page_number:null,_originalIndex:-1}]:[]].map((B,oe,be)=>{var nw,rw,iw,sw,ow,aw,rx;const Ae=F1(B._originalIndex),it=(ui==null?void 0:ui.high_quantity_threshold)??100,en=B.quantity!==null&&B.quantity>it,rn=Vu==null?void 0:Vu[B.id.toString()],Nn=(rn==null?void 0:rn.has_history)&&rn.previously_non_stock&&!B.is_non_stock,Qn=B.quantity!=null&&B.quantity!==0,gr=B.unit_price!=null&&B.unit_price!==0,br=B.amount!=null&&B.amount!==0,mr=(B.quantity||0)*(B.unit_price||0),Wi=B.amount||0,er=Math.abs(mr-Wi)>.02,lr=gr&&(!Qn||!br)||br&&(!Qn||!gr)||Qn&&gr&&br&&er,Kt=(nw=_e.disputed_line_item_ids)==null?void 0:nw.includes(B.id),Fn=_e&&_e.total_pages&&_e.total_pages>1&&!gi&&!hn&&!tn&&!js&&!fs&&B.page_number&&oefC(B.id,B._originalIndex),style:{...fe.eyeBtn,padding:"0.25rem 0.4rem",fontSize:"0.8rem",...de===B.id?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})}),ge===B.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.product_code||"":B.product_code||"",onChange:vr=>{ed(B),he({...Be,product_code:vr.target.value})},style:{...fe.tableInput,width:"70px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.description||"":B.description||"",onChange:vr=>{ed(B),he({...Be,description:vr.target.value})},style:fe.tableInput})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.unit||"":B.unit||"",onChange:vr=>{ed(B),he({...Be,unit:vr.target.value})},style:{...fe.tableInput,width:"50px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"number",step:"0.01",value:ge===B.id?Be.quantity??"":B.quantity??"",onChange:vr=>{ed(B),he({...Be,quantity:parseFloat(vr.target.value)})},style:{...fe.tableInput,width:"50px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"number",step:"0.01",value:ge===B.id?Be.unit_price??"":B.unit_price??"",onChange:vr=>{ed(B),he({...Be,unit_price:parseFloat(vr.target.value)})},style:{...fe.tableInput,width:"70px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.tax_rate||"":B.tax_rate||"",onChange:vr=>{ed(B),he({...Be,tax_rate:vr.target.value})},style:{...fe.tableInput,width:"50px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"number",step:"0.01",value:ge===B.id?Be.amount??"":B.amount??"",onChange:vr=>{ed(B),he({...Be,amount:parseFloat(vr.target.value)})},style:{...fe.tableInput,width:"60px"}})}),s.jsx("td",{style:{...fe.td,textAlign:"center"},children:s.jsx("input",{type:"checkbox",checked:ge===B.id?!Be.is_non_stock:!B.is_non_stock,onChange:vr=>{ed(B),he({...Be,is_non_stock:!vr.target.checked})},style:{width:"18px",height:"18px",cursor:"pointer"}})}),s.jsx("td",{style:{...fe.td,textAlign:"center"}}),s.jsx("td",{style:fe.td,children:s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("button",{onClick:()=>_C(B.id),style:{padding:"0.35rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem",display:"flex",alignItems:"center",justifyContent:"center",minWidth:"32px",height:"32px"},title:"Save changes",children:"✅"}),s.jsx("button",{onClick:CC,style:{padding:"0.35rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem",display:"flex",alignItems:"center",justifyContent:"center",minWidth:"32px",height:"32px"},title:"Cancel editing",children:"❌"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsx("td",{style:{...fe.td,fontSize:"0.85rem",color:"#666"},children:s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px"},children:[s.jsx("span",{style:B.ocr_warnings?{background:"#fff3cd",padding:"2px 6px",borderRadius:"3px",border:"1px solid #ffc107"}:void 0,children:B.product_code||"—"}),B.ocr_warnings&&s.jsx("span",{title:B.ocr_warnings,style:{cursor:"help",fontSize:"1rem"},children:"⚠️"})]})}),s.jsxs("td",{style:{...fe.td,...B.is_non_stock?{color:"#856404",fontStyle:"italic"}:{}},children:[s.jsxs("div",{children:[ffe(B.description)||"—",B.description_alt&&B.description!==B.description_alt&&s.jsx("button",{onClick:vr=>{vr.stopPropagation(),we(B)},style:{background:"none",border:"none",cursor:"pointer",padding:"2px 6px",fontSize:"0.9rem",color:"#e94560",marginLeft:"6px"},title:"OCR detected alternative description - click to compare",children:"🔄"}),((iw=_e.disputed_line_item_ids)==null?void 0:iw.includes(B.id))&&s.jsx("span",{style:{marginLeft:"8px",color:"#e94560",fontSize:"0.7rem",fontWeight:"bold",padding:"2px 6px",background:"#ffe0e6",borderRadius:"3px"},children:"[DISPUTED]"})]}),Nn&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#856404",fontStyle:"italic",marginTop:"4px",lineHeight:"1.2"},children:"⚠️ This item has previously been marked as not a stock item"}),lr&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#dc3545",fontWeight:"bold",marginTop:"4px",lineHeight:"1.3"},children:["! QTY x Price = Total Check Failed",s.jsx("br",{}),(sw=B.quantity)==null?void 0:sw.toFixed(2)," × £",(ow=B.unit_price)==null?void 0:ow.toFixed(2)," ≠ £",(aw=B.amount)==null?void 0:aw.toFixed(2)]}),!B.ingredient_id&&!B.product_code&&B.description&&(()=>{const vr=B.description.split(` `)[0].trim().toLowerCase(),Gr=Qe[vr];if(!Gr)return null;const Ho=kt===vr;return s.jsxs("div",{style:{fontSize:"0.75rem",color:"#0c5460",background:"#d1ecf1",padding:"0.25rem 0.5rem",borderRadius:"4px",marginTop:"4px",border:"1px solid #bee5eb",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsxs("span",{children:['Similar to "',Gr.canonical_description,'"',Gr.ingredient_name&&s.jsxs(s.Fragment,{children:[" → ",Gr.ingredient_name]})," ","(",Math.round(Gr.similarity*100),"% match)",Gr.price_difference!=null&&Gr.price_difference>5&&s.jsxs("span",{style:{color:"#856404",marginLeft:"6px"},children:["Price differs ",Gr.price_difference.toFixed(0),"%"]})]}),s.jsx("button",{type:"button",onClick:Qu=>{Qu.stopPropagation(),Ht(vr),xC.mutate({sourceId:Gr.source_id,alias:B.description.split(` `)[0].trim()})},disabled:Ho,style:{padding:"0.2rem 0.5rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:Ho?"default":"pointer",fontSize:"0.7rem",fontWeight:"500",whiteSpace:"nowrap",opacity:Ho?.6:1},children:Ho?"Adding...":"+ Add as alias"})]})})()]}),s.jsx("td",{style:{...fe.td,fontSize:"0.85rem"},children:B.unit||"—"}),s.jsx("td",{style:{...fe.td,...Uo},children:((rx=B.quantity)==null?void 0:rx.toFixed(2))||"—"}),s.jsxs("td",{style:{...fe.td,...da,position:"relative"},children:[s.jsxs("div",{style:{display:"inline-block",verticalAlign:"middle",whiteSpace:"nowrap"},children:[B.unit_price!=null?`£${B.unit_price.toFixed(2)}`:"—",B.price_change_status==="consistent"&&s.jsx("span",{style:{marginLeft:"6px",color:"#22c55e",fontWeight:"bold"},children:"✓"}),B.price_change_status==="no_history"&&s.jsx("span",{style:{marginLeft:"6px",color:"#22c55e"},children:"📄⁺"}),B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_status!=="consistent"&&s.jsx("span",{style:{marginLeft:"6px",color:"#f59e0b"},children:"🪙"})]}),B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_status!=="consistent"&&B.price_change_percent!==null&&B.price_change_percent!==0&&(()=>{const vr=B.price_change_percent>0,Gr=vr?"▲":"▼",Ho=vr?"#ef4444":"#22c55e";return s.jsxs("div",{onClick:()=>Z0(B),style:{position:"absolute",bottom:"0.2rem",left:"0.5rem",fontSize:"0.65rem",lineHeight:"1",color:Ho,cursor:"pointer"},title:"View price history",children:[s.jsx("span",{style:{fontWeight:"bold"},children:Gr})," ",Math.abs(B.price_change_percent).toFixed(1),"%"]})})(),B.future_change_percent!==null&&B.future_change_percent!==0&&(()=>{const Gr=B.future_change_percent>0?"▲":"▼";return s.jsxs("div",{onClick:()=>Z0(B),style:{position:"absolute",bottom:"0.2rem",left:"0.5rem",fontSize:"0.75rem",color:"#9ca3af",cursor:"pointer"},title:"Price changed after this invoice",children:["(",s.jsx("span",{style:{fontWeight:"bold"},children:Gr})," ",Math.abs(B.future_change_percent).toFixed(1),"%)"]})})()]}),s.jsx("td",{style:{...fe.td,fontSize:"0.85rem",...da},children:B.tax_rate||"—"}),s.jsx("td",{style:{...fe.td,...zf},children:B.amount?`£${B.amount.toFixed(2)}`:"—"}),s.jsx("td",{style:{...fe.td,textAlign:"center"},children:s.jsx("input",{type:"checkbox",checked:!B.is_non_stock,onChange:vr=>{Jl.mutate({itemId:B.id,data:{is_non_stock:!vr.target.checked}})},style:{width:"18px",height:"18px",cursor:"pointer"},title:B.is_non_stock?"Mark as stock item":"Mark as non-stock item"})}),s.jsx("td",{style:{...fe.td,textAlign:"center"},children:s.jsx("button",{type:"button",onClick:()=>X1(B),style:{...fe.scaleBtn,...(nn==null?void 0:nn.id)===B.id?fe.scaleBtnActive:{},color:hfe(B)},title:B.ingredient_id?`Mapped → ${B.ingredient_name||"Ingredient"}`:B.pack_quantity?B.portions_per_unit===null?"Pack data extracted - click to map ingredient":"Pack data complete - click to map ingredient":"No pack data - click to map ingredient",children:s.jsx(cfe,{})})}),s.jsx("td",{style:{...fe.td,minWidth:"135px",whiteSpace:"nowrap",verticalAlign:"middle"},children:s.jsx("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:He?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>U1(B),style:fe.iconBtn,title:"Edit line item",children:"✏️"}),s.jsx("button",{onClick:()=>pD(B.id),style:{...fe.iconBtn,color:"#dc3545"},title:"Delete line item",children:"🗑️"})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>TC(B),style:fe.iconBtn,title:"Search similar items",children:"🔍"}),s.jsx("button",{onClick:()=>B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null&&Z0(B),style:{...fe.iconBtn,opacity:B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null?1:.5,cursor:B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null?"pointer":"not-allowed"},title:B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null?"View price history":"No price history available",disabled:!(B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null),children:"📊"})]})})})]})]}),de===B.id&&Ae&&s.jsx("tr",{children:s.jsx("td",{colSpan:11,style:fe.lineItemPreviewCell,children:Yu&&Je.length>0?(()=>{const vr=Ae.pageNumber-1,Gr=Je[vr];if(!Gr)return null;const Ho=Ae.x/100*Gr.width,Qu=Ae.y/100*Gr.height,Of=Ae.width/100*Gr.width,lw=Ae.height/100*Gr.height,$u=15,dw=Math.max(0,Ho-$u),Xg=Math.max(0,Qu-$u),cw=Of+$u*2,uw=lw+$u*2,Yg=5,ix=Math.max(0,dw-Yg),Lf=Math.max(0,Xg-Yg),hw=Math.min(Gr.width,dw+cw+Yg),PC=Math.min(Gr.height,Xg+uw+Yg),Zu=hw-ix,Qg=PC-Lf,fw=dw-ix,gD=Xg-Lf,Nf=document.createElement("canvas");Nf.width=Zu,Nf.height=Qg;const pw=Nf.getContext("2d");return pw&&pw.drawImage(Gr.canvas,ix,Lf,Zu,Qg,0,0,Zu,Qg),s.jsx("div",{style:fe.lineItemPreviewContainer,children:s.jsxs("div",{style:{position:"relative",display:"block",width:"100%"},children:[s.jsx("img",{src:Nf.toDataURL(),alt:"Line item from invoice",style:{width:"100%",height:"auto",display:"block"}}),s.jsx("div",{style:{position:"absolute",left:`${fw/Zu*100}%`,top:`${gD/Qg*100}%`,width:`${cw/Zu*100}%`,height:`${uw/Qg*100}%`,border:"2px solid #ffc107",borderRadius:"2px",pointerEvents:"none",boxShadow:"0 0 8px rgba(255, 193, 7, 0.5)"}})]})})})():Mf?(()=>{const Gr=Math.max(0,Ae.x-2),Ho=Math.max(0,Ae.y-2),Qu=Math.min(100-Gr,Ae.width+2*2),Of=Math.min(100-Ho,Ae.height+2*2);return s.jsx("div",{style:fe.lineItemPreviewContainer,children:s.jsxs("div",{style:{position:"relative",display:"block",width:"100%"},children:[s.jsx("img",{src:`${Mf.split("?")[0]}?token=${encodeURIComponent(e||"")}`,alt:"Line item location",style:{width:"100%",height:"auto",display:"block"}}),s.jsx("div",{style:{position:"absolute",left:`${Gr}%`,top:`${Ho}%`,width:`${Qu}%`,height:`${Of}%`,border:"2px solid #ffc107",borderRadius:"2px",pointerEvents:"none",boxShadow:"0 0 8px rgba(255, 193, 7, 0.5)"}})]})})})():null})})]},B.id)}),He&&s.jsx("tr",{children:s.jsx("td",{colSpan:11,style:{textAlign:"center",padding:"1.5rem",background:"#f9fafb"},children:s.jsx("button",{onClick:$0,style:{...fe.confirmBtn,padding:"0.75rem 2rem",fontSize:"0.95rem"},children:"+ Add Line Item"})})})]})]})}):s.jsx("p",{style:fe.noItems,children:"No line items extracted"}),s.jsx(gfe,{lineItems:Yt||[],invoiceTotal:parseFloat(c)||0,netTotal:f?parseFloat(f):null})]}),b&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>C(!1),children:s.jsxs("div",{style:fe.modal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Delete Invoice?"}),s.jsxs("div",{style:fe.modalInfo,children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",_e.invoice_number||"N/A"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",_e.invoice_date||"N/A"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",_e.total?`£${Number(_e.total).toFixed(2)}`:"N/A"]})]}),_e.duplicate_status&&s.jsxs("div",{style:fe.modalDuplicateInfo,children:["This invoice is marked as a ",_e.duplicate_status==="firm_duplicate"?"duplicate":"possible duplicate",". Deleting it will resolve the duplicate warning."]}),s.jsxs("div",{style:fe.modalActions,children:[s.jsx("button",{onClick:()=>C(!1),style:fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:wC,style:fe.confirmDeleteBtn,children:"Delete"})]})]})}),Ci&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>Lr(!1),children:s.jsxs("div",{style:fe.modal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Send Invoice to Dext?"}),s.jsx("p",{style:{marginBottom:"1rem"},children:"This will email the invoice PDF to your configured Dext address."}),Cr&&s.jsxs("p",{style:{fontSize:"0.9rem",color:"#666"},children:[s.jsx("strong",{children:"Note:"})," Invoice notes will be included in the email."]}),Yt&&Yt.some(B=>B.is_non_stock)&&s.jsxs("p",{style:{fontSize:"0.9rem",color:"#666"},children:[s.jsx("strong",{children:"Note:"})," Non-stock items table will be included in the email."]}),s.jsxs("div",{style:fe.modalActions,children:[s.jsx("button",{onClick:()=>Lr(!1),style:fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:async()=>{try{const B=await fetch(`/api/invoices/${n}/send-to-dext`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(B.ok){const oe=await B.json();alert(`Invoice sent to Dext successfully at ${new Date(oe.sent_at).toLocaleString()}`),Lr(!1),i.invalidateQueries({queryKey:["invoice",n]})}else{const oe=await B.json();alert(`Failed to send: ${oe.detail}`)}}catch(B){console.error("Failed to send to Dext:",B),alert("Failed to send invoice to Dext")}},style:fe.confirmBtn,children:"Send to Dext"})]})]})}),T&&Li&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>F(!1),children:s.jsxs("div",{style:fe.wideModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Duplicate Comparison"}),s.jsxs("div",{style:fe.compareGrid,children:[s.jsxs("div",{style:fe.compareCard,children:[s.jsx("h4",{children:"Current Invoice"}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",Li.current_invoice.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",Li.current_invoice.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",Li.current_invoice.total?`£${Number(Li.current_invoice.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",Li.current_invoice.order_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Type:"})," ",Li.current_invoice.document_type||"invoice"]})]}),Li.firm_duplicate&&s.jsxs("div",{style:{...fe.compareCard,borderColor:"#dc3545"},children:[s.jsx("h4",{style:{color:"#dc3545"},children:"Exact Duplicate"}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",Li.firm_duplicate.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",Li.firm_duplicate.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",Li.firm_duplicate.total?`£${Number(Li.firm_duplicate.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",Li.firm_duplicate.order_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Type:"})," ",Li.firm_duplicate.document_type||"invoice"]}),s.jsx("button",{onClick:()=>r(`/invoice/${Li.firm_duplicate.id}`),style:fe.viewBtn,children:"View This Invoice"})]}),Li.possible_duplicates.map(B=>s.jsxs("div",{style:{...fe.compareCard,borderColor:"#ffc107"},children:[s.jsx("h4",{style:{color:"#856404"},children:"Possible Duplicate"}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",B.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",B.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",B.total?`£${Number(B.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",B.order_number||"—"]}),s.jsx("button",{onClick:()=>r(`/invoice/${B.id}`),style:fe.viewBtn,children:"View This Invoice"})]},B.id)),Li.related_documents.map(B=>s.jsxs("div",{style:{...fe.compareCard,borderColor:"#17a2b8"},children:[s.jsxs("h4",{style:{color:"#17a2b8"},children:["Related ",B.document_type==="delivery_note"?"Delivery Note":"Invoice"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",B.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",B.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",B.total?`£${Number(B.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",B.order_number||"—"]}),s.jsx("button",{onClick:()=>r(`/invoice/${B.id}`),style:fe.viewBtn,children:"View This Invoice"})]},B.id))]}),s.jsx("button",{onClick:()=>F(!1),style:fe.closeBtn,children:"Close"})]})}),A&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>D(!1),children:s.jsxs("div",{style:fe.modal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Create New Supplier"}),s.jsxs("label",{style:fe.modalLabel,children:["Supplier Name",s.jsx("input",{type:"text",value:ee,onChange:B=>Z(B.target.value),style:fe.input,placeholder:"e.g., Sysco, US Foods",autoFocus:!0})]}),s.jsxs("div",{style:fe.modalActions,children:[s.jsx("button",{onClick:()=>D(!1),style:fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:B1,style:fe.saveBtn,disabled:!ee.trim()||X0.isPending,children:X0.isPending?"Creating...":"Create & Select"})]})]})}),z&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>G(!1),children:s.jsxs("div",{style:fe.rawOcrModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Raw Azure OCR Data"}),s.jsx("p",{style:fe.rawOcrHint,children:"This shows the raw data extracted by Azure. Use this to debug field extraction issues or identify custom field names that need mapping."}),ks!=null&&ks.raw_json?s.jsxs("div",{style:fe.rawOcrContent,children:[s.jsx("h4",{children:"Extracted Fields"}),(J1=ks.raw_json.documents)==null?void 0:J1.map((B,oe)=>s.jsxs("div",{style:fe.rawOcrDoc,children:[s.jsxs("h5",{children:["Document ",oe+1," (Confidence: ",(B.confidence*100).toFixed(1),"%)"]}),s.jsxs("table",{style:fe.rawOcrTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:fe.rawOcrTh,children:"Field"}),s.jsx("th",{style:fe.rawOcrTh,children:"Value"}),s.jsx("th",{style:fe.rawOcrTh,children:"Content"})]})}),s.jsx("tbody",{children:Object.entries(B.fields||{}).map(([be,Ae])=>s.jsxs("tr",{children:[s.jsx("td",{style:fe.rawOcrTd,children:s.jsx("strong",{children:be})}),s.jsx("td",{style:fe.rawOcrTd,children:typeof(Ae==null?void 0:Ae.value)=="object"?JSON.stringify(Ae==null?void 0:Ae.value,null,2):String((Ae==null?void 0:Ae.value)??"—")}),s.jsx("td",{style:fe.rawOcrTd,children:(Ae==null?void 0:Ae.content)||"—"})]},be))})]})]},oe))]}):s.jsx("p",{style:{color:"#999"},children:"No raw OCR data available for this invoice."}),s.jsx("button",{onClick:()=>G(!1),style:fe.closeBtn,children:"Close"})]})}),Vd&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>Gn(!1),children:s.jsxs("div",{style:{...fe.rawOcrModal,maxWidth:"480px"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{style:{marginTop:0,marginBottom:"0.75rem"},children:"Previously Non-Stock Items"}),s.jsxs("p",{style:{fontSize:"0.9rem",color:"#555",marginBottom:"1rem",lineHeight:1.5},children:["The following item",Dr.length!==1?"s have":" has"," been marked as ",s.jsx("strong",{children:"non-stock"})," on previous invoices from this supplier but ",Dr.length!==1?"are":"is"," currently included in the stock cost for this invoice. Please confirm they have been checked."]}),s.jsx("div",{style:{marginBottom:"1.25rem",borderRadius:"6px",border:"1px solid #f0c36d",background:"#fffbf0",overflow:"hidden"},children:Dr.map((B,oe)=>{var be;return s.jsxs("div",{style:{padding:"0.6rem 0.85rem",borderBottom:oeGn(!1),style:{...fe.closeBtn,margin:0},children:"Go back"}),s.jsx("button",{onClick:async()=>{Gn(!1),await z1()},style:{padding:"0.5rem 1.25rem",background:"#e85d04",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},children:"Confirm anyway"})]})]})}),Ks&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>un(!1),children:s.jsxs("div",{style:{...fe.rawOcrModal,maxWidth:"520px"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Select Invoice Date"}),(()=>{var be;const B=la("InvoiceDate");if(!B)return null;if(((be=_e==null?void 0:_e.image_path)==null?void 0:be.toLowerCase().endsWith(".pdf"))&&Je.length>0){const Ae=Je[B.pageNumber-1];if(!Ae)return null;const it=B.x/100*Ae.width,en=B.y/100*Ae.height,rn=B.width/100*Ae.width,Nn=B.height/100*Ae.height,Qn=20,gr=Math.max(0,it-Qn*3),br=Math.max(0,en-Qn),mr=Math.min(Ae.width,it+rn+Qn*3),Wi=Math.min(Ae.height,en+Nn+Qn),er=mr-gr,lr=Wi-br,Kt=document.createElement("canvas");Kt.width=er,Kt.height=lr;const Fn=Kt.getContext("2d");return Fn&&(Fn.drawImage(Ae.canvas,gr,br,er,lr,0,0,er,lr),Fn.strokeStyle="#e85d04",Fn.lineWidth=3,Fn.strokeRect(it-gr-4,en-br-4,rn+8,Nn+8)),s.jsxs("div",{style:{marginBottom:"1rem",border:"1px solid #ddd",borderRadius:"6px",overflow:"hidden"},children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#666",padding:"4px 8px",background:"#f8f9fa",borderBottom:"1px solid #ddd"},children:"Date field from document"}),s.jsx("img",{src:Kt.toDataURL(),alt:"Date field from invoice",style:{width:"100%",height:"auto",display:"block"}})]})}return null})(),l&&bx(l,"PENDING")==="future"&&(()=>{const B=new Date;B.setHours(0,0,0,0);const oe=NN(l),be=oe&&new Date(oe)<=B,Ae=WN(l);if(!be&&!Ae)return null;const it=[];return Ae&&it.push({date:Ae.date,label:new Date(Ae.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"}),sublabel:`Year corrected from ${l.split("-")[0]} → ${Ae.year}`}),be&&oe&&it.push({date:oe,label:new Date(oe).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"}),sublabel:`Day and month swapped from ${new Date(l).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}`}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{fontSize:"0.8rem",fontWeight:600,color:"#e85d04",marginBottom:"0.5rem"},children:["⚠ Suggested fix",it.length>1?"es":""," — date is in the future:"]}),it.map((en,rn)=>s.jsxs("div",{onClick:()=>Q0(en.date),style:{padding:"0.75rem 1rem",border:"2px solid #e85d04",borderRadius:"4px",cursor:"pointer",background:"#fff8f5",transition:"all 0.2s",marginBottom:rn{Nn.currentTarget.style.background="#fff0e8"},onMouseLeave:Nn=>{Nn.currentTarget.style.background="#fff8f5"},children:[s.jsx("div",{style:{fontWeight:"600",fontSize:"1.1rem",marginBottom:"0.25rem"},children:en.label}),s.jsx("div",{style:{fontSize:"0.8rem",color:"#888"},children:en.sublabel})]},rn)),Fr.length>0&&s.jsx("div",{style:{borderTop:"1px solid #eee",marginTop:"1rem",paddingTop:"0.75rem",fontSize:"0.8rem",color:"#666",marginBottom:"0.5rem"},children:"Or choose a date found in the document:"})]})})(),!l&&s.jsx("p",{style:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},children:"Dates found in the document. Click to select."}),l&&bx(l,"PENDING")!=="future"&&s.jsx("p",{style:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},children:"Dates found in the document. Click to select."}),aa?s.jsx("p",{style:{color:"#999",textAlign:"center",padding:"2rem"},children:"Searching for dates..."}):Fr.length===0?l&&bx(l,"PENDING")==="future"?null:s.jsx("p",{style:{color:"#999",textAlign:"center",padding:"2rem"},children:"No dates found in document text."}):s.jsx("div",{style:{maxHeight:"400px",overflowY:"auto"},children:Fr.filter(B=>{if(!l||bx(l,"PENDING")!=="future")return!0;const oe=new Date;oe.setHours(0,0,0,0);const be=NN(l);if(be&&new Date(be)<=oe&&B.date===be)return!1;const Ae=WN(l);return!(Ae&&B.date===Ae.date)}).map((B,oe)=>{const be=B.bbox?D1(B.bbox,{padX:80,padY:25,strokeColor:"#e85d04"}):null;return s.jsxs("div",{onClick:()=>Q0(B.date),style:{marginBottom:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s",background:"#fff",overflow:"hidden"},onMouseEnter:Ae=>{Ae.currentTarget.style.background="#f0f7ff",Ae.currentTarget.style.borderColor="#007bff"},onMouseLeave:Ae=>{Ae.currentTarget.style.background="#fff",Ae.currentTarget.style.borderColor="#ddd"},children:[be&&s.jsx("img",{src:be,alt:"Date location in document",style:{width:"100%",height:"auto",display:"block",borderBottom:"1px solid #eee"}}),s.jsxs("div",{style:{padding:"0.75rem 1rem"},children:[s.jsx("div",{style:{fontWeight:"600",fontSize:"1.1rem",marginBottom:"0.25rem"},children:new Date(B.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"})}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666"},children:["Original: ",B.original]}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem",fontStyle:"italic"},children:["...",B.context,"..."]})]})]},oe)})}),s.jsx("button",{onClick:()=>un(!1),style:fe.closeBtn,children:"Cancel"})]})}),Ss&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>rs(!1),children:s.jsxs("div",{style:{...fe.rawOcrModal,maxWidth:"520px"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Find Invoice Number"}),(()=>{var be;const B=la("InvoiceId");if(!B)return null;if(((be=_e==null?void 0:_e.image_path)==null?void 0:be.toLowerCase().endsWith(".pdf"))&&Je.length>0){const Ae=Je[B.pageNumber-1];if(!Ae)return null;const it=B.x/100*Ae.width,en=B.y/100*Ae.height,rn=B.width/100*Ae.width,Nn=B.height/100*Ae.height,Qn=20,gr=Math.max(0,it-Qn*3),br=Math.max(0,en-Qn),mr=Math.min(Ae.width,it+rn+Qn*3),Wi=Math.min(Ae.height,en+Nn+Qn),er=mr-gr,lr=Wi-br,Kt=document.createElement("canvas");Kt.width=er,Kt.height=lr;const Fn=Kt.getContext("2d");return Fn&&(Fn.drawImage(Ae.canvas,gr,br,er,lr,0,0,er,lr),Fn.strokeStyle="#007bff",Fn.lineWidth=3,Fn.strokeRect(it-gr-4,en-br-4,rn+8,Nn+8)),s.jsxs("div",{style:{marginBottom:"1rem",border:"1px solid #ddd",borderRadius:"6px",overflow:"hidden"},children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#666",padding:"4px 8px",background:"#f8f9fa",borderBottom:"1px solid #ddd"},children:"Invoice number field from document"}),s.jsx("img",{src:Kt.toDataURL(),alt:"Invoice number field",style:{width:"100%",height:"auto",display:"block"}})]})}return null})(),Ys.length>0&&s.jsxs("div",{style:{marginBottom:"1rem",padding:"0.5rem 0.75rem",background:"#f8f9fa",borderRadius:"4px",fontSize:"0.8rem",color:"#555"},children:[s.jsx("strong",{children:"Format from this supplier:"})," ",Ys.slice(0,4).join(", ")]}),s.jsx("p",{style:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},children:Ea?"Searching document...":Xs.length===0?"No candidates found in document text.":"Candidates found in the document. Click to use."}),Ea?s.jsx("p",{style:{color:"#999",textAlign:"center",padding:"2rem"},children:"Searching for invoice number..."}):Xs.length===0?null:s.jsx("div",{style:{maxHeight:"400px",overflowY:"auto"},children:Xs.map((B,oe)=>{const be=B.bbox?D1(B.bbox,{padX:80,padY:25,strokeColor:"#007bff"}):null;return s.jsxs("div",{onClick:()=>N1(B.value),style:{marginBottom:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",background:"#fff",transition:"all 0.2s",overflow:"hidden"},onMouseEnter:Ae=>{Ae.currentTarget.style.background="#f0f7ff",Ae.currentTarget.style.borderColor="#007bff"},onMouseLeave:Ae=>{Ae.currentTarget.style.background="#fff",Ae.currentTarget.style.borderColor="#ddd"},children:[be&&s.jsx("img",{src:be,alt:"Candidate location in document",style:{width:"100%",height:"auto",display:"block",borderBottom:"1px solid #eee"}}),s.jsxs("div",{style:{padding:"0.75rem 1rem"},children:[s.jsx("div",{style:{fontWeight:"600",fontSize:"1.05rem",marginBottom:"0.25rem",fontFamily:"monospace"},children:B.value}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#999",marginBottom:"0.2rem"},children:B.source==="ocr_field"?"📋 Azure OCR field":B.source==="supplier_pattern"?"🔗 Matches supplier format":"🔤 Found near reference keyword"}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#888",fontStyle:"italic"},children:["...",B.context,"..."]})]})]},oe)})}),s.jsx("button",{onClick:()=>rs(!1),style:fe.closeBtn,children:"Cancel"})]})}),te&&ne&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>re(!1),children:s.jsxs("div",{style:fe.searchModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Compare Similar Items"}),s.jsxs("div",{style:fe.currentItemSection,children:[s.jsxs("h4",{style:fe.currentItemHeader,children:["Current Item (",((ew=Yd==null?void 0:Yd.find(B=>B.id===(_e==null?void 0:_e.supplier_id)))==null?void 0:ew.name)||"Unknown Supplier",")"]}),s.jsxs("table",{style:fe.searchResultsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:fe.searchTh,children:"Description"}),s.jsx("th",{style:fe.searchThRight,children:"Unit Price"}),s.jsx("th",{style:fe.searchTh,children:"Unit"}),s.jsx("th",{style:fe.searchTh,children:"Pack Info"}),s.jsx("th",{style:fe.searchTh,children:"Invoice Date"})]})}),s.jsx("tbody",{children:s.jsxs("tr",{style:fe.currentItemRow,children:[s.jsx("td",{style:fe.searchTd,children:ne.description}),s.jsx("td",{style:fe.searchTdRight,children:ne.unit_price?`£${ne.unit_price.toFixed(2)}`:"—"}),s.jsx("td",{style:fe.searchTd,children:ne.unit||"—"}),s.jsx("td",{style:fe.searchTd,children:ne.pack_quantity&&ne.unit_size&&ne.unit_size_type?`${ne.pack_quantity}x${ne.unit_size}${ne.unit_size_type}`:ne.pack_quantity?`${ne.pack_quantity} pack`:"—"}),s.jsx("td",{style:fe.searchTd,children:(_e==null?void 0:_e.invoice_date)||"—"})]})})]})]}),s.jsxs("div",{style:fe.searchInputRow,children:[s.jsx("input",{type:"text",value:ke,onChange:B=>Ye(B.target.value),onKeyDown:B=>B.key==="Enter"&&J0(ke),style:fe.searchInput,placeholder:"Enter search keywords...",autoFocus:!0}),s.jsx("button",{onClick:()=>J0(ke),style:fe.searchButton,disabled:ue,children:ue?"Searching...":"Search"})]}),De&&s.jsxs("div",{style:fe.searchResultsContainer,children:[s.jsxs("p",{style:fe.resultsInfo,children:["Found ",De.total_matches," matches",De.extracted_keywords&&s.jsxs("span",{style:{color:"#666"},children:[' (searched: "',De.extracted_keywords,'")']})]}),De.results.length===0?s.jsx("p",{style:{color:"#999",fontStyle:"italic"},children:"No matching items found."}):De.results.map(B=>s.jsxs("div",{style:fe.supplierGroup,children:[s.jsx("h4",{style:fe.supplierHeader,children:B.supplier_name}),s.jsxs("table",{style:fe.searchResultsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:fe.searchTh,children:"Description"}),s.jsx("th",{style:fe.searchThRight,children:"Unit Price"}),s.jsx("th",{style:fe.searchTh,children:"Unit"}),s.jsx("th",{style:fe.searchTh,children:"Pack Info"}),s.jsx("th",{style:fe.searchTh,children:"Last Invoice"}),s.jsx("th",{style:fe.searchTh})]})}),s.jsx("tbody",{children:B.items.map((oe,be)=>s.jsxs("tr",{children:[s.jsx("td",{style:fe.searchTd,children:oe.description}),s.jsx("td",{style:fe.searchTdRight,children:oe.unit_price!=null?`£${oe.unit_price.toFixed(2)}`:"—"}),s.jsx("td",{style:fe.searchTd,children:oe.unit||"—"}),s.jsx("td",{style:fe.searchTd,children:oe.pack_info||"—"}),s.jsx("td",{style:fe.searchTd,children:oe.last_invoice_date||"—"}),s.jsx("td",{style:fe.searchTd,children:s.jsx("a",{href:`/invoice/${oe.invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:fe.invoiceLink,title:"Open invoice in new tab",children:"View"})})]},be))})]})]},B.supplier_id||"unknown"))]}),s.jsx("button",{onClick:()=>re(!1),style:fe.closeBtn,children:"Close"})]})}),me&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>J(!1),children:s.jsxs("div",{style:{...fe.modal,maxWidth:"400px",textAlign:"center"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{style:{marginBottom:"1rem"},children:"Bulk Stock Update"}),s.jsx("p",{style:{marginBottom:"1.5rem",color:"#666"},children:"Mark all line items on this invoice as:"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[s.jsx("button",{onClick:()=>ex(!0),style:{...fe.saveBtn,padding:"1rem",background:"#28a745",fontSize:"0.95rem"},children:"Mark All as Stock"}),s.jsx("button",{onClick:()=>ex(!1),style:{...fe.saveBtn,padding:"1rem",background:"#dc3545",fontSize:"0.95rem"},children:"Mark All as Non-Stock"}),s.jsx("button",{onClick:()=>J(!1),style:{...fe.backBtn,padding:"0.75rem",marginTop:"0.5rem"},children:"Cancel"})]})]})}),Ia&&s.jsx(FK,{isOpen:Ia.isOpen,onClose:()=>q0(null),productCode:Ia.productCode,description:Ia.description,unit:Ia.unit,supplierId:Ia.supplierId,supplierName:Ia.supplierName,currentPrice:Ia.currentPrice,sourceInvoiceId:Ia.sourceInvoiceId,sourceLineItemId:Ia.sourceLineItemId,onAcknowledge:()=>{zc()}}),P&&_e&&s.jsx(Xhe,{invoiceId:_e.id,invoiceNumber:_e.invoice_number,supplierId:_e.supplier_id||null,supplierName:_e.supplier_name||null,lineItems:Yt||[],onClose:()=>L(!1),onSuccess:()=>{G0()}}),Gs&&_e&&_e.supplier_id&&s.jsx(tfe,{supplierId:_e.supplier_id,supplierName:_e.supplier_name||null,creditNoteInvoiceId:_e.id,creditNoteNumber:_e.invoice_number,creditNoteAmount:_e.total,onClose:()=>Ai(!1),onSuccess:()=>{Ai(!1),G0()}}),W&&s.jsx(DK,{disputeId:W,onClose:()=>O(null),onUpdate:()=>{G0()}}),pe&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>we(null),children:s.jsxs("div",{style:fe.descSwapModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{style:{marginBottom:"0.5rem"},children:"Choose Description"}),s.jsx("p",{style:fe.modalHint,children:"OCR extracted two different descriptions. Select the correct one:"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem"},children:[s.jsxs("div",{style:fe.descriptionOption,onClick:()=>{we(null)},children:[s.jsx("div",{style:{fontWeight:"bold",marginBottom:"0.5rem",color:"#666"},children:"Current (Value)"}),s.jsx("div",{style:{whiteSpace:"pre-wrap",fontFamily:"monospace",fontSize:"0.85rem"},children:pe.description||"(empty)"})]}),s.jsxs("div",{style:{...fe.descriptionOption,borderColor:"#e94560"},onClick:async()=>{await Jl.mutateAsync({itemId:pe.id,data:{description:pe.description_alt,description_alt:null}}),we(null)},children:[s.jsx("div",{style:{fontWeight:"bold",marginBottom:"0.5rem",color:"#e94560"},children:"Alternative (Content) ✓ Select"}),s.jsx("div",{style:{whiteSpace:"pre-wrap",fontFamily:"monospace",fontSize:"0.85rem"},children:pe.description_alt||"(empty)"})]})]}),s.jsx("button",{onClick:()=>we(null),style:{...fe.backBtn,marginTop:"1rem",padding:"0.75rem"},children:"Cancel"})]})}),s.jsx(TT,{isOpen:A1!==null,onClose:()=>V0(null),onSaved:()=>K0(),poId:A1}),nn&&s.jsx("div",{style:fe.modalOverlay,onClick:dl,children:s.jsxs("div",{style:{...fe.wideModal,maxWidth:"650px"},onClick:B=>B.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsx("h3",{style:{margin:0},children:"Ingredient Mapping"}),s.jsx("button",{onClick:dl,style:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666"},children:"×"})]}),s.jsxs("div",{style:{padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:nn.description||nn.product_code||"Unknown item"}),nn.unit_price&&s.jsxs("span",{style:{marginLeft:"1rem",color:"#666"},children:["£",nn.unit_price.toFixed(2)]}),nn.raw_content&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},children:["Raw: ",nn.raw_content.substring(0,80)]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("label",{style:{fontWeight:"600",fontSize:"0.9rem",display:"block",marginBottom:"0.5rem"},children:["Ingredient ",Zs&&s.jsxs("span",{style:{color:"#28a745",fontWeight:"normal"},children:["(",Xd,")"]})]}),Zs?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"#d4edda",borderRadius:"6px",border:"1px solid #c3e6cb"},children:[s.jsxs("span",{style:{flex:1},children:[Xd," ",s.jsxs("span",{style:{color:"#666",fontSize:"0.85rem"},children:["(",Js,")"]})]}),s.jsx("button",{onClick:()=>{Ra(null),No(""),Ba(""),ze("")},style:{background:"none",border:"none",cursor:"pointer",color:"#666",fontSize:"1.1rem"},children:"×"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{type:"text",value:qu,onChange:B=>{$s(B.target.value),Y1(B.target.value)},placeholder:"Search ingredients...",style:{...fe.input,width:"100%",boxSizing:"border-box"}}),Bc&&s.jsx("span",{style:{position:"absolute",right:"10px",top:"10px",color:"#999"},children:"..."})]}),Gd.length>0&&s.jsx("div",{style:{border:"1px solid #ddd",borderRadius:"0 0 6px 6px",maxHeight:"200px",overflowY:"auto",background:"#fff"},children:Gd.map(B=>s.jsxs("div",{onClick:()=>Q1(B),style:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem",display:"flex",justifyContent:"space-between"},onMouseOver:oe=>oe.currentTarget.style.background="#f0f7ff",onMouseOut:oe=>oe.currentTarget.style.background="#fff",children:[s.jsxs("span",{children:[B.name," ",s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:["(",B.standard_unit,")"]})]}),s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:[B.category_name||""," ",B.similarity?`${(B.similarity*100).toFixed(0)}%`:""]})]},B.id))}),(ui==null?void 0:ui.llm_enabled)&&(ui==null?void 0:ui.anthropic_api_key_set)&&(nn==null?void 0:nn.description)&&!Zs&&s.jsxs("div",{style:{marginTop:"0.5rem"},children:[s.jsx("button",{onClick:()=>q1(nn.description),disabled:Gt,style:{padding:"0.4rem 0.75rem",background:"#7952b3",color:"white",border:"none",borderRadius:"4px",cursor:Gt?"wait":"pointer",fontSize:"0.85rem",opacity:Gt?.7:1},children:Gt?"Matching...":"✨ AI Match"}),ar.length>0&&s.jsx("div",{style:{border:"1px solid #d4c5f9",borderRadius:"6px",marginTop:"0.35rem",maxHeight:"160px",overflowY:"auto",background:"#f8f5ff"},children:ar.map(B=>s.jsxs("div",{onClick:()=>{const oe=Gd.find(be=>be.id===B.id);oe?Q1(oe):(Ra(B.id),No(B.name),Ba("")),Kn([])},style:{padding:"0.4rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #e8e0f7",fontSize:"0.85rem",display:"flex",justifyContent:"space-between"},onMouseOver:oe=>oe.currentTarget.style.background="#ede5ff",onMouseOut:oe=>oe.currentTarget.style.background="#f8f5ff",children:[s.jsxs("span",{children:["✨"," ",B.name]}),s.jsxs("span",{style:{color:"#7952b3",fontSize:"0.8rem"},children:[(B.confidence*100).toFixed(0),"%"]})]},B.id))})]}),s.jsx("button",{onClick:()=>al(!0),style:{marginTop:"0.5rem",padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"+ Create new ingredient"})]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("label",{style:{fontWeight:"600",fontSize:"0.9rem",display:"block",marginBottom:"0.25rem"},children:Zs?`How much ${Xd} is in this line item?`:"Unit size & pricing"}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#888",marginBottom:"0.5rem"},children:[nn==null?void 0:nn.description,nn!=null&&nn.unit_price?` @ £${nn.unit_price.toFixed(2)}`:"",nn!=null&&nn.quantity&&nn.quantity>1?` × ${nn.quantity}`:""]}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem",alignItems:"flex-end"},children:[s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsxs("label",{style:{fontSize:"0.8rem",color:"#666"},children:["Contains",ll&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#7952b3"},children:"analysing..."}),Mc==="ai"&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#7952b3"},title:"Deduced by AI from product knowledge",children:"✨"}),Mc==="regex"&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#28a745"},title:"Parsed from description",children:"auto"}),Mc==="unit_field"&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#28a745"},title:"Inferred from invoice unit field",children:"auto"})]}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",step:"0.1",value:Q.unit_size||"",onChange:B=>{const oe={...Q,unit_size:parseFloat(B.target.value)||null};X(oe),Ku(void 0,oe)},onFocus:B=>B.target.select(),style:{...fe.costBreakdownInput,width:"70px"},placeholder:"e.g., 2"}),s.jsxs("select",{value:Q.unit_size_type||Js||"",onChange:B=>{const oe={...Q,unit_size_type:B.target.value||null};X(oe),Ku(void 0,oe)},style:{...fe.costBreakdownInput,width:"60px"},children:[s.jsx("option",{value:"",children:"--"}),s.jsx("option",{value:"each",children:"each"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"}),s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"oz",children:"oz"}),s.jsx("option",{value:"cl",children:"cl"})]}),Js&&Q.unit_size_type&&Q.unit_size_type!==Js&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#999"},children:["→ ",Js]})]})]}),s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Pack of"}),s.jsx("input",{type:"number",value:Q.pack_quantity||"",onChange:B=>{const oe={...Q,pack_quantity:parseInt(B.target.value)||null};X(oe),Ku(void 0,oe)},onFocus:B=>B.target.select(),style:{...fe.costBreakdownInput,width:"50px"},placeholder:"1"})]}),s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Line Price"}),s.jsx("span",{style:{...fe.costBreakdownValue,fontSize:"0.9rem"},children:Q.unit_price?`£${Q.unit_price.toFixed(2)}`:"--"})]})]}),$&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.5rem 0.75rem",background:"#e8f5e9",borderRadius:"6px",fontSize:"0.9rem",color:"#2e7d32",fontWeight:"500"},children:$})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("button",{onClick:()=>nt(!ie),style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem",color:"#666",padding:0},children:[ie?"▾":"▸"," Legacy Portioning"]}),ie&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem"},children:[s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Portions/Unit"}),s.jsx("input",{type:"number",value:Q.portions_per_unit??"",onChange:B=>X({...Q,portions_per_unit:B.target.value?parseInt(B.target.value):null}),style:fe.costBreakdownInput,min:"1",placeholder:"--"})]}),s.jsxs("div",{style:{...fe.costBreakdownField,minWidth:"150px"},children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Portion Desc"}),s.jsx("input",{type:"text",value:Ne,onChange:B=>st(B.target.value),style:{...fe.costBreakdownInput,width:"100%"},placeholder:"e.g., 250ml glass"})]}),s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Cost/Portion"}),s.jsx("span",{style:{...fe.costBreakdownValue,color:"#28a745",fontWeight:"600",fontSize:"0.9rem"},children:Q.pack_quantity&&Q.unit_price&&Q.portions_per_unit?`£${(Q.unit_price/(Q.pack_quantity*Q.portions_per_unit)).toFixed(4)}`:"--"})]})]})})]}),(nn.product_code||nn.description)&&s.jsxs(s.Fragment,{children:[$e?s.jsx("div",{style:{fontSize:"0.85rem",color:"#666",marginBottom:"0.5rem"},children:"Loading saved default..."}):Le?s.jsx("div",{style:{...fe.savedByInfo,marginBottom:"0.5rem"},children:s.jsxs("span",{style:{fontSize:"0.85rem"},children:["Definition by ",s.jsx("strong",{children:Le.saved_by_username||"Unknown"}),Le.updated_at&&s.jsxs(s.Fragment,{children:[" on ",new Date(Le.updated_at).toLocaleDateString()]})]})}):null,!Zs&&s.jsx("div",{style:{...fe.saveAsDefaultRow,marginBottom:"1rem"},children:s.jsxs("label",{style:fe.saveAsDefaultLabel,children:[s.jsx("input",{type:"checkbox",checked:Ve,onChange:B=>Re(B.target.checked),style:{marginRight:"0.5rem"}}),Le?"Update saved default":`Save as default for "${nn.product_code||((nx=nn.description)==null?void 0:nx.substring(0,30))}"`]})})]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:dl,style:{...fe.smallBtnCancel,padding:"0.5rem 1.25rem"},children:"Cancel"}),s.jsx("button",{onClick:()=>DC(nn.id),style:{...fe.smallBtn,padding:"0.5rem 1.25rem"},children:Zs?"Save & Map Ingredient":Ve?"Save & Update Default":"Save"})]})]})}),s.jsx(A0,{open:Ic,onClose:()=>al(!1),onSaved:FC,prePopulateName:qu||((EC=nn==null?void 0:nn.description)==null?void 0:EC.split(` `)[0])||"",preSelectLineItem:nn?{product_code:nn.product_code,description:((tw=nn.description)==null?void 0:tw.split(` `)[0])||"",supplier_id:(_e==null?void 0:_e.supplier_id)||null,supplier_name:(_e==null?void 0:_e.supplier_name)||null,unit:nn.unit,most_recent_price:nn.unit_price,total_quantity:nn.quantity,occurrence_count:1,most_recent_invoice_id:Number(n),most_recent_line_number:nn.line_number,most_recent_pack_quantity:nn.pack_quantity,most_recent_unit_size:nn.unit_size,most_recent_unit_size_type:nn.unit_size_type,ingredient_id:nn.ingredient_id||null,ingredient_name:nn.ingredient_name||null}:null})]})}const fe={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00"},pageContainer:{display:"flex",flexDirection:"column",gap:"1.5rem"},topRow:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1.5rem"},imageSection:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",overflow:"hidden",minWidth:0},imageZoomControls:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"1rem",justifyContent:"center"},zoomBtn:{padding:"0.5rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"1rem",fontWeight:"bold",minWidth:"36px"},zoomLabel:{fontSize:"0.9rem",color:"#666",minWidth:"50px",textAlign:"center"},zoomResetBtnSmall:{padding:"0.4rem 0.75rem",background:"#fff3cd",border:"1px solid #ffc107",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"500"},imageScrollContainer:{marginTop:"0.5rem",maxHeight:"70vh",maxWidth:"100%",overflow:"auto",background:"#f5f5f5",borderRadius:"8px",padding:"8px"},imageContainer:{position:"relative"},image:{width:"100%",borderRadius:"8px",display:"block"},pdfScrollContainer:{marginTop:"1rem",maxHeight:"70vh",overflow:"auto",background:"#e5e5e5",borderRadius:"8px",padding:"16px"},pdfPageWrapper:{marginBottom:"16px"},pdfPageContainer:{position:"relative",margin:"0 auto",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},pageLabel:{textAlign:"center",fontSize:"0.8rem",color:"#666",marginTop:"4px"},highlightOverlay:{position:"absolute",background:"rgba(255, 200, 0, 0.3)",borderRadius:"2px",cursor:"pointer",boxShadow:"0 0 8px rgba(255, 200, 0, 0.6)",animation:"pulse 1.5s infinite"},imagePlaceholder:{width:"100%",height:"300px",background:"#f5f5f5",borderRadius:"8px",marginTop:"1rem",display:"flex",alignItems:"center",justifyContent:"center",color:"#999"},openPdfLink:{display:"block",marginTop:"0.5rem",textAlign:"center",color:"#0066cc",fontSize:"0.85rem"},zoomResetBtn:{display:"block",margin:"0.5rem auto",padding:"0.4rem 1rem",background:"#fff3cd",border:"1px solid #ffc107",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"500"},confidenceBadge:{marginTop:"1rem",padding:"0.5rem 1rem",background:"#f0f0f0",borderRadius:"20px",textAlign:"center",fontSize:"0.9rem",color:"#666"},formSection:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},duplicateWarning:{padding:"1rem",borderRadius:"8px",marginBottom:"1rem",cursor:"pointer",borderWidth:"1px",borderStyle:"solid",fontWeight:"500"},form:{display:"flex",flexDirection:"column",gap:"0.75rem"},row:{display:"flex",gap:"1rem"},label:{display:"flex",flexDirection:"column",gap:"0.25rem",color:"#333",fontWeight:"500",fontSize:"0.9rem"},input:{padding:"0.5rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.95rem",flex:1},inputWithEye:{display:"flex",gap:"0.5rem",alignItems:"center"},eyeBtn:{padding:"0.4rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem",lineHeight:1,flexShrink:0},eyeBtnActive:{background:"#fff3cd",border:"1px solid #ffc107"},extractedHint:{fontSize:"0.8rem",color:"#666",fontWeight:"normal",fontStyle:"italic"},extractedHintRow:{display:"flex",alignItems:"center",gap:"0.75rem",marginTop:"0.25rem",flexWrap:"wrap"},fuzzyMatchWarning:{fontSize:"0.8rem",color:"#856404",background:"#fff3cd",padding:"0.35rem 0.5rem",borderRadius:"4px",marginTop:"0.25rem",border:"1px solid #ffc107",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",flexWrap:"wrap"},addAliasBtn:{padding:"0.2rem 0.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.75rem",fontWeight:"500",whiteSpace:"nowrap"},supplierRow:{display:"flex",gap:"0.5rem",alignItems:"center"},createSupplierBtn:{padding:"0.5rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",whiteSpace:"nowrap"},createFromExtractedBtn:{padding:"0.25rem 0.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.75rem",fontWeight:"normal"},modalLabel:{display:"flex",flexDirection:"column",gap:"0.5rem",color:"#333",fontWeight:"500",marginTop:"1rem"},lineItemsSection:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},lineItemsTableContainer:{maxHeight:"60vh",overflowY:"auto",overflowX:"auto",border:"1px solid #eee",borderRadius:"8px",position:"relative"},stickyThead:{position:"sticky",top:0,zIndex:2,borderBottom:"2px solid #ddd"},stickyPageIndicatorCell:{background:"#e9ecef",padding:"0.3rem 1rem",textAlign:"center",fontSize:"0.85rem",fontWeight:"500",color:"#495057"},lineItemsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.95rem"},th:{textAlign:"left",padding:"0.75rem 0.5rem",fontWeight:"600",background:"#f8f9fa"},td:{padding:"0.75rem 0.5rem",borderBottom:"1px solid #eee",verticalAlign:"middle"},tableInput:{padding:"0.35rem",borderRadius:"4px",border:"1px solid #ddd",fontSize:"0.9rem",width:"100%"},smallBtn:{padding:"0.35rem 0.75rem",background:"#5cb85c",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",marginRight:"0.25rem",fontSize:"0.8rem"},smallBtnCancel:{padding:"0.35rem 0.75rem",background:"#999",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},editBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},iconBtn:{padding:"0.35rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem",display:"flex",alignItems:"center",justifyContent:"center",minWidth:"32px",height:"32px"},noItems:{color:"#999",fontStyle:"italic",marginTop:"0.5rem"},saveBtn:{flex:1,padding:"1.25rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},confirmBtn:{flex:1,padding:"1.25rem",background:"#5cb85c",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},backBtn:{marginTop:"0.5rem",padding:"0.5rem",background:"transparent",border:"none",color:"#666",cursor:"pointer",width:"100%",fontSize:"0.9rem"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"400px",width:"90%"},wideModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"800px",width:"90%",maxHeight:"80vh",overflowY:"auto"},modalInfo:{margin:"1rem 0",padding:"1rem",background:"#f5f5f5",borderRadius:"8px"},modalDuplicateInfo:{padding:"0.75rem",background:"#d4edda",borderRadius:"6px",marginBottom:"1rem",color:"#155724",fontSize:"0.9rem"},modalActions:{display:"flex",gap:"1rem",marginTop:"1.5rem"},cancelBtn:{flex:1,padding:"0.75rem",background:"#f0f0f0",border:"none",borderRadius:"6px",cursor:"pointer"},confirmDeleteBtn:{flex:1,padding:"0.75rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},compareGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"1rem",marginTop:"1rem"},compareCard:{padding:"1rem",border:"2px solid #ddd",borderRadius:"8px"},viewBtn:{marginTop:"0.5rem",padding:"0.5rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",width:"100%",fontSize:"0.85rem"},closeBtn:{marginTop:"1.5rem",padding:"0.75rem 2rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},rawOcrModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"900px",width:"95%",maxHeight:"85vh",overflowY:"auto"},rawOcrHint:{color:"#666",fontSize:"0.9rem",marginBottom:"1rem"},rawOcrContent:{marginTop:"1rem"},rawOcrDoc:{marginBottom:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},rawOcrTable:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem",fontSize:"0.85rem"},rawOcrTh:{textAlign:"left",padding:"0.5rem",borderBottom:"2px solid #ddd",fontWeight:"600",background:"#e9ecef"},rawOcrTd:{padding:"0.5rem",borderBottom:"1px solid #eee",verticalAlign:"top",wordBreak:"break-word",maxWidth:"300px"},lineItemPreviewCell:{padding:"0.5rem",background:"#f8f9fa",borderBottom:"1px solid #eee",textAlign:"center"},lineItemPreviewContainer:{width:"100%",overflow:"hidden",display:"inline-block"},scaleBtn:{padding:"0.25rem",background:"transparent",borderWidth:"1px",borderStyle:"solid",borderColor:"#ddd",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#666"},scaleBtnActive:{background:"#e8f5e9",borderColor:"#28a745"},costBreakdownField:{display:"flex",flexDirection:"column",gap:"0.25rem",minWidth:"70px"},costBreakdownInput:{padding:"0.4rem",borderRadius:"4px",border:"1px solid #ddd",fontSize:"0.9rem",width:"70px",MozAppearance:"textfield",appearance:"textfield"},costBreakdownValue:{fontSize:"0.95rem",padding:"0.4rem 0"},saveAsDefaultRow:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.75rem",marginBottom:"0.5rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},saveAsDefaultLabel:{display:"flex",alignItems:"center",fontSize:"0.9rem",cursor:"pointer",fontWeight:"500"},savedByInfo:{display:"flex",alignItems:"center",padding:"0.6rem 0.75rem",marginBottom:"0.5rem",background:"#e8f4fd",borderRadius:"6px",border:"1px solid #b8daff",fontSize:"0.85rem",color:"#004085"},searchModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"900px",width:"95%",maxHeight:"85vh",overflowY:"auto"},searchInputRow:{display:"flex",gap:"0.5rem",marginBottom:"1rem"},searchInput:{flex:1,padding:"0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"1rem"},searchButton:{padding:"0.75rem 1.5rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"500"},searchResultsContainer:{marginTop:"1rem",maxHeight:"50vh",overflowY:"auto"},resultsInfo:{color:"#333",fontSize:"0.9rem",marginBottom:"1rem"},supplierGroup:{marginBottom:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},supplierHeader:{margin:"0 0 0.75rem",color:"#1a1a2e",fontSize:"1rem"},searchResultsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},searchTh:{textAlign:"left",padding:"0.5rem",borderBottom:"2px solid #ddd",fontWeight:"600",background:"#e9ecef"},searchThRight:{textAlign:"right",padding:"0.5rem",borderBottom:"2px solid #ddd",fontWeight:"600",background:"#e9ecef"},searchTd:{padding:"0.5rem",borderBottom:"1px solid #eee"},searchTdRight:{padding:"0.5rem",borderBottom:"1px solid #eee",textAlign:"right"},currentItemSection:{marginBottom:"1.5rem",padding:"1rem",background:"#e8f4f8",borderRadius:"8px",border:"2px solid #2196f3"},currentItemHeader:{margin:"0 0 0.75rem",color:"#1565c0",fontSize:"1rem",fontWeight:"600"},currentItemRow:{background:"#fff"},invoiceLink:{color:"#1976d2",textDecoration:"none",fontSize:"0.8rem",padding:"0.2rem 0.5rem",background:"#e3f2fd",borderRadius:"4px"},errorBanner:{display:"flex",gap:"1rem",padding:"1rem 1.5rem",marginBottom:"1.5rem",background:"#fff3cd",border:"2px solid #ffc107",borderRadius:"8px",color:"#856404"},errorBannerIcon:{fontSize:"2rem",flexShrink:0},errorBannerContent:{flex:1},descSwapModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"600px",width:"90%",maxHeight:"80vh",overflowY:"auto"},descriptionOption:{padding:"1rem",borderRadius:"8px",background:"#f9f9f9",border:"2px solid #ccc",cursor:"pointer",transition:"background 0.2s"},modalHint:{color:"#666",fontSize:"0.9rem",margin:0}},yfe={new:"#e94560",contacted:"#f0ad4e",awaiting_credit:"#9b59b6",awaiting_replacement:"#8b7ec8",resolved:"#5cb85c"},xfe={low:"#5cb85c",medium:"#5bc0de",high:"#f0ad4e",urgent:"#e94560"};function bfe(){const{token:n}=gn(),[e,t]=K_(),r=e.get("date")||"",[i,o]=k.useState(r?"":"not_resolved"),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState(r),[p,g]=k.useState(null),{data:m}=Oe({queryKey:["suppliers"],queryFn:async()=>{const C=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!C.ok)throw new Error("Failed to fetch suppliers");return C.json()},enabled:!!n}),y=new URLSearchParams;i&&i!=="not_resolved"&&y.append("status",i.toUpperCase()),a&&y.append("priority",a),d&&y.append("supplier_id",d),u&&y.append("opened_date",u);const v=y.toString(),{data:x,isLoading:w,error:S}=Oe({queryKey:["disputes",i,a,d,u],queryFn:async()=>{const C=v?`/api/disputes?${v}`:"/api/disputes",T=await fetch(C,{headers:{Authorization:`Bearer ${n}`}});if(!T.ok)throw new Error("Failed to fetch disputes");return T.json()},enabled:!!n});let _=(x==null?void 0:x.disputes)||[];if(i==="not_resolved"&&(_=_.filter(C=>C.status.toUpperCase()!=="RESOLVED")),k.useEffect(()=>{const C=e.get("invoice_id");if(C&&_.length>0&&!p){const T=_.filter(F=>F.invoice_id===parseInt(C));T.length>0&&(g(T[0]),t({}))}},[_,e,p,t]),w)return s.jsx("div",{style:bi.loading,children:"Loading disputes..."});if(S)return s.jsxs("div",{style:bi.error,children:["Error loading disputes: ",S.message]});const b=(m==null?void 0:m.suppliers)||[];return s.jsxs("div",{children:[s.jsx("div",{style:bi.header,children:s.jsx("h2",{style:bi.title,children:"Invoice Disputes"})}),s.jsxs("div",{style:bi.filters,children:[s.jsxs("select",{value:i,onChange:C=>o(C.target.value),style:bi.filterSelect,children:[s.jsx("option",{value:"not_resolved",children:"Not Resolved (Default)"}),s.jsx("option",{value:"",children:"All Statuses"}),s.jsx("option",{value:"new",children:"New"}),s.jsx("option",{value:"contacted",children:"Contacted"}),s.jsx("option",{value:"awaiting_credit",children:"Awaiting Credit"}),s.jsx("option",{value:"awaiting_replacement",children:"Awaiting Replacement"}),s.jsx("option",{value:"resolved",children:"Resolved"})]}),s.jsxs("select",{value:a,onChange:C=>l(C.target.value),style:bi.filterSelect,children:[s.jsx("option",{value:"",children:"All Priorities"}),s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"urgent",children:"Urgent"})]}),s.jsxs("select",{value:d,onChange:C=>c(C.target.value),style:bi.filterSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),b.map(C=>s.jsx("option",{value:C.id,children:C.name},C.id))]}),s.jsx("input",{type:"date",value:u,onChange:C=>f(C.target.value),style:bi.filterSelect}),(i!=="not_resolved"||a||d||u)&&s.jsx("button",{onClick:()=>{o("not_resolved"),l(""),c(""),f("")},style:bi.clearBtn,children:"Reset Filters"})]}),_.length===0?s.jsxs("div",{style:bi.empty,children:[s.jsx("p",{children:"No disputes found."}),i!=="not_resolved"||a||d||u?s.jsx("button",{onClick:()=>{o("not_resolved"),l(""),c(""),f("")},style:bi.link,children:"Reset filters"}):s.jsx("p",{style:bi.noDataSubtext,children:"No open disputes. Great job!"})]}):s.jsx("div",{style:bi.list,children:_.map(C=>s.jsxs("div",{onClick:()=>g(C),style:bi.card,children:[s.jsxs("div",{style:bi.cardMain,children:[s.jsxs("div",{style:bi.disputeTitleRow,children:[C.supplier_name||"Unknown"," - Invoice #",C.invoice_number||C.invoice_id,s.jsx("span",{style:bi.disputeType,children:C.dispute_type.replace(/_/g," ").toUpperCase()})]}),s.jsxs("div",{style:bi.disputeDateRow,children:["Opened ",new Date(C.opened_at).toLocaleDateString()," • Last updated ",new Date(C.updated_at).toLocaleDateString()]}),s.jsx("div",{style:bi.disputeTitle,children:C.title}),C.description&&s.jsx("div",{style:bi.description,children:C.description.length>120?`${C.description.substring(0,120)}...`:C.description})]}),s.jsxs("div",{style:bi.cardRight,children:[s.jsx("div",{style:{...bi.status,background:yfe[C.status.toLowerCase()]||"#999"},children:C.status.replace(/_/g," ")}),C.difference_amount!=null&&s.jsxs("div",{style:bi.amount,children:["£",Number(Math.abs(C.difference_amount)).toFixed(2)]}),s.jsx("span",{style:{...bi.priorityBadge,background:xfe[C.priority]||"#999"},children:C.priority})]})]},C.id))}),p&&s.jsx(DK,{disputeId:p.id,onClose:()=>g(null),onUpdate:()=>{}})]})}const bi={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},filters:{display:"flex",gap:"1rem",marginBottom:"1.5rem",flexWrap:"wrap"},filterSelect:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",minWidth:"150px"},clearBtn:{padding:"0.5rem 1rem",borderRadius:"8px",border:"none",background:"#666",color:"white",cursor:"pointer",fontWeight:"bold"},empty:{padding:"3rem",textAlign:"center",color:"#666",background:"white",borderRadius:"12px"},noDataSubtext:{marginTop:"0.5rem",color:"#999",fontSize:"0.9rem"},link:{display:"inline-block",marginTop:"1rem",padding:"0.75rem 1.5rem",background:"transparent",color:"#e94560",border:"2px solid #e94560",borderRadius:"8px",textDecoration:"none",fontWeight:"bold",cursor:"pointer"},list:{display:"flex",flexDirection:"column",gap:"1rem"},card:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",padding:"1.5rem",background:"white",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",cursor:"pointer",textDecoration:"none",color:"inherit",transition:"box-shadow 0.2s"},cardMain:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},cardRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"0.5rem"},disputeTitleRow:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",display:"flex",alignItems:"center",gap:"0.5rem"},disputeType:{fontSize:"0.65rem",fontWeight:"bold",color:"#666",letterSpacing:"0.5px"},disputeDateRow:{fontSize:"0.75rem",color:"#999",marginBottom:"0.25rem"},disputeTitle:{fontSize:"1rem",fontWeight:"bold",color:"#1a1a2e"},priorityBadge:{padding:"0.25rem 0.75rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:"bold",color:"white",textTransform:"uppercase",flexShrink:0},description:{color:"#666",fontSize:"0.9rem"},amount:{fontSize:"1.25rem",fontWeight:"bold",color:"#e94560"},status:{padding:"0.5rem 1rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:"bold",color:"white",textTransform:"uppercase",textAlign:"center",minWidth:"120px"}};pf.register(Bj,Ij,GS,qx,U6,H6,W6);const Cu=n=>n.toISOString().split("T")[0],PK="purchases-report-from-date",RK="purchases-report-to-date",vfe=()=>{const n=sessionStorage.getItem(PK),e=sessionStorage.getItem(RK);if(n&&e)return{from:n,to:e};const t=new Date,r=(7-t.getDay())%7,i=new Date(t);i.setDate(t.getDate()+r);const o=new Date(i);return o.setDate(i.getDate()-27),{from:Cu(o),to:Cu(i)}},wfe=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Cu(t),end:Cu(r)}},Sfe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()};function jfe(){var Be;const{token:n}=gn(),e=go(),[t]=K_(),r=k.useRef(null),o=(()=>{const he=t.get("from"),He=t.get("to");return he&&He?{from:he,to:He,fromUrl:!0}:{...vfe(),fromUrl:!1}})(),[a,l]=k.useState(o.from),[d,c]=k.useState(o.to),[u,f]=k.useState(""),[p,g]=k.useState((o.fromUrl,"custom")),[m,y]=k.useState(o.from),[v,x]=k.useState(o.to);k.useEffect(()=>{sessionStorage.setItem(PK,m),sessionStorage.setItem(RK,v)},[m,v]);const w=Sfe(),S=a!==m||d!==v,_=()=>{y(a),x(d)};k.useEffect(()=>{if(u){const[he,He]=u.split("-").map(Number),Ge=wfe(he,He);l(Ge.start),c(Ge.end),y(Ge.start),x(Ge.end)}},[u]);const b=he=>{l(he),f(""),g("custom")},C=he=>{c(he),f(""),g("custom")},T=he=>{f(he),g(he?"month":"custom")},F=()=>{const he=new Date,He=(7-he.getDay())%7,Ge=new Date(he);Ge.setDate(he.getDate()+He);const ae=new Date(Ge);ae.setDate(Ge.getDate()-27);const K=Cu(ae),de=Cu(Ge);l(K),c(de),y(K),x(de),f(""),g("last28")},A=()=>{const he=new Date;f(`${he.getFullYear()}-${he.getMonth()}`),g("month")},D=()=>{const he=new Date,He=new Date(he.getFullYear(),he.getMonth()-1,1);f(`${He.getFullYear()}-${He.getMonth()}`),g("month")},P=()=>{if(p==="last28")return"Last 4 Weeks: ";if(p==="month"&&u){const[he,He]=u.split("-").map(Number);return`Month of ${new Date(he,He,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},[L,W]=k.useState(!1),{data:O,isLoading:U,error:M}=Oe({queryKey:["purchases-range",m,v],queryFn:async()=>{const he=await fetch(`/api/reports/purchases/range?from_date=${m}&to_date=${v}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch purchases");return he.json()}}),{data:I}=Oe({queryKey:["daily-dispute-stats",m,v],queryFn:async()=>{const he=await fetch(`/api/disputes/stats/daily?from_date=${m}&to_date=${v}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch dispute stats");return he.json()}}),{data:H}=Oe({queryKey:["daily-allowance-stats",m,v],queryFn:async()=>{const he=await fetch(`/api/logbook/daily-stats?date_from=${m}&date_to=${v}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch allowance stats");return he.json()}}),z=he=>{var X;const He=(X=H==null?void 0:H.daily_stats)==null?void 0:X[he];if(!He)return{wastageTotal:0,otherTotal:0,total:0,wastageBreakdown:"",otherBreakdown:"",breakdown:""};const Ge={wastage:"Wastage",transfer:"Transfer",staff_food:"Staff Food",manual_adjustment:"Manual Adjustment"};let ae=0,K=0;const de=[],Y=[],Q=[];for(const[pe,we]of Object.entries(He))if(we&&we.total_cost>0){const st=`${Ge[pe]||pe}: £${we.total_cost.toFixed(2)}`;de.push(st),pe==="wastage"?(ae+=we.total_cost,Y.push(st)):(K+=we.total_cost,Q.push(st))}return{wastageTotal:ae,otherTotal:K,total:ae+K,wastageBreakdown:Y.join(` `),otherBreakdown:Q.join(` `),breakdown:de.join(` `)}},G=k.useMemo(()=>{const he=new Date,He=(7-he.getDay())%7,Ge=new Date(he);Ge.setDate(he.getDate()+He);const ae=new Date(Ge);return ae.setDate(Ge.getDate()-(24*7-1)),{from:Cu(ae),to:Cu(Ge)}},[]),{data:te,isLoading:re,error:me}=Oe({queryKey:["weekly-chart-data",G.from,G.to],queryFn:async()=>{const he=await fetch(`/api/reports/gp/daily?from_date=${G.from}&to_date=${G.to}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch weekly chart data");return he.json()}}),J=k.useMemo(()=>{if(!(te!=null&&te.data))return[];const he=[],He=new Date(G.from);for(let Ge=0;Ge<24;Ge++){const ae=new Date(He);ae.setDate(He.getDate()+Ge*7);const K=new Date(ae);K.setDate(ae.getDate()+6);const de=Cu(ae),Y=Cu(K);let Q=0,X=0;for(const Ve of te.data)Ve.date>=de&&Ve.date<=Y&&(Q+=Number(Ve.net_purchases)||0,X+=Number(Ve.net_sales)||0);const pe=new Date(de),we=new Date(Y),Ne={day:"numeric",month:"short"},st=`${pe.toLocaleDateString("en-GB",Ne)} - ${we.toLocaleDateString("en-GB",Ne)}`;he.push({weekLabel:st,weekStart:de,weekEnd:Y,totalPurchases:Q,totalSales:X})}return he},[te,G]),ne=J.slice(12,24),ye=J.slice(0,12),ke=k.useMemo(()=>({labels:ne.map(he=>he.weekLabel),datasets:[{label:"Purchases (Last 12 Weeks)",data:ne.map(he=>he.totalPurchases),borderColor:"#e94560",backgroundColor:"rgba(233, 69, 96, 0.1)",borderWidth:2,tension:.1,pointRadius:4,pointBackgroundColor:"#e94560",yAxisID:"y"},{label:"Net Food Sales (Last 12 Weeks)",data:ne.map(he=>he.totalSales),borderColor:"#3b82f6",backgroundColor:"rgba(59, 130, 246, 0.1)",borderWidth:2,tension:.1,pointRadius:4,pointBackgroundColor:"#3b82f6",yAxisID:"y"},{label:"Purchases (Previous 12 Weeks)",data:ye.map(he=>he.totalPurchases),borderColor:"rgba(233, 69, 96, 0.4)",backgroundColor:"transparent",borderWidth:2,borderDash:[5,5],tension:.1,pointRadius:3,pointBackgroundColor:"rgba(233, 69, 96, 0.4)",yAxisID:"y"},{label:"Net Food Sales (Previous 12 Weeks)",data:ye.map(he=>he.totalSales),borderColor:"rgba(59, 130, 246, 0.4)",backgroundColor:"transparent",borderWidth:2,borderDash:[5,5],tension:.1,pointRadius:3,pointBackgroundColor:"rgba(59, 130, 246, 0.4)",yAxisID:"y"},{label:"GP % (Last 12 Weeks)",data:ne.map(he=>he.totalSales>0?(he.totalSales-he.totalPurchases)/he.totalSales*100:0),borderColor:"#10b981",backgroundColor:"transparent",borderWidth:2,borderDash:[8,4],tension:.1,pointRadius:4,pointBackgroundColor:"#10b981",yAxisID:"y1"},{label:"GP % (Previous 12 Weeks)",data:ye.map(he=>he.totalSales>0?(he.totalSales-he.totalPurchases)/he.totalSales*100:0),borderColor:"rgba(16, 185, 129, 0.4)",backgroundColor:"transparent",borderWidth:2,borderDash:[8,4],tension:.1,pointRadius:3,pointBackgroundColor:"rgba(16, 185, 129, 0.4)",yAxisID:"y1"}]}),[ne,ye]),Ye={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top",labels:{usePointStyle:!0,padding:15}},title:{display:!0,text:"Weekly Purchases vs Net Food Sales (Last 12 Weeks with Previous 12 Weeks Comparison)",font:{size:16,weight:"bold"},padding:{bottom:20}},tooltip:{callbacks:{label:function(he){return he.dataset.yAxisID==="y1"?`${he.dataset.label}: ${he.parsed.y.toFixed(1)}%`:`${he.dataset.label}: £${he.parsed.y.toFixed(2)}`}}}},scales:{y:{type:"linear",position:"left",ticks:{callback:function(he){return"£"+he.toLocaleString()}},title:{display:!0,text:"Amount (£)"}},y1:{type:"linear",position:"right",beginAtZero:!0,grid:{drawOnChartArea:!1},ticks:{callback:function(he){return he.toFixed(0)+"%"}},title:{display:!0,text:"GP %"}},x:{title:{display:!0,text:"Week"}}}},De=he=>new Date(he).toLocaleDateString("en-GB",{weekday:"short",day:"numeric"}),qe=(he,He)=>{const Ge=new Date(he),ae=new Date(He),K={day:"numeric",month:"short"};return`${Ge.toLocaleDateString("en-GB",K)} - ${ae.toLocaleDateString("en-GB",K)}`},ue=he=>he>=a&&he<=d,Ze=()=>{if(!O)return[];const he=[];for(const He of O.weeks)for(const Ge of He.suppliers)for(const ae of Object.keys(Ge.invoices_by_date))for(const K of Ge.invoices_by_date[ae])he.find(de=>de.invoice.id===K.id)||he.push({invoice:K,supplierName:Ge.supplier_name});return he.sort((He,Ge)=>{const ae=He.invoice.invoice_date||"",K=Ge.invoice.invoice_date||"";return ae.localeCompare(K)}),he},ee=()=>{W(!0),setTimeout(()=>{window.print(),W(!1)},100)};if(U)return s.jsx("div",{style:et.loading,children:"Loading purchases..."});if(M)return s.jsxs("div",{style:et.error,children:["Error loading purchases: ",M.message]});const{weeks:Z=[],period_total:ge=0,period_label:Te=""}=O||{};if(L){const he=Ze();return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:` @media print { header, nav, .no-print { display: none !important; } body { margin: 0; padding: 0; } } `}),s.jsxs("div",{style:et.printContainer,ref:r,children:[s.jsxs("h1",{style:et.printTitle,children:["Purchases Report - ",P(),Te]}),s.jsxs("table",{style:et.printTableSmall,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:et.printThDateSmall,children:"Date"}),s.jsx("th",{style:et.printThSmall,children:"Supplier"}),s.jsx("th",{style:et.printThSmall,children:"Invoice #"}),s.jsx("th",{style:et.printThRightSmall,children:"Net Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Gross Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Net Non-Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Gross Non-Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Net Total"}),s.jsx("th",{style:et.printThRightSmall,children:"Gross Total"})]})}),s.jsx("tbody",{children:he.map(({invoice:He,supplierName:Ge})=>{const ae=Number(He.total??0),K=Number(He.net_total??0),de=K||ae,Y=ae||K,Q=Number(He.net_stock??0),pe=Number(He.gross_stock??0)||(Math.abs(Q)>0&&Math.abs(Y)>0&&Math.abs(de)>0?Q*(Y/de):Q),we=de-Q,Ne=Y-pe,st=de<0||Q<0,Ve=(Re,Le=!1)=>Math.abs(Re)<.01&&!Le?"-":Re<0?`-£${Math.abs(Re).toFixed(2)} CR`:`£${Re.toFixed(2)}`;return s.jsxs("tr",{style:st?{background:"#d4edda"}:{},children:[s.jsx("td",{style:et.printTdDateSmall,children:He.invoice_date||"-"}),s.jsxs("td",{style:et.printTdSmall,children:[Ge,st&&" (CR)"]}),s.jsx("td",{style:et.printTdSmall,children:He.invoice_number||"-"}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(Q,!0)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(pe,!0)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(we)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(Ne)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(de,!0)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(Y,!0)})]},He.id)})}),s.jsx("tfoot",{children:(()=>{const He=he.reduce((de,{invoice:Y})=>{const Q=Number(Y.total??0),X=Number(Y.net_total??0),pe=X||Q,we=Q||X,Ne=Number(Y.net_stock??0),Ve=Number(Y.gross_stock??0)||(Math.abs(Ne)>0&&Math.abs(we)>0&&Math.abs(pe)>0?Ne*(we/pe):Ne);return{netStock:de.netStock+Ne,grossStock:de.grossStock+Ve,netTotal:de.netTotal+pe,grossTotal:de.grossTotal+we}},{netStock:0,grossStock:0,netTotal:0,grossTotal:0}),Ge=He.netTotal-He.netStock,ae=He.grossTotal-He.grossStock,K=(de,Y=!1)=>Math.abs(de)<.01&&!Y?"-":de<0?`-£${Math.abs(de).toFixed(2)} CR`:`£${de.toFixed(2)}`;return s.jsxs("tr",{style:et.printFooter,children:[s.jsx("td",{colSpan:3,style:et.printTdSmall,children:s.jsx("strong",{children:"Period Total"})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.netStock,!0)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.grossStock,!0)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(Ge)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(ae)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.netTotal,!0)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.grossTotal,!0)})})]})})()})]})]})]})}return s.jsxs("div",{children:[s.jsxs("div",{style:et.header,children:[s.jsx("h2",{style:et.title,children:"Purchases Report"}),s.jsx("button",{onClick:ee,style:et.printBtn,children:"Print"})]}),s.jsxs("div",{style:et.dateControls,children:[s.jsxs("div",{style:et.dateRow,children:[s.jsxs("div",{style:et.dateField,children:[s.jsx("label",{style:et.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:a,onChange:he=>b(he.target.value),style:et.dateInput})]}),s.jsxs("div",{style:et.dateField,children:[s.jsx("label",{style:et.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:d,onChange:he=>C(he.target.value),style:et.dateInput})]}),s.jsxs("div",{style:et.dateField,children:[s.jsx("label",{style:et.dateLabel,children:"Month"}),s.jsxs("select",{value:u,onChange:he=>T(he.target.value),style:et.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),w.map(he=>s.jsx("option",{value:`${he.year}-${he.month}`,children:he.label},`${he.year}-${he.month}`))]})]})]}),s.jsxs("div",{style:et.presetRow,children:[s.jsx("button",{onClick:F,style:et.presetBtn,children:"Last 4 Weeks"}),s.jsx("button",{onClick:A,style:et.presetBtn,children:"This Month"}),s.jsx("button",{onClick:D,style:et.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:_,disabled:!S,style:{...et.generateBtn,...S?{}:et.generateBtnDisabled},children:S?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:et.periodLabel,children:[P(),Te]}),Z.length===0?s.jsx("div",{style:et.empty,children:s.jsx("p",{children:"No purchases in this period."})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:et.sectionContainer,children:[s.jsx("h3",{style:et.sectionTitle,children:"Daily Spending by Supplier"}),[...Z].reverse().map((he,He)=>{const Ge=Z.length-1-He;return!he.dates.some(K=>{const de=K;return ue(de)?he.suppliers.some(Y=>{var Q;return((Q=Y.invoices_by_date[de])==null?void 0:Q.length)>0}):!1})&&he.week_total===0?null:s.jsxs("div",{style:et.weekContainer,children:[s.jsxs("div",{style:et.weekHeader,children:[s.jsxs("span",{style:et.weekTitle,children:["Week ",Ge+1]}),s.jsx("span",{style:et.weekRange,children:qe(he.week_start,he.week_end)}),s.jsxs("span",{style:{...et.weekTotal,...Number(he.week_total)<0?{color:"#28a745"}:{}},children:["Week Total: ",Number(he.week_total)<0?"-":"","£",Math.abs(Number(he.week_total)).toFixed(2),Number(he.week_total)<0&&" CR"]})]}),s.jsx("div",{style:et.tableContainer,children:s.jsxs("table",{style:et.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...et.th,...et.supplierHeader},children:"Supplier"}),he.dates.map(K=>{const de=K,Y=ue(de);return s.jsx("th",{style:{...et.th,...Y?{}:et.outOfMonth},children:De(de)},de)}),s.jsx("th",{style:{...et.th,...et.totalHeader},children:"Total"}),s.jsx("th",{style:{...et.th,...et.percentHeader},children:"%"})]})}),s.jsx("tbody",{children:he.suppliers.map(K=>Object.values(K.invoices_by_date).some(Y=>Y.length>0)?s.jsxs("tr",{style:et.tr,children:[s.jsxs("td",{style:{...et.td,...et.supplierCell,...K.is_unmatched?et.unmatchedSupplier:{}},children:[K.supplier_name,K.is_unmatched&&s.jsx("span",{style:et.unmatchedBadge,children:"!"})]}),he.dates.map(Y=>{const Q=Y,X=K.invoices_by_date[Q]||[],pe=ue(Q);return s.jsx("td",{style:{...et.td,...pe?{}:et.outOfMonthCell},children:X.length>0?s.jsx("div",{style:et.invoicesCell,children:X.map(we=>{const Ne=Number(we.net_stock??0),st=Number(we.net_total??we.total??0),Ve=Ne===0&&st!==0,Re=Ne!==0&&Math.abs(Math.abs(Ne)-Math.abs(st))>.01,Le=Ne<0||st<0;return s.jsx("button",{onClick:()=>e(`/invoice/${we.id}`),style:{...et.invoiceBtn,...Le?et.creditNoteInvoice:{},...Ve&&!Le?et.nonStockInvoice:{},...we.supplier_match_type==="fuzzy"&&!Le?et.fuzzyInvoice:{},...we.supplier_match_type===null&&K.is_unmatched&&!Le?et.unmatchedInvoice:{}},title:`${Le?"CREDIT NOTE: ":""}${we.invoice_number||`Invoice #${we.id}`}`,children:Ve?s.jsxs("span",{children:[Le?"":"(","£",Math.abs(st).toFixed(2),Le?" CR":")"]}):Re?s.jsxs("span",{children:[Le&&"-","£",Math.abs(Ne).toFixed(2),Le&&" CR",s.jsx("br",{}),s.jsxs("span",{style:{fontSize:"0.7rem",opacity:.8},children:["(",Le&&"-","£",Math.abs(st).toFixed(2),")"]})]}):s.jsxs("span",{children:[Le&&"-","£",Math.abs(Ne).toFixed(2),Le&&" CR"]})},we.id)})}):s.jsx("span",{style:et.emptyCell,children:"-"})},Q)}),s.jsx("td",{style:{...et.td,...Number(K.total_net_stock)<0?et.negativeTotalCell:et.totalCell},children:(()=>{const Y=Number(K.total_net_stock),Q=Object.values(K.invoices_by_date).flat().reduce((we,Ne)=>we+Number(Ne.net_total??Ne.total??0),0),X=Math.abs(Q)>.01&&Math.abs(Y-Q)>.01,pe=Y<0;return s.jsxs(s.Fragment,{children:[pe?"-":"","£",Math.abs(Y).toFixed(2),pe&&" CR",X&&s.jsxs("div",{style:{fontSize:"0.75rem",color:pe?"#155724":"#888"},children:["(",Q<0?"-":"","£",Math.abs(Q).toFixed(2),")"]})]})})()}),s.jsxs("td",{style:{...et.td,...et.percentCell},children:[Number(K.percentage).toFixed(1),"%"]})]},K.supplier_id??K.supplier_name):null)}),s.jsxs("tfoot",{children:[s.jsxs("tr",{style:et.footerRow,children:[s.jsx("td",{style:{...et.td,...et.footerLabel},children:"Daily Total"}),he.dates.map(K=>{var Ne;const de=K,Y=ue(de),Q=Number(he.daily_totals[de]??0),X=Number(((Ne=he.daily_invoice_totals)==null?void 0:Ne[de])??0),pe=Math.abs(X)>.01&&Math.abs(Q-X)>.01,we=Q<0;return s.jsxs("td",{style:{...et.td,...et.footerCell,...Y?{}:et.outOfMonthCell,...we?{color:"#155724",background:"#d4edda"}:{}},children:[we?"-":"","£",Math.abs(Q).toFixed(2),we&&" CR",pe&&s.jsxs("div",{style:{fontSize:"0.75rem",color:we?"#155724":"#888"},children:["(",X<0?"-":"","£",Math.abs(X).toFixed(2),")"]})]},de)}),s.jsxs("td",{style:{...et.td,...et.grandTotal,...Number(he.week_total)<0?{background:"#28a745"}:{}},children:[Number(he.week_total)<0?"-":"","£",Math.abs(Number(he.week_total)).toFixed(2),Number(he.week_total)<0&&" CR",he.week_invoice_total!=null&&Math.abs(he.week_invoice_total-he.week_total)>.01&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#ccc"},children:["(",Number(he.week_invoice_total)<0?"-":"","£",Math.abs(Number(he.week_invoice_total)).toFixed(2),")"]})]}),s.jsx("td",{style:{...et.td,...et.footerCell},children:"100%"})]}),s.jsxs("tr",{style:et.statsRow,children:[s.jsx("td",{style:{...et.td,...et.statsLabel},children:"Disputes"}),he.dates.map(K=>{var pe;const de=K,Y=ue(de),Q=(pe=I==null?void 0:I.daily_stats)==null?void 0:pe[de],X=Q&&Q.total_disputed>0;return s.jsx("td",{style:{...et.td,...Y?{}:et.outOfMonthCell},children:X?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",alignItems:"center"},children:[Q.unresolved_total>0&&s.jsxs("button",{onClick:()=>e(`/disputes?date=${de}`),style:et.statsBtn,title:`${Q.unresolved_count} unresolved dispute(s)`,children:["£",Q.unresolved_total.toFixed(2)]}),Q.resolved_total>0&&s.jsxs("button",{onClick:()=>e(`/disputes?date=${de}`),style:et.statsBtnResolved,title:`${Q.resolved_count} resolved dispute(s)`,children:["£",Q.resolved_total.toFixed(2)]})]}):s.jsx("span",{style:et.emptyCell,children:"-"})},de)}),s.jsx("td",{style:{...et.td,...et.statsTotal},children:(()=>{const K=Object.entries((I==null?void 0:I.daily_stats)||{}).filter(([Q])=>he.dates.includes(Q)),de=K.reduce((Q,[,X])=>Q+((X==null?void 0:X.unresolved_total)||0),0),Y=K.reduce((Q,[,X])=>Q+((X==null?void 0:X.resolved_total)||0),0);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[de>0&&s.jsxs("span",{style:{color:"#dc3545"},children:["£",de.toFixed(2)]}),Y>0&&s.jsxs("span",{style:{color:"#6c757d"},children:["£",Y.toFixed(2)]}),de===0&&Y===0&&s.jsx("span",{children:"£0.00"})]})})()}),s.jsx("td",{style:{...et.td}})]}),s.jsxs("tr",{style:et.statsRow,children:[s.jsx("td",{style:{...et.td,...et.statsLabel},children:"Allowances"}),he.dates.map(K=>{const de=K,Y=ue(de),{wastageTotal:Q,otherTotal:X,total:pe,wastageBreakdown:we,otherBreakdown:Ne}=z(de),st=pe>0;return s.jsx("td",{style:{...et.td,...Y?{}:et.outOfMonthCell},children:st?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",alignItems:"center"},children:[Q>0&&s.jsxs("button",{onClick:()=>e(`/logbook?date_from=${de}&date_to=${de}`),style:et.wastageBtn,title:we,children:["£",Q.toFixed(2)]}),X>0&&s.jsxs("button",{onClick:()=>e(`/logbook?date_from=${de}&date_to=${de}`),style:et.allowancePurpleBtn,title:Ne,children:["£",X.toFixed(2)]})]}):s.jsx("span",{style:et.emptyCell,children:"-"})},de)}),s.jsx("td",{style:{...et.td,...et.statsTotal},children:(()=>{const K=he.dates.reduce((Y,Q)=>Y+z(Q).wastageTotal,0),de=he.dates.reduce((Y,Q)=>Y+z(Q).otherTotal,0);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[K>0&&s.jsxs("span",{style:{color:"#fd7e14"},children:["£",K.toFixed(2)]}),de>0&&s.jsxs("span",{style:{color:"#6f42c1"},children:["£",de.toFixed(2)]}),K===0&&de===0&&s.jsx("span",{children:"£0.00"})]})})()}),s.jsx("td",{style:{...et.td}})]})]})]})})]},Ge)})]}),s.jsx("div",{style:{...et.periodTotalContainer,...Number(ge)<0?{color:"#28a745"}:{}},children:s.jsxs("strong",{children:["Period Total: ",Number(ge)<0?"-":"","£",Math.abs(Number(ge)).toFixed(2),Number(ge)<0&&" CR"]})})]}),s.jsx("div",{style:et.chartContainer,children:re?s.jsx("div",{style:{textAlign:"center",padding:"2rem",color:"#666"},children:"Loading weekly comparison chart..."}):me?s.jsxs("div",{style:{textAlign:"center",padding:"2rem",color:"#c00"},children:["Error loading chart: ",me.message]}):J.length>0?s.jsx("div",{style:{height:"400px"},children:s.jsx(IU,{data:ke,options:Ye})}):s.jsxs("div",{style:{textAlign:"center",padding:"2rem",color:"#666"},children:[s.jsx("div",{children:"No data available for weekly comparison chart"}),te&&s.jsxs("div",{style:{marginTop:"1rem",fontSize:"0.85rem"},children:["Debug: Date range ",G.from," to ",G.to,s.jsx("br",{}),"Data points received: ",((Be=te.data)==null?void 0:Be.length)||0]})]})})]})}const et={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",flexWrap:"wrap",gap:"1rem"},title:{color:"#1a1a2e",margin:0},printBtn:{padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},periodTotalContainer:{background:"white",borderRadius:"12px",padding:"1rem 1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",textAlign:"right",fontSize:"1.1rem",color:"#e94560"},empty:{background:"white",padding:"3rem",borderRadius:"12px",textAlign:"center",color:"#666"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem"},chartContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginTop:"2rem"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e"},weekContainer:{marginBottom:"2rem"},weekHeader:{display:"flex",alignItems:"center",gap:"1rem",marginBottom:"0.5rem",flexWrap:"wrap"},weekTitle:{fontWeight:"bold",fontSize:"1rem",color:"#1a1a2e"},weekRange:{color:"#666",fontSize:"0.9rem"},weekTotal:{marginLeft:"auto",fontWeight:"bold",color:"#e94560"},tableContainer:{background:"white",borderRadius:"12px",overflow:"auto",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{padding:"0.75rem 0.5rem",background:"#1a1a2e",color:"white",fontWeight:"600",textAlign:"center",whiteSpace:"nowrap"},supplierHeader:{textAlign:"left",paddingLeft:"1rem",minWidth:"150px"},totalHeader:{background:"#2d2d44"},percentHeader:{background:"#2d2d44",minWidth:"60px"},outOfMonth:{background:"#3d3d54",opacity:.7},outOfMonthCell:{background:"#f8f9fa",opacity:.6},tr:{borderBottom:"1px solid #eee"},td:{padding:"0.5rem",textAlign:"center",verticalAlign:"top"},supplierCell:{textAlign:"left",paddingLeft:"1rem",fontWeight:"500",whiteSpace:"nowrap"},unmatchedSupplier:{color:"#721c24",background:"#f8d7da"},unmatchedBadge:{display:"inline-block",marginLeft:"0.3rem",width:"14px",height:"14px",lineHeight:"14px",textAlign:"center",background:"#dc3545",color:"white",borderRadius:"50%",fontSize:"0.7rem",fontWeight:"bold"},invoicesCell:{display:"flex",flexDirection:"column",gap:"0.25rem",alignItems:"center"},invoiceBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#e8f4e8",color:"#155724",borderRadius:"4px",textDecoration:"none",fontSize:"0.85rem",fontWeight:"500",border:"1px solid #c3e6cb",cursor:"pointer"},fuzzyInvoice:{background:"#fff3cd",color:"#856404",border:"1px solid #ffc107"},nonStockInvoice:{background:"#e9ecef",color:"#6c757d",border:"1px solid #ced4da"},unmatchedInvoice:{background:"#f8d7da",color:"#721c24",border:"1px solid #f5c6cb"},creditNoteInvoice:{background:"#d4edda",color:"#155724",border:"2px solid #28a745",fontWeight:"bold"},emptyCell:{color:"#ccc"},totalCell:{fontWeight:"bold",background:"#f8f9fa"},negativeTotalCell:{fontWeight:"bold",background:"#d4edda",color:"#155724"},percentCell:{fontWeight:"500",background:"#f8f9fa",color:"#666"},footerRow:{background:"#f8f9fa",borderTop:"2px solid #dee2e6"},footerLabel:{textAlign:"left",paddingLeft:"1rem",fontWeight:"bold"},footerCell:{fontWeight:"bold"},grandTotal:{fontWeight:"bold",background:"#1a1a2e",color:"white"},statsRow:{background:"#fafbfc",borderTop:"1px solid #e9ecef"},statsLabel:{textAlign:"left",paddingLeft:"1rem",fontWeight:"500",color:"#6c757d",fontSize:"0.85rem"},statsBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#dc3545",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer",minWidth:"28px"},statsBtnResolved:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#6c757d",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer",minWidth:"28px"},allowancePurpleBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#6f42c1",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer"},wastageBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#fd7e14",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer"},statsTotal:{fontWeight:"600",color:"#6c757d",fontSize:"0.85rem"},printContainer:{padding:"1rem",background:"white"},printTitle:{marginBottom:"1rem",color:"#1a1a2e",fontSize:"1.2rem"},printTableSmall:{width:"100%",borderCollapse:"collapse",fontSize:"0.65rem"},printThSmall:{padding:"0.2rem 0.3rem",background:"#f8f9fa",border:"1px solid #dee2e6",textAlign:"left",fontWeight:"bold"},printThDateSmall:{padding:"0.2rem 0.3rem",background:"#f8f9fa",border:"1px solid #dee2e6",textAlign:"left",fontWeight:"bold",whiteSpace:"nowrap",minWidth:"60px"},printThRightSmall:{padding:"0.2rem 0.3rem",background:"#f8f9fa",border:"1px solid #dee2e6",textAlign:"right",fontWeight:"bold"},printTdSmall:{padding:"0.15rem 0.2rem",border:"1px solid #dee2e6"},printTdDateSmall:{padding:"0.15rem 0.2rem",border:"1px solid #dee2e6",whiteSpace:"nowrap"},printTdRightSmall:{padding:"0.15rem 0.2rem",border:"1px solid #dee2e6",textAlign:"right"},printFooter:{background:"#f8f9fa"}},kfe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];function _fe({isOpen:n,onClose:e,onSaved:t,invoiceId:r,distributionId:i,isAdmin:o}){const{token:a}=gn(),[l,d]=k.useState(null),[c,u]=k.useState(null),[f,p]=k.useState({}),[g,m]=k.useState("OFFSET"),[y,v]=k.useState(""),[x,w]=k.useState([!0,!0,!0,!0,!0,!1,!1]),[S,_]=k.useState(4),[b,C]=k.useState(""),[T,F]=k.useState(""),[A,D]=k.useState(!1),[P,L]=k.useState(!1),[W,O]=k.useState(null),[U,M]=k.useState(!1),[I,H]=k.useState(!1),[z,G]=k.useState(""),[te,re]=k.useState("");k.useEffect(()=>{n&&(O(null),p({}),m("OFFSET"),v(""),w([!0,!0,!0,!0,!0,!1,!1]),_(4),C(""),F(""),u(null),d(null),H(!1),G(""),re(""))},[n,r,i]),k.useEffect(()=>{!n||!a||(i?(M(!0),fetch(`/api/cost-distributions/${i}`,{headers:{Authorization:`Bearer ${a}`}}).then(ee=>{if(!ee.ok)throw new Error("Failed to load distribution");return ee.json()}).then(ee=>{u(ee),F(ee.notes||""),M(!1)}).catch(ee=>{O(ee.message),M(!1)})):r&&(M(!0),fetch(`/api/cost-distributions/invoice/${r}/availability`,{headers:{Authorization:`Bearer ${a}`}}).then(ee=>{if(!ee.ok)throw new Error("Failed to load invoice data");return ee.json()}).then(ee=>{d(ee);const Z={};for(const ge of ee.line_items)!ge.is_non_stock&&ge.available_qty>0&&(Z[ge.id]={selected:!1,qty:ge.available_qty});if(p(Z),ee.invoice_date){const ge=new Date(ee.invoice_date),Te=ge.getDay(),Be=Te===0?1:8-Te;ge.setDate(ge.getDate()+Be),C(ge.toISOString().slice(0,10))}M(!1)}).catch(ee=>{O(ee.message),M(!1)})))},[n,a,r,i]);const me=k.useMemo(()=>{if(!c)return 0;const ee=new Date().toISOString().slice(0,10),Z=c.entries.filter(ge=>!ge.is_source_offset&&!ge.is_overpay&&ge.entry_date>ee).reduce((ge,Te)=>ge+Te.amount,0);return Math.round(Z*100)/100},[c]),J=k.useMemo(()=>{if(!c||!z)return me;const ee=c.entries.filter(Z=>!Z.is_source_offset&&!Z.is_overpay&&Z.entry_date>=z).reduce((Z,ge)=>Z+ge.amount,0);return Math.round(ee*100)/100},[c,z,me]);k.useEffect(()=>{if(I&&c&&z){const ee=c.entries.filter(Z=>!Z.is_source_offset&&!Z.is_overpay&&Z.entry_date>=z).reduce((Z,ge)=>Z+ge.amount,0);re((Math.round(ee*100)/100).toFixed(2))}},[z,I,c]);const ne=k.useMemo(()=>{if(!l)return 0;let ee=0;for(const Z of l.line_items){const ge=f[Z.id];ge!=null&&ge.selected&&Z.unit_price&&(ee+=ge.qty*Z.unit_price)}return Math.round(ee*100)/100},[l,f]),ye=k.useMemo(()=>{if(g!=="DISTRIBUTE"||!b||S<1||ne<=0)return[];const ee=x.reduce((He,Ge,ae)=>(Ge&&He.push(ae),He),[]);if(ee.length===0)return[];const Z=[],ge=new Date(b);for(let He=0;He({date:He,amount:Ge===Te.length-1?Math.round((ne-Be*(Te.length-1))*100)/100:Be}))},[g,b,S,x,ne]),ke=async()=>{if(!(!a||!r)){O(null),D(!0);try{const ee=Object.entries(f).filter(([Te,Be])=>Be.selected).map(([Te,Be])=>({line_item_id:parseInt(Te),selected_quantity:Be.qty}));if(ee.length===0){O("Please select at least one line item"),D(!1);return}const Z={invoice_id:r,method:g,notes:T||null,line_selections:ee};if(g==="OFFSET"){if(!y){O("Please select a target date"),D(!1);return}Z.target_date=y}else{const Te=x.reduce((Be,he,He)=>(he&&Be.push(He),Be),[]);if(Te.length===0){O("Please select at least one day"),D(!1);return}if(!b){O("Please select a start date"),D(!1);return}Z.days_of_week=Te,Z.num_weeks=S,Z.start_date=b}const ge=await fetch("/api/cost-distributions/",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!ge.ok){const Te=await ge.json();throw new Error(Te.detail||"Failed to create distribution")}t(),e()}catch(ee){O(ee.message)}finally{D(!1)}}},Ye=async()=>{if(!(!a||!i)){D(!0);try{if(!(await fetch(`/api/cost-distributions/${i}`,{method:"PUT",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({notes:T})})).ok)throw new Error("Failed to update");t(),e()}catch(ee){O(ee.message)}finally{D(!1)}}},De=async()=>{if(!(!a||!i)&&confirm("Are you sure you want to cancel this distribution? This will remove all scheduled entries.")){L(!0);try{const ee=await fetch(`/api/cost-distributions/${i}`,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!ee.ok){const Z=await ee.json();throw new Error(Z.detail||"Failed to delete")}t(),e()}catch(ee){O(ee.message)}finally{L(!1)}}},qe=async ee=>{if(!(!a||!i||!z)){D(!0);try{const Z={entry_date:z};!ee&&te&&(Z.amount=parseFloat(te));const ge=await fetch(`/api/cost-distributions/${i}/settle-early`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!ge.ok){const Te=await ge.json();throw new Error(Te.detail||"Failed to settle")}t(),e()}catch(Z){O(Z.message)}finally{D(!1)}}};if(!n)return null;const ue=!!i&&!!c,Ze=(c==null?void 0:c.status)==="ACTIVE";return s.jsx("div",{style:tt.overlay,onClick:e,children:s.jsxs("div",{style:tt.modal,onClick:ee=>ee.stopPropagation(),children:[s.jsxs("div",{style:tt.header,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("h2",{style:{margin:0,fontSize:"1.1rem"},children:ue?`Cost Distribution #${c.id}`:"New Cost Distribution"}),c&&s.jsx("span",{style:{...tt.statusBadge,background:c.status==="ACTIVE"?"#e3f2fd":c.status==="COMPLETED"?"#e8f5e9":"#ffebee",color:c.status==="ACTIVE"?"#1565c0":c.status==="COMPLETED"?"#2e7d32":"#c62828"},children:c.status})]}),s.jsx("button",{onClick:e,style:tt.closeBtn,children:"×"})]}),s.jsxs("div",{style:tt.body,children:[U&&s.jsx("div",{style:tt.loadingText,children:"Loading..."}),W&&s.jsx("div",{style:tt.error,children:W}),(l||c)&&s.jsxs("div",{style:tt.fieldRow,children:[s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Invoice Date"}),s.jsx("input",{type:"text",disabled:!0,value:(c==null?void 0:c.invoice_date)||(l==null?void 0:l.invoice_date)||"",style:tt.input})]}),s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Invoice #"}),s.jsx("input",{type:"text",disabled:!0,value:(c==null?void 0:c.invoice_number)||(l==null?void 0:l.invoice_number)||"",style:tt.input})]}),s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Supplier"}),s.jsx("input",{type:"text",disabled:!0,value:(c==null?void 0:c.supplier_name)||(l==null?void 0:l.supplier_name)||"",style:tt.input})]})]}),s.jsxs("label",{style:{...tt.field,marginBottom:"1rem"},children:[s.jsx("span",{style:tt.label,children:"Notes"}),s.jsx("textarea",{value:T,onChange:ee=>F(ee.target.value),style:tt.textarea,placeholder:"Optional notes...",disabled:ue&&!Ze})]}),!ue&&l&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:tt.sectionTitle,children:"Line Items"}),s.jsx("div",{style:tt.lineItemsContainer,children:s.jsxs("table",{style:tt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:tt.th}),s.jsx("th",{style:{...tt.th,textAlign:"left"},children:"Description"}),s.jsx("th",{style:tt.th,children:"Unit"}),s.jsx("th",{style:tt.th,children:"Available"}),s.jsx("th",{style:tt.th,children:"Distribute Qty"}),s.jsx("th",{style:tt.th,children:"Price"}),s.jsx("th",{style:tt.th,children:"Value"})]})}),s.jsx("tbody",{children:l.line_items.filter(ee=>!ee.is_non_stock).map(ee=>{const Z=f[ee.id],ge=ee.available_qty<=0,Te=Z!=null&&Z.selected?Math.round(Z.qty*(ee.unit_price||0)*100)/100:0;return s.jsxs("tr",{style:{opacity:ge?.4:1},children:[s.jsx("td",{style:tt.td,children:s.jsx("input",{type:"checkbox",checked:(Z==null?void 0:Z.selected)||!1,disabled:ge,onChange:Be=>p(he=>({...he,[ee.id]:{...he[ee.id],selected:Be.target.checked}}))})}),s.jsx("td",{style:{...tt.td,textAlign:"left",maxWidth:"200px",overflow:"hidden",textOverflow:"ellipsis"},children:ee.description||"-"}),s.jsx("td",{style:tt.td,children:ee.unit||"-"}),s.jsx("td",{style:tt.td,children:ee.available_qty.toFixed(2)}),s.jsx("td",{style:tt.td,children:Z!=null&&Z.selected?s.jsx("input",{type:"number",value:Z.qty,min:.001,max:ee.available_qty,step:.001,onChange:Be=>{const he=Math.min(parseFloat(Be.target.value)||0,ee.available_qty);p(He=>({...He,[ee.id]:{...He[ee.id],qty:he}}))},style:{...tt.qtyInput}}):"-"}),s.jsxs("td",{style:tt.td,children:["£",(ee.unit_price||0).toFixed(2)]}),s.jsx("td",{style:{...tt.td,fontWeight:Z!=null&&Z.selected?600:400},children:Z!=null&&Z.selected?`£${Te.toFixed(2)}`:"-"})]},ee.id)})}),s.jsx("tfoot",{children:s.jsxs("tr",{style:tt.totalRow,children:[s.jsx("td",{colSpan:6,style:{...tt.td,textAlign:"right",fontWeight:600},children:"Total to Distribute:"}),s.jsxs("td",{style:{...tt.td,fontWeight:700,fontSize:"0.95rem"},children:["£",ne.toFixed(2)]})]})})]})}),s.jsx("h3",{style:tt.sectionTitle,children:"Distribution Method"}),s.jsxs("div",{style:tt.tabs,children:[s.jsx("button",{style:g==="OFFSET"?tt.tabActive:tt.tab,onClick:()=>m("OFFSET"),children:"Offset to Date"}),s.jsx("button",{style:g==="DISTRIBUTE"?tt.tabActive:tt.tab,onClick:()=>m("DISTRIBUTE"),children:"Distribute Over Period"})]}),g==="OFFSET"&&s.jsx("div",{style:tt.methodContent,children:s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Target Date"}),s.jsx("input",{type:"date",value:y,onChange:ee=>v(ee.target.value),style:tt.input})]})}),g==="DISTRIBUTE"&&s.jsxs("div",{style:tt.methodContent,children:[s.jsxs("div",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Days of Week"}),s.jsx("div",{style:tt.dowRow,children:kfe.map((ee,Z)=>s.jsx("button",{style:x[Z]?tt.dowBtnActive:tt.dowBtn,onClick:()=>{const ge=[...x];ge[Z]=!ge[Z],w(ge)},children:ee},Z))})]}),s.jsxs("div",{style:tt.fieldRow,children:[s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"For how many weeks?"}),s.jsx("input",{type:"number",value:S,min:1,max:52,onChange:ee=>_(parseInt(ee.target.value)||1),style:{...tt.input,maxWidth:"80px"}})]}),s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Starting from"}),s.jsx("input",{type:"date",value:b,onChange:ee=>C(ee.target.value),style:tt.input})]})]}),ye.length>0&&s.jsxs("div",{style:tt.preview,children:[s.jsxs("div",{style:tt.previewTitle,children:["Preview: ",ye.length," entries, £",ne.toFixed(2)," total"]}),s.jsx("div",{style:tt.previewGrid,children:ye.map(ee=>s.jsxs("div",{style:tt.previewEntry,children:[s.jsx("span",{style:tt.previewDate,children:new Date(ee.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}),s.jsxs("span",{style:tt.previewAmount,children:["£",ee.amount.toFixed(2)]})]},ee.date))})]})]})]}),ue&&c&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:tt.summaryRow,children:[s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Total Value"}),s.jsxs("span",{style:tt.summaryValue,children:["£",c.total_distributed_value.toFixed(2)]})]}),s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Remaining"}),s.jsxs("span",{style:{...tt.summaryValue,color:c.remaining_balance>0?"#e65100":"#2e7d32"},children:["£",c.remaining_balance.toFixed(2)]})]}),s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Method"}),s.jsx("span",{style:tt.summaryValue,children:c.method})]}),s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Created"}),s.jsxs("span",{style:tt.summaryValue,children:[c.created_by_name||"Unknown",", ",new Date(c.created_at).toLocaleDateString("en-GB")]})]})]}),s.jsx("h3",{style:tt.sectionTitle,children:"Distributed Items"}),s.jsx("div",{style:tt.lineItemsContainer,children:s.jsxs("table",{style:tt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...tt.th,textAlign:"left"},children:"Description"}),s.jsx("th",{style:tt.th,children:"Qty"}),s.jsx("th",{style:tt.th,children:"Price"}),s.jsx("th",{style:tt.th,children:"Value"})]})}),s.jsx("tbody",{children:c.line_selections.map(ee=>s.jsxs("tr",{children:[s.jsx("td",{style:{...tt.td,textAlign:"left"},children:ee.description||"-"}),s.jsx("td",{style:tt.td,children:ee.selected_quantity}),s.jsxs("td",{style:tt.td,children:["£",ee.unit_price.toFixed(2)]}),s.jsxs("td",{style:tt.td,children:["£",ee.distributed_value.toFixed(2)]})]},ee.id))})]})}),s.jsx("h3",{style:tt.sectionTitle,children:"Schedule"}),s.jsx("div",{style:tt.lineItemsContainer,children:s.jsxs("table",{style:tt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...tt.th,textAlign:"left"},children:"Date"}),s.jsx("th",{style:tt.th,children:"Amount"}),s.jsx("th",{style:tt.th,children:"Type"})]})}),s.jsx("tbody",{children:c.entries.map(ee=>s.jsxs("tr",{style:{background:ee.is_source_offset?"#fff3e0":ee.is_overpay?"#e3f2fd":"transparent"},children:[s.jsx("td",{style:{...tt.td,textAlign:"left"},children:new Date(ee.entry_date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"})}),s.jsxs("td",{style:{...tt.td,color:ee.amount<0?"#c62828":"#2e7d32",fontWeight:600},children:[ee.amount<0?"-":"","£",Math.abs(ee.amount).toFixed(2)]}),s.jsx("td",{style:tt.td,children:ee.is_source_offset?"Source Offset":ee.is_overpay?"Settled Early":"Scheduled"})]},ee.id))})]})}),Ze&&me>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:tt.sectionTitle,children:"Settle Early"}),I?s.jsxs("div",{style:tt.settleForm,children:[s.jsxs("div",{style:tt.fieldRow,children:[s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Settle Date"}),s.jsx("input",{type:"date",value:z,onChange:ee=>G(ee.target.value),style:tt.input})]}),s.jsxs("label",{style:tt.field,children:[s.jsxs("span",{style:tt.label,children:["Amount (max £",J.toFixed(2),")"]}),s.jsx("input",{type:"number",value:te,min:.01,max:J,step:.01,onChange:ee=>re(ee.target.value),style:{...tt.input,maxWidth:"120px"}})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.5rem"},children:[s.jsx("button",{style:tt.submitBtn,onClick:()=>qe(),disabled:A||!z,children:A?"Settling...":"Confirm Settle"}),s.jsx("button",{style:tt.settleAllBtn,onClick:()=>qe(!0),disabled:A,children:"Settle All"}),s.jsx("button",{style:tt.cancelBtn,onClick:()=>H(!1),children:"Cancel"})]})]}):s.jsx("button",{style:tt.settleBtn,onClick:()=>{H(!0),G(new Date().toISOString().slice(0,10)),re(me.toFixed(2))},children:"Settle Early..."})]})]})]}),s.jsxs("div",{style:tt.footer,children:[s.jsx("div",{style:{display:"flex",gap:"0.5rem"},children:ue&&o&&(c==null?void 0:c.status)!=="CANCELLED"&&s.jsx("button",{style:tt.deleteBtn,onClick:De,disabled:P,children:P?"Cancelling...":"Cancel Distribution"})}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{style:tt.cancelBtn,onClick:e,children:"Close"}),!ue&&s.jsx("button",{style:tt.submitBtn,onClick:ke,disabled:A||ne<=0,children:A?"Saving...":"Create Distribution"}),ue&&Ze&&s.jsx("button",{style:tt.submitBtn,onClick:Ye,disabled:A,children:A?"Saving...":"Save Notes"})]})]})]})})}const tt={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",maxWidth:"850px",width:"95%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.5rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#999",lineHeight:1},statusBadge:{padding:"0.2rem 0.6rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:600},body:{flex:1,overflowY:"auto",padding:"1.5rem"},loadingText:{textAlign:"center",padding:"2rem",color:"#999"},error:{background:"#ffebee",color:"#c62828",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},fieldRow:{display:"flex",gap:"1rem",marginBottom:"1rem"},field:{display:"flex",flexDirection:"column",gap:"0.3rem",flex:1},label:{fontSize:"0.8rem",fontWeight:500,color:"#666"},input:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},textarea:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",minHeight:"50px",resize:"vertical",fontFamily:"inherit"},sectionTitle:{fontSize:"0.95rem",fontWeight:600,margin:"1rem 0 0.5rem 0",color:"#333"},lineItemsContainer:{maxHeight:"300px",overflowY:"auto",border:"1px solid #eee",borderRadius:"6px",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{padding:"0.5rem 0.4rem",background:"#f5f5f5",fontWeight:600,textAlign:"center",borderBottom:"2px solid #ddd",fontSize:"0.8rem",position:"sticky",top:0,zIndex:1},td:{padding:"0.4rem",borderBottom:"1px solid #f0f0f0",textAlign:"center",fontSize:"0.85rem"},totalRow:{background:"#f8f9fa"},qtyInput:{width:"70px",padding:"0.3rem",border:"1px solid #ddd",borderRadius:"4px",textAlign:"center",fontSize:"0.85rem"},tabs:{display:"flex",gap:"0",marginBottom:"1rem"},tab:{flex:1,padding:"0.6rem 1rem",border:"1px solid #ddd",background:"#f5f5f5",cursor:"pointer",fontSize:"0.9rem",fontWeight:500,color:"#666",textAlign:"center"},tabActive:{flex:1,padding:"0.6rem 1rem",border:"1px solid #1a1a2e",background:"#1a1a2e",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500,textAlign:"center"},methodContent:{padding:"1rem",background:"#fafafa",borderRadius:"6px",marginBottom:"1rem"},dowRow:{display:"flex",gap:"0.25rem"},dowBtn:{padding:"0.4rem 0.6rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.8rem",fontWeight:500,color:"#666",minWidth:"42px",textAlign:"center"},dowBtnActive:{padding:"0.4rem 0.6rem",border:"1px solid #1565c0",borderRadius:"4px",background:"#e3f2fd",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,color:"#1565c0",minWidth:"42px",textAlign:"center"},preview:{marginTop:"1rem",padding:"0.75rem",border:"1px solid #c8e6c9",borderRadius:"6px",background:"#f1f8e9"},previewTitle:{fontSize:"0.85rem",fontWeight:600,color:"#33691e",marginBottom:"0.5rem"},previewGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:"0.25rem"},previewEntry:{display:"flex",justifyContent:"space-between",padding:"0.2rem 0.4rem",fontSize:"0.8rem",background:"white",borderRadius:"3px"},previewDate:{color:"#555"},previewAmount:{fontWeight:600,color:"#2e7d32"},summaryRow:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:"0.75rem",marginBottom:"1rem"},summaryItem:{display:"flex",flexDirection:"column",gap:"0.2rem",padding:"0.75rem",background:"#f5f5f5",borderRadius:"6px"},summaryLabel:{fontSize:"0.75rem",fontWeight:500,color:"#999",textTransform:"uppercase"},summaryValue:{fontSize:"0.95rem",fontWeight:600,color:"#333"},settleBtn:{padding:"0.5rem 1rem",border:"1px solid #e65100",borderRadius:"6px",background:"#fff3e0",color:"#e65100",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},settleForm:{padding:"1rem",background:"#fff3e0",borderRadius:"6px",border:"1px solid #ffcc80"},settleAllBtn:{padding:"0.5rem 1rem",border:"1px solid #e65100",borderRadius:"6px",background:"#e65100",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},footer:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.5rem",borderTop:"1px solid #eee"},cancelBtn:{padding:"0.5rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"white",cursor:"pointer",fontSize:"0.9rem"},submitBtn:{padding:"0.5rem 1rem",border:"none",borderRadius:"6px",background:"#1a1a2e",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},deleteBtn:{padding:"0.5rem 1rem",border:"1px solid #c62828",borderRadius:"6px",background:"#ffebee",color:"#c62828",cursor:"pointer",fontSize:"0.85rem"}};pf.register(Bj,Ij,y5,U6,H6,W6);const GP=n=>{const e=new Date(n);return`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][e.getDay()]} ${e.getDate()}`},KP=(n,e)=>{const t=new Date(n),r=new Date(e),i=t.toLocaleDateString("en-GB",{month:"short"}),o=r.toLocaleDateString("en-GB",{month:"short"});return i===o?`${t.getDate()} - ${r.getDate()} ${i}`:`${t.getDate()} ${i} - ${r.getDate()} ${o}`};function Cfe(){const{token:n,user:e}=gn(),t=go(),r=pi(),[i,o]=k.useState(0),[a,l]=k.useState(!1),[d,c]=k.useState(!1),[u,f]=k.useState(!1),[p,g]=k.useState(null),[m,y]=k.useState(null),[v,x]=k.useState(null),[w,S]=k.useState(!1),[_,b]=k.useState(!1),[C,T]=k.useState(null),[F,A]=k.useState(null),[D,P]=k.useState(!1),[L,W]=k.useState(new Set),{data:O,isLoading:U,error:M,refetch:I}=Oe({queryKey:["budget","weekly",i],queryFn:async()=>{const X=await fetch(`/api/budget/weekly?week_offset=${i}`,{headers:{Authorization:`Bearer ${n}`}});if(!X.ok)throw new Error("Failed to fetch budget data");return X.json()},enabled:!!n}),{data:H}=Oe({queryKey:["budget","weekly",i-1],queryFn:async()=>{const X=await fetch(`/api/budget/weekly?week_offset=${i-1}`,{headers:{Authorization:`Bearer ${n}`}});return X.ok?X.json():null},enabled:!!n}),{data:z}=Oe({queryKey:["budget","weekly",i-2],queryFn:async()=>{const X=await fetch(`/api/budget/weekly?week_offset=${i-2}`,{headers:{Authorization:`Bearer ${n}`}});return X.ok?X.json():null},enabled:!!n}),G=()=>o(X=>X-1),te=()=>o(X=>X+1),re=()=>o(0),[me,J]=k.useState({}),[ne,ye]=k.useState(!1),{data:ke,refetch:Ye,isLoading:De}=Oe({queryKey:["cover-overrides","weekly",i],queryFn:async()=>{const X=await fetch(`/api/cover-overrides/weekly?week_offset=${i}`,{headers:{Authorization:`Bearer ${n}`}});if(!X.ok)throw new Error("Failed to fetch override data");return X.json()},enabled:!!n&&a}),{data:qe}=Oe({queryKey:["cost-distributions","weekly",i,O==null?void 0:O.week_start,O==null?void 0:O.week_end],queryFn:async()=>{const X=await fetch(`/api/cost-distributions/weekly?week_start=${O.week_start}&week_end=${O.week_end}`,{headers:{Authorization:`Bearer ${n}`}});if(!X.ok)throw new Error("Failed to fetch distribution data");return X.json()},enabled:!!n&&!!O});k.useEffect(()=>{qe&&qe.distributions.some(X=>X.status==="ACTIVE"&&(X.bf_balance!==0||X.cf_balance!==0))&&P(!0)},[qe]);const{data:ue}=Oe({queryKey:["resos","resident-covers",O==null?void 0:O.week_start,O==null?void 0:O.week_end],queryFn:async()=>{const X=await fetch(`/api/resos/resident-covers?start_date=${O.week_start}&end_date=${O.week_end}`,{headers:{Authorization:`Bearer ${n}`}});return X.ok?(await X.json()).dates??{}:{}},enabled:!!n&&!!O&&a}),Ze=Ue({mutationFn:async()=>{const X=await fetch("/api/cover-overrides/snapshot",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({week_offset:i})});if(!X.ok)throw new Error("Failed to create snapshot");return X.json()},onSuccess:()=>{Ye(),I()}}),ee=Object.keys(me).length>0,Z=(X,pe,we)=>{const Ne=`${X}|${pe}`;return Ne in me?me[Ne]:we},ge=(X,pe)=>`${X}|${pe}`in me?!0:!!(ke!=null&&ke.overrides.find(Ne=>Ne.override_date===X&&Ne.period===pe)),Te=(X,pe,we,Ne)=>{const st=`${X}|${pe}`,Ve=st in me?me[st]:we;J(Re=>({...Re,[st]:Math.max(0,Ve+Ne)}))},Be=async()=>{ye(!0);try{await Promise.all(Object.entries(me).map(([X,pe])=>{const[we,Ne]=X.split("|");return fetch("/api/cover-overrides",{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({override_date:we,period:Ne,override_covers:pe})})})),J({}),Ye(),I()}finally{ye(!1)}},he=async X=>{await fetch(`/api/cover-overrides/${X}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}}),Ye(),I()},He=async(X,pe,we)=>{await fetch("/api/cover-overrides/spend-rates",{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({week_offset:i,period:X,food_spend:pe,drinks_spend:we})}),Ye(),I()},Ge=X=>{const pe=new Date;pe.setHours(0,0,0,0);const we=new Date(X);return we.setHours(0,0,0,0),we<=pe},ae=X=>{const pe=new Date;pe.setHours(0,0,0,0);const we=new Date(X);return we.setHours(0,0,0,0),weX.dates.map(pe=>{const we=X.daily_totals[pe]??0;let Ne=0;return X.suppliers.forEach(st=>{((st.purchase_orders_by_date||{})[pe]||[]).forEach(Re=>{Ne+=Re.total_amount||0})}),we+Ne}),de=O?(()=>{const X=K(O),pe=H?K(H):Array(7).fill(0),we=z?K(z):Array(7).fill(0),Ne=H?KP(H.week_start,H.week_end):"Week -2",st=z?KP(z.week_start,z.week_end):"Week -3";return{labels:O.daily_data.map(Ve=>Ve.day_name),datasets:[{label:st,data:we,backgroundColor:"rgba(189, 195, 199, 0.4)",borderColor:"rgba(189, 195, 199, 0.6)",borderWidth:1,borderRadius:3,order:3},{label:Ne,data:pe,backgroundColor:"rgba(52, 152, 219, 0.35)",borderColor:"rgba(52, 152, 219, 0.5)",borderWidth:1,borderRadius:3,order:2},{label:"This Week",data:X,backgroundColor:"rgba(46, 204, 113, 0.7)",borderColor:"rgba(39, 174, 96, 0.9)",borderWidth:1,borderRadius:3,order:1}]}})():null,Y={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top"},title:{display:!1},tooltip:{callbacks:{label:X=>{var pe;return`${X.dataset.label}: £${((pe=X.parsed.y)==null?void 0:pe.toFixed(2))??"0.00"}`}}}},scales:{y:{beginAtZero:!0,ticks:{callback:X=>`£${Number(X).toLocaleString()}`}}}};if(U)return s.jsx("div",{style:xe.container,children:s.jsx("div",{style:xe.loading,children:"Loading budget data..."})});if(M||!O)return s.jsx("div",{style:xe.container,children:s.jsxs("div",{style:xe.error,children:[s.jsx("p",{children:"Failed to load budget data."}),s.jsx("p",{style:{fontSize:"0.9rem",color:"#666"},children:"Make sure the Forecast API is configured in Settings."}),s.jsx("button",{onClick:()=>I(),style:xe.retryBtn,children:"Retry"})]})});const Q=O.total_budget>0?Math.round(O.total_spent/O.total_budget*100):0;return s.jsxs("div",{style:xe.container,children:[s.jsxs("div",{style:xe.header,children:[s.jsx("h2",{style:xe.title,children:"Spend Budget"}),s.jsxs("div",{style:xe.weekNav,children:[s.jsx("button",{onClick:G,style:xe.navBtn,children:"<"}),s.jsx("button",{onClick:re,style:xe.currentBtn,children:i===0?"This Week":"Current"}),s.jsx("button",{onClick:te,style:xe.navBtn,children:">"})]})]}),s.jsxs("div",{style:xe.weekInfo,children:[KP(O.week_start,O.week_end),O.forecast_source!=="forecast_api"&&s.jsx("span",{style:xe.warningBadge,children:"No forecast data"})]}),O.forecast_summary&&(()=>{var st,Ve;const X=O.forecast_summary,pe=X.daily_covers,we=pe.length>0,Ne=we?pe.every(Re=>ae(Re.date)):O.dates.every(Re=>ae(Re));return s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("button",{onClick:()=>l(!a),style:xe.forecastToggle,children:[a?"▾ Hide":"▸ Show"," Forecast Breakdown"]}),a&&s.jsx("div",{style:xe.forecastTableContainer,children:s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh,children:"Service"}),(we?pe:O.dates.map(Re=>({date:Re,day_name:GP(Re)}))).map(Re=>s.jsx("th",{style:xe.forecastTh,children:"day_name"in Re&&Re.day_name?Re.day_name:GP(Re.date)},Re.date)),s.jsx("th",{style:{...xe.forecastTh,...xe.forecastTotalCol},children:"Total"})]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:"Hotel"}),we?pe.map(Re=>{const Le=ae(Re.date),rt=Le?xe.fcActual:xe.fcOtb,$e=Le?xe.fcActual:xe.fcPickup;return s.jsxs("td",{style:xe.forecastTd,children:[s.jsx("span",{style:rt,children:Re.otb_rooms}),s.jsxs("span",{style:{...rt,fontSize:"0.75rem"},children:[" (",Re.otb_guests,")"]}),Re.pickup_rooms>0&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:$e,children:[" +",Re.pickup_rooms]}),s.jsxs("span",{style:{...$e,fontSize:"0.75rem"},children:[" (",Re.pickup_guests,")"]})]})]},Re.date)}):O.dates.map(Re=>s.jsx("td",{style:xe.forecastTd,children:"-"},Re)),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol},children:Ne?s.jsxs("span",{style:xe.fcActual,children:[X.forecast_rooms," (",X.forecast_guests,")"]}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:xe.fcOtb,children:[X.otb_rooms," (",X.otb_guests,")"]}),X.pickup_rooms>0&&s.jsxs("span",{style:xe.fcPickup,children:[" +",X.pickup_rooms," (",X.pickup_guests,")"]})]})})]}),["breakfast","lunch","dinner"].map(Re=>{const Le=X[Re];return s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:Re.charAt(0).toUpperCase()+Re.slice(1)}),we?pe.map(rt=>{const $e=rt[Re],ce=ae(rt.date),Je=ce?xe.fcActual:xe.fcOtb,jt=ce?xe.fcActual:xe.fcPickup;return s.jsx("td",{style:xe.forecastTd,children:ce?s.jsx("span",{style:Je,children:$e.forecast}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:Je,children:$e.otb}),$e.pickup>0&&s.jsxs("span",{style:jt,children:[" +",$e.pickup]})]})},rt.date)}):O.dates.map(rt=>s.jsx("td",{style:xe.forecastTd,children:"-"},rt)),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol},children:Ne?s.jsx("span",{style:xe.fcActual,children:Le.forecast}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:xe.fcOtb,children:Le.otb}),Le.pickup>0&&s.jsxs("span",{style:xe.fcPickup,children:[" +",Le.pickup]}),s.jsxs("span",{style:xe.fcTotal,children:[" = ",Le.forecast]})]})})]},Re)}),ue&&s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:{...xe.forecastServiceCell,fontSize:"0.8rem",color:"#888",fontStyle:"italic"},children:"inc Residents"}),we?pe.map(Re=>{const Le=ue[Re.date]||{},rt=Le.lunch||{covers:0,bookings:0},$e=Le.dinner||{covers:0,bookings:0},ce=rt.bookings+$e.bookings,Je=rt.covers+$e.covers;return s.jsx("td",{style:{...xe.forecastTd,fontSize:"0.8rem",color:"#888",fontStyle:"italic"},children:Je>0?`${ce}/${Je}`:"-"},Re.date)}):O.dates.map(Re=>s.jsx("td",{style:{...xe.forecastTd,fontSize:"0.8rem",color:"#888"},children:"-"},Re)),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol,fontSize:"0.8rem",color:"#888",fontStyle:"italic"},children:(()=>{let Re=0,Le=0;return Object.values(ue).forEach(rt=>{const $e=rt.lunch||{covers:0,bookings:0},ce=rt.dinner||{covers:0,bookings:0};Re+=$e.bookings+ce.bookings,Le+=$e.covers+ce.covers}),Le>0?`${Re}/${Le}`:"-"})()})]})]})]})}),a&&De&&s.jsx("div",{style:{textAlign:"center",padding:"1rem",color:"#888",fontSize:"0.85rem"},children:"Loading override data..."}),a&&ke&&!ke.has_snapshot&&s.jsxs("div",{style:{textAlign:"center",padding:"1rem"},children:[s.jsx("button",{onClick:()=>Ze.mutate(),disabled:Ze.isPending,style:xe.snapshotBtn,children:Ze.isPending?"Creating Snapshot...":"Snapshot Forecast & Override"}),s.jsx("div",{style:{fontSize:"0.8rem",color:"#888",marginTop:"0.5rem"},children:"Takes a snapshot of the current forecast as a baseline for overrides"})]}),a&&(ke==null?void 0:ke.has_snapshot)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:xe.snapshotInfoBar,children:[s.jsxs("span",{children:["Snapshot: £",((st=ke.snapshot_revenue)==null?void 0:st.toLocaleString(void 0,{minimumFractionDigits:2}))??"-",ke.adjusted_revenue!=null&&Math.abs(ke.adjusted_revenue-(ke.snapshot_revenue??0))>1&&s.jsxs("span",{style:{marginLeft:"0.5rem",fontWeight:"bold",color:ke.adjusted_revenue>(ke.snapshot_revenue??0)?"#27ae60":"#e74c3c"},children:["→ £",ke.adjusted_revenue.toLocaleString(void 0,{minimumFractionDigits:2})]})]}),s.jsx("button",{onClick:()=>{window.confirm("Re-snapshot will update the baseline forecast. Continue?")&&Ze.mutate()},style:xe.resnapshotBtn,disabled:Ze.isPending,children:Ze.isPending?"...":"Re-snapshot"})]}),s.jsxs("div",{style:xe.overrideTableContainer,children:[s.jsxs("div",{style:{...xe.overrideSectionHeader,cursor:"pointer",userSelect:"none"},onClick:()=>c(!d),children:[d?"▾":"▸"," Food Spend Per Cover (Gross inc VAT)"]}),d&&s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh}),ke.spend_rates.map(Re=>s.jsx("th",{style:xe.forecastTh,children:Re.period.charAt(0).toUpperCase()+Re.period.slice(1)},Re.period))]})}),s.jsx("tbody",{children:s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:"Food £/hd"}),ke.spend_rates.map(Re=>{const Le=Re.food_spend_effective*ke.vat_rate;return s.jsx("td",{style:xe.forecastTd,children:s.jsx("input",{type:"number",step:"0.50",defaultValue:Le.toFixed(2),style:{...xe.spendInput,...Re.food_spend_override!==null?xe.spendInputOverridden:{}},onBlur:rt=>{const $e=parseFloat(rt.target.value);if(!isNaN($e)&&Math.abs($e-Le)>.001){const ce=Math.round($e/ke.vat_rate*100)/100;He(Re.period,ce,null)}},onKeyDown:rt=>{rt.key==="Enter"&&rt.target.blur()}},`food-${Re.period}-${Le.toFixed(2)}`)},Re.period)})]})})]})]}),s.jsxs("div",{style:xe.overrideTableContainer,children:[s.jsxs("div",{style:{...xe.overrideSectionHeader,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{children:"Cover Overrides (Lunch & Dinner)"}),ee&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>J({}),style:xe.discardBtn,children:"Discard"}),s.jsx("button",{onClick:Be,disabled:ne,style:xe.saveOverrideBtn,children:ne?"Saving...":"Save"})]})]}),s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh,children:"Service"}),ke.recalc_days.map(Re=>s.jsx("th",{style:xe.forecastTh,children:Re.day_name},Re.date))]})}),s.jsx("tbody",{children:["lunch","dinner"].map(Re=>s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:Re.charAt(0).toUpperCase()+Re.slice(1)}),ke.recalc_days.map(Le=>{const rt=Le.periods[Re];if(!rt)return s.jsx("td",{style:xe.forecastTd,children:"-"},Le.date);const $e=ke.overrides.find(Se=>Se.override_date===Le.date&&Se.period===Re),ce=Z(Le.date,Re,($e==null?void 0:$e.override_covers)??rt.effective),Je=ge(Le.date,Re),ct=`${Le.date}|${Re}`in me;return Le.is_past?s.jsx("td",{style:{...xe.forecastTd,color:"#999"},children:rt.effective},Le.date):s.jsx("td",{style:xe.forecastTd,children:s.jsxs("div",{style:xe.stepperCell,children:[s.jsx("button",{onClick:()=>Te(Le.date,Re,($e==null?void 0:$e.override_covers)??rt.effective,-1),style:xe.stepperBtn,children:"−"}),s.jsx("span",{style:Je?xe.overriddenValue:void 0,children:ce}),s.jsx("button",{onClick:()=>Te(Le.date,Re,($e==null?void 0:$e.override_covers)??rt.effective,1),style:xe.stepperBtn,children:"+"}),$e&&!ct&&s.jsx("button",{onClick:()=>he($e.id),style:xe.deleteOverrideBtn,title:"Remove override",children:"×"})]})},Le.date)})]},Re))})]})]}),s.jsxs("div",{style:xe.overrideTableContainer,children:[s.jsx("div",{style:xe.overrideSectionHeader,children:"Recalculated Forecast"}),s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh,children:"Service"}),ke.recalc_days.map(Re=>s.jsx("th",{style:xe.forecastTh,children:Re.day_name},Re.date)),s.jsx("th",{style:{...xe.forecastTh,...xe.forecastTotalCol},children:"Total"})]})}),s.jsxs("tbody",{children:[["breakfast","lunch","dinner"].map(Re=>{let Le=0;return s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:Re.charAt(0).toUpperCase()+Re.slice(1)}),ke.recalc_days.map(rt=>{const $e=rt.periods[Re];return $e?(Le+=$e.effective,rt.is_past?s.jsxs("td",{style:xe.forecastTd,children:[s.jsx("span",{style:xe.fcActual,children:$e.actual??$e.effective}),$e.variance!=null&&$e.variance!==0&&s.jsxs("span",{style:{fontSize:"0.7rem",marginLeft:"2px",color:$e.variance>0?"#27ae60":"#e74c3c"},children:[$e.variance>0?"▲":"▼",Math.abs($e.variance)]})]},rt.date):s.jsxs("td",{style:xe.forecastTd,children:[s.jsx("span",{style:xe.fcOtb,children:$e.otb}),$e.pickup>0&&s.jsx("span",{style:{...xe.fcPickup,...$e.is_overridden?xe.overriddenValue:{}},children:" +"+$e.pickup})]},rt.date)):s.jsx("td",{style:xe.forecastTd,children:"-"},rt.date)}),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol},children:Le})]},Re)}),s.jsxs("tr",{style:{...xe.forecastTr,borderTop:"2px solid #ddd"},children:[s.jsx("td",{style:{...xe.forecastServiceCell,fontStyle:"italic",color:"#666"},children:"Revenue"}),ke.recalc_days.map(Re=>s.jsxs("td",{style:{...xe.forecastTd,fontSize:"0.8rem",color:"#666"},children:["£",Re.day_revenue.toLocaleString(void 0,{maximumFractionDigits:0})]},Re.date)),s.jsxs("td",{style:{...xe.forecastTd,...xe.forecastTotalCol,fontSize:"0.8rem"},children:["£",((Ve=ke.adjusted_revenue)==null?void 0:Ve.toLocaleString(void 0,{maximumFractionDigits:0}))??"-"]})]})]})]})]})]})]})})(),s.jsxs("div",{style:xe.summaryCards,children:[s.jsxs("div",{style:xe.card,children:[s.jsx("div",{style:xe.cardLabel,children:O.has_overrides?"Adjusted Revenue":"Forecast Revenue"}),s.jsxs("div",{style:xe.cardValue,children:["£",O.forecast_revenue.toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsx("div",{style:xe.cardSubtext,children:O.has_overrides&&O.snapshot_revenue!=null?`Snapshot: £${O.snapshot_revenue.toLocaleString(void 0,{minimumFractionDigits:2})}`:`OTB: £${O.otb_revenue.toLocaleString(void 0,{minimumFractionDigits:2})}`})]}),s.jsxs("div",{style:xe.card,children:[s.jsx("div",{style:xe.cardLabel,children:"Budget"}),s.jsxs("div",{style:xe.cardValue,children:["£",O.total_budget.toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsxs("div",{style:xe.cardSubtext,children:["OTB: £",O.min_budget.toLocaleString(void 0,{minimumFractionDigits:2})]})]}),s.jsxs("div",{style:xe.card,children:[s.jsx("div",{style:xe.cardLabel,children:"Spent"}),s.jsxs("div",{style:{...xe.cardValue,color:O.total_remaining<0?"#e74c3c":"#333"},children:["£",O.total_spent.toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsxs("div",{style:xe.cardSubtext,children:[Q,"% used"]})]}),s.jsxs("div",{style:{...xe.card,...O.total_remaining<0?xe.cardOver:xe.cardUnder},children:[s.jsx("div",{style:xe.cardLabel,children:"Remaining"}),s.jsxs("div",{style:xe.cardValue,children:[O.total_remaining<0?"-":"","£",Math.abs(O.total_remaining).toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsx("div",{style:xe.cardSubtext,children:O.total_remaining<0?"OVER BUDGET":`${100-Q}% remaining`})]})]}),s.jsxs("div",{style:xe.section,children:[s.jsx("h3",{style:xe.sectionTitle,children:"Weekly Budget by Supplier"}),s.jsx("div",{style:xe.tableContainer,children:s.jsxs("table",{style:xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...xe.th,...xe.supplierHeader},children:"Supplier"}),O.dates.map(X=>s.jsx("th",{style:{...xe.th,...Ge(X)?{}:xe.futureDate},children:GP(X)},X)),s.jsx("th",{style:{...xe.th,...xe.budgetHeader},children:"Budget"}),s.jsx("th",{style:{...xe.th,...xe.spentHeader},children:"Spent"}),s.jsx("th",{style:{...xe.th,...xe.orderedHeader},children:"Ordered"}),s.jsx("th",{style:{...xe.th,...xe.remainingHeader},children:"Remaining"}),s.jsx("th",{style:{...xe.th,...xe.statusHeader},children:"Status"})]})}),s.jsx("tbody",{children:O.suppliers.map(X=>Object.values(X.invoices_by_date).some(we=>we.length>0)||Object.values(X.purchase_orders_by_date||{}).some(we=>we.length>0)||X.allocated_budget>0?s.jsxs("tr",{style:xe.tr,children:[s.jsxs("td",{style:xe.supplierCell,children:[s.jsx("div",{children:X.supplier_name}),X.historical_pct>0&&s.jsxs("div",{style:xe.supplierPct,children:["(",X.historical_pct.toFixed(1),"%)"]})]}),O.dates.map(we=>{const Ne=X.invoices_by_date[we]||[],st=(X.purchase_orders_by_date||{})[we]||[],Ve=Ne.length>0||st.length>0;return s.jsx("td",{style:{...xe.td,...!Ve&&X.supplier_id?xe.clickableCell:{}},onClick:()=>{!Ve&&X.supplier_id&&(y(X.supplier_id),x(we),g(null),f(!0))},children:Ve?s.jsxs("div",{style:xe.invoicesCell,children:[Ne.map(Re=>{const Le=Re.document_type==="credit_note"||Re.net_stock<0;return s.jsxs("button",{onClick:()=>{w&&!Le?(T(Re.id),A(null),b(!0),S(!1)):t(`/invoice/${Re.id}`)},style:{...xe.invoiceBtn,...Le?xe.creditNoteBtn:{},...w&&!Le?xe.invoiceBtnSelectMode:{}},title:w&&!Le?"Click to distribute this invoice":Re.invoice_number||`Invoice #${Re.id}`,children:[Le&&"-","£",Math.abs(Re.net_stock).toFixed(2),Le&&" CR"]},Re.id)}),st.map(Re=>s.jsxs("button",{onClick:Le=>{Le.stopPropagation(),g(Re.id),y(null),x(null),f(!0)},style:xe.poBtn,title:Re.order_reference?`PO: ${Re.order_reference}`:`PO #${Re.id}`,children:["£",(Re.total_amount||0).toFixed(2)]},`po-${Re.id}`))]}):s.jsx("span",{style:xe.emptyCell,children:X.supplier_id?"+":"-"})},we)}),s.jsxs("td",{style:xe.budgetCell,children:["£",X.allocated_budget.toFixed(2)]}),s.jsxs("td",{style:xe.spentCell,children:["£",X.actual_spent.toFixed(2),X.cd_total!==0&&s.jsxs("div",{style:{fontSize:"0.65rem",color:X.cd_total>0?"#e65100":"#2e7d32"},children:["(",X.cd_total>0?"+":"-","£",Math.abs(X.cd_total).toFixed(2)," dist)"]})]}),s.jsx("td",{style:xe.orderedCell,children:X.po_ordered>0?`£${X.po_ordered.toFixed(2)}`:"-"}),s.jsxs("td",{style:{...xe.remainingCell,...X.remaining<0?xe.overBudget:{}},children:[X.remaining<0?"-":"","£",Math.abs(X.remaining).toFixed(2)]}),s.jsx("td",{style:xe.statusCell,children:s.jsx("span",{style:{...xe.statusBadge,...X.status==="over"?xe.statusOver:X.status==="on_track"?xe.statusOnTrack:xe.statusUnder},children:X.status==="over"?"!":X.status==="on_track"?"~":""})})]},X.supplier_id??X.supplier_name):null)}),s.jsxs("tfoot",{children:[qe&&qe.week_total!==0&&s.jsxs("tr",{style:{...xe.footerRow,background:"#fff8e1"},children:[s.jsx("td",{style:{...xe.footerLabel,color:"#e65100",fontWeight:600},children:"Distributed"}),O.dates.map(X=>{const pe=qe.daily_totals[X]??0;return s.jsx("td",{style:{...xe.footerTd,color:pe<0?"#c62828":pe>0?"#2e7d32":"#999",fontWeight:500},children:pe!==0?s.jsxs(s.Fragment,{children:[pe<0?"-":"+","£",Math.abs(pe).toFixed(2)]}):"-"},X)}),s.jsx("td",{style:xe.footerTd}),s.jsxs("td",{style:{...xe.footerTd,color:"#e65100",fontWeight:600},children:[qe.week_total<0?"-":"+","£",Math.abs(qe.week_total).toFixed(2)]}),s.jsx("td",{style:xe.footerTd}),s.jsx("td",{style:xe.footerTd}),s.jsx("td",{style:xe.footerTd})]}),s.jsxs("tr",{style:xe.footerRow,children:[s.jsx("td",{style:xe.footerLabel,children:"Daily Total"}),O.dates.map(X=>{const pe=O.daily_totals[X]??0,we=Ge(X);return s.jsx("td",{style:xe.footerTd,children:we?`£${pe.toFixed(2)}`:"-"},X)}),s.jsxs("td",{style:xe.footerTd,children:["£",O.total_budget.toFixed(2)]}),s.jsxs("td",{style:xe.footerTd,children:["£",O.total_spent.toFixed(2)]}),s.jsx("td",{style:xe.footerTd,children:O.total_po_ordered>0?`£${O.total_po_ordered.toFixed(2)}`:"-"}),s.jsxs("td",{style:{...xe.footerTd,...O.total_remaining<0?xe.overBudget:{}},children:[O.total_remaining<0?"-":"","£",Math.abs(O.total_remaining).toFixed(2)]}),s.jsx("td",{style:xe.footerTd})]}),s.jsxs("tr",{style:xe.footerRow,children:[s.jsx("td",{style:xe.footerLabel,children:"% of Budget"}),O.daily_data.map(X=>{if(X.actual_spent===null||O.total_budget===0)return s.jsx("td",{style:xe.footerTd,children:"-"},X.date);const pe=X.actual_spent/O.total_budget*100;return s.jsx("td",{style:xe.footerTd,children:X.actual_spent===0?"0%":`${pe.toFixed(0)}%`},X.date)}),s.jsx("td",{colSpan:5})]})]})]})})]}),s.jsxs("div",{style:xe.section,children:[s.jsxs("div",{style:xe.distributionHeader,onClick:()=>P(!D),children:[s.jsxs("span",{style:{cursor:"pointer"},children:[D?"▾":"▸"," Distributed Costs"]}),qe&&qe.distributions.length>0&&s.jsxs("span",{style:xe.distributionSummary,children:["BF: ",qe.bf_balance<0?"-":"","£",Math.abs(qe.bf_balance).toFixed(2)," | ","Movement: ",qe.week_total<0?"-":qe.week_total>0?"+":"","£",Math.abs(qe.week_total).toFixed(2)," | ","CF: ",qe.cf_balance<0?"-":"","£",Math.abs(qe.cf_balance).toFixed(2)]})]}),D&&O&&s.jsx("div",{style:{overflowX:"auto",marginTop:"0.5rem"},children:s.jsxs("table",{style:xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...xe.th,...xe.supplierHeader,minWidth:"180px"},children:"Distribution"}),s.jsx("th",{style:{...xe.th,minWidth:"70px"},children:"BF"}),O.dates.map(X=>s.jsx("th",{style:{...xe.th,minWidth:"70px"},children:new Date(X).toLocaleDateString("en-GB",{weekday:"short",day:"numeric"})},X)),s.jsx("th",{style:{...xe.th,minWidth:"70px"},children:"CF"})]})}),s.jsxs("tbody",{children:[qe==null?void 0:qe.distributions.map(X=>{const pe=L.has(X.distribution_id);return s.jsxs(k.Fragment,{children:[s.jsxs("tr",{children:[s.jsxs("td",{style:{...xe.supplierCell,fontSize:"0.8rem",padding:"0.3rem 0.5rem"},children:[s.jsx("span",{style:{cursor:"pointer",color:"#555",marginRight:"0.3rem",fontSize:"0.7rem"},onClick:()=>W(we=>{const Ne=new Set(we);return Ne.has(X.distribution_id)?Ne.delete(X.distribution_id):Ne.add(X.distribution_id),Ne}),children:pe?"▾":"▸"}),s.jsx("span",{style:{cursor:"pointer",color:"#1565c0"},onClick:()=>{A(X.distribution_id),T(X.invoice_id),b(!0)},title:"Click to view/edit distribution",children:X.title})]}),s.jsx("td",{style:{...xe.dayCell,fontWeight:600,fontSize:"0.8rem",color:"#555"},children:X.bf_balance!==0?s.jsxs(s.Fragment,{children:[X.bf_balance<0?"-":"","£",Math.abs(X.bf_balance).toFixed(2)]}):"-"}),O.dates.map(we=>{const Ne=X.entries_by_date[we];return s.jsx("td",{style:{...xe.dayCell,fontSize:"0.8rem"},children:Ne!=null?s.jsxs("span",{style:{color:Ne<0?"#c62828":"#2e7d32",fontWeight:500},children:[Ne<0?"-":"","£",Math.abs(Ne).toFixed(2)]}):"-"},we)}),s.jsx("td",{style:{...xe.dayCell,fontWeight:600,fontSize:"0.8rem",color:X.cf_balance<0?"#c62828":X.cf_balance===0?"#2e7d32":"#555"},children:X.cf_balance!==0?s.jsxs(s.Fragment,{children:[X.cf_balance<0?"-":"","£",Math.abs(X.cf_balance).toFixed(2)]}):"£0.00"})]}),pe&&s.jsx("tr",{children:s.jsxs("td",{colSpan:O.dates.length+3,style:{padding:"0.3rem 0.5rem 0.5rem 1.5rem",background:"#fafafa",fontSize:"0.75rem",color:"#555",borderTop:"none"},children:[s.jsxs("div",{style:{fontWeight:600},children:[X.supplier_name||"Unknown"," ",X.invoice_number||""]}),s.jsx("div",{children:X.summary}),X.notes&&s.jsx("div",{style:{fontStyle:"italic",marginTop:"0.2rem",color:"#888"},children:X.notes})]})})]},X.distribution_id)}),qe&&qe.distributions.length>0&&s.jsxs("tr",{style:{background:"#f8f9fa",borderTop:"2px solid #ddd"},children:[s.jsx("td",{style:{...xe.supplierCell,fontWeight:600,fontSize:"0.8rem"},children:"Total Movement"}),s.jsx("td",{style:xe.dayCell}),O.dates.map(X=>{const pe=qe.daily_totals[X]??0;return s.jsx("td",{style:{...xe.dayCell,fontWeight:600,fontSize:"0.8rem"},children:pe!==0?s.jsxs("span",{style:{color:pe<0?"#c62828":"#2e7d32"},children:[pe<0?"-":"+","£",Math.abs(pe).toFixed(2)]}):"-"},X)}),s.jsx("td",{style:xe.dayCell})]}),qe&&qe.distributions.length>0&&(()=>{let X=qe.bf_balance;return s.jsxs("tr",{style:{background:"#f0f4f8"},children:[s.jsx("td",{style:{...xe.supplierCell,fontWeight:700,fontSize:"0.8rem"},children:"Balance"}),s.jsx("td",{style:{...xe.dayCell,fontWeight:700,fontSize:"0.8rem"},children:X!==0?s.jsxs(s.Fragment,{children:[X<0?"-":"","£",Math.abs(X).toFixed(2)]}):"-"}),O.dates.map(pe=>(X+=qe.daily_totals[pe]??0,s.jsx("td",{style:{...xe.dayCell,fontWeight:700,fontSize:"0.8rem",color:X<0?"#c62828":X===0?"#2e7d32":"#333"},children:X!==0?s.jsxs(s.Fragment,{children:[X<0?"-":"","£",Math.abs(X).toFixed(2)]}):"£0.00"},pe))),s.jsx("td",{style:{...xe.dayCell,fontWeight:700,fontSize:"0.8rem",color:qe.cf_balance<0?"#c62828":qe.cf_balance===0?"#2e7d32":"#333"},children:qe.cf_balance!==0?s.jsxs(s.Fragment,{children:[qe.cf_balance<0?"-":"","£",Math.abs(qe.cf_balance).toFixed(2)]}):"£0.00"})]})})(),s.jsx("tr",{children:s.jsx("td",{colSpan:O.dates.length+3,style:{padding:"0.5rem",textAlign:"left",borderTop:"1px solid #e0e0e0"},children:w?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("button",{onClick:()=>S(!1),style:xe.spreadCostBtnActive,children:"Cancel"}),s.jsx("span",{style:xe.selectModeHint,children:"Click an invoice in the table above to spread its cost"})]}):s.jsx("button",{onClick:()=>S(!0),style:xe.addDistributionBtn,children:"+ Add Distribution"})})})]})]})})]}),s.jsxs("div",{style:xe.section,children:[s.jsx("h3",{style:xe.sectionTitle,children:"Daily Spend Comparison"}),s.jsx("div",{style:xe.chartContainer,children:de&&s.jsx(Qre,{data:de,options:Y})})]}),s.jsx(TT,{isOpen:u,onClose:()=>{f(!1),g(null),y(null),x(null)},onSaved:()=>{I()},poId:p,defaultSupplierId:m,defaultDate:v}),s.jsx(_fe,{isOpen:_,onClose:()=>{b(!1),T(null),A(null)},onSaved:()=>{I(),r.invalidateQueries({queryKey:["cost-distributions"]})},invoiceId:C,distributionId:F,isAdmin:e==null?void 0:e.is_admin})]})}const xe={container:{padding:"1rem"},loading:{textAlign:"center",padding:"3rem",color:"#666"},error:{textAlign:"center",padding:"3rem",background:"#fff3f3",borderRadius:"8px"},retryBtn:{marginTop:"1rem",padding:"0.5rem 1rem",background:"#3498db",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},title:{margin:0,fontSize:"1.5rem",fontWeight:"bold"},weekNav:{display:"flex",gap:"0.5rem"},navBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem"},currentBtn:{padding:"0.5rem 1rem",background:"#3498db",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},weekInfo:{fontSize:"1.1rem",color:"#666",marginBottom:"1rem",display:"flex",alignItems:"center",gap:"0.5rem"},warningBadge:{background:"#f39c12",color:"white",padding:"0.2rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem"},forecastToggle:{background:"none",border:"1px solid #ddd",borderRadius:"4px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",color:"#555",fontWeight:"500"},forecastTableContainer:{overflowX:"auto",background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",marginTop:"0.5rem"},forecastTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},forecastTh:{padding:"0.6rem 0.5rem",borderBottom:"2px solid #e0e0e0",textAlign:"center",fontWeight:"bold",background:"#f5f5f5",whiteSpace:"nowrap",fontSize:"0.8rem"},forecastTr:{borderBottom:"1px solid #e0e0e0"},forecastServiceCell:{padding:"0.5rem 0.75rem",fontWeight:"600",textAlign:"left",whiteSpace:"nowrap",color:"#333"},forecastTd:{padding:"0.5rem",textAlign:"center",whiteSpace:"nowrap"},forecastTotalCol:{background:"#f0f7ff",fontWeight:"600"},fcActual:{color:"#27ae60",fontWeight:"500"},fcOtb:{color:"#2980b9",fontWeight:"500"},fcPickup:{color:"#e67e22",fontSize:"0.85rem"},fcTotal:{color:"#555",fontWeight:"600"},summaryCards:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"1rem",marginBottom:"2rem"},card:{background:"white",padding:"1rem",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",textAlign:"center"},cardLabel:{fontSize:"0.9rem",color:"#666",marginBottom:"0.5rem"},cardValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#333"},cardSubtext:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},cardOver:{background:"#ffebee",borderLeft:"4px solid #e74c3c"},cardUnder:{background:"#e8f5e9",borderLeft:"4px solid #27ae60"},section:{marginBottom:"2rem"},sectionTitle:{fontSize:"1.2rem",fontWeight:"bold",marginBottom:"1rem",color:"#333"},tableContainer:{overflowX:"auto",background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{padding:"0.75rem 0.5rem",borderBottom:"2px solid #e0e0e0",textAlign:"center",fontWeight:"bold",background:"#f5f5f5",whiteSpace:"nowrap"},supplierHeader:{textAlign:"left",minWidth:"150px"},budgetHeader:{background:"#e3f2fd"},spentHeader:{background:"#fff3e0"},remainingHeader:{background:"#e8f5e9"},statusHeader:{width:"50px"},tr:{borderBottom:"1px solid #e0e0e0"},td:{padding:"0.5rem",textAlign:"center",verticalAlign:"top"},supplierCell:{padding:"0.5rem",textAlign:"left",fontWeight:"500"},supplierPct:{fontSize:"0.75rem",color:"#888"},futureDate:{opacity:.6},invoicesCell:{display:"flex",flexDirection:"column",gap:"0.25rem",alignItems:"center"},invoiceBtn:{padding:"0.25rem 0.5rem",background:"#d4edda",border:"1px solid #28a745",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",whiteSpace:"nowrap",color:"#155724"},creditNoteBtn:{background:"#ffebee",borderColor:"#c62828",color:"#c62828"},poBtn:{padding:"0.25rem 0.5rem",background:"#e3f2fd",border:"1px dashed #42a5f5",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontStyle:"italic",color:"#1565c0",whiteSpace:"nowrap"},emptyCell:{color:"#ccc"},clickableCell:{cursor:"pointer"},budgetCell:{padding:"0.5rem",background:"#e3f2fd",fontWeight:"500"},spentCell:{padding:"0.5rem",background:"#fff3e0"},orderedHeader:{textAlign:"center"},orderedCell:{padding:"0.5rem",background:"#e3f2fd",textAlign:"center",color:"#1565c0",fontStyle:"italic",fontSize:"0.85rem"},remainingCell:{padding:"0.5rem",background:"#e8f5e9",fontWeight:"500"},overBudget:{background:"#ffebee",color:"#c62828"},statusCell:{padding:"0.5rem",textAlign:"center"},statusBadge:{display:"inline-block",width:"24px",height:"24px",borderRadius:"50%",lineHeight:"24px",textAlign:"center",fontWeight:"bold"},statusUnder:{background:"#c8e6c9",color:"#2e7d32"},statusOnTrack:{background:"#fff9c4",color:"#f57f17"},statusOver:{background:"#ffcdd2",color:"#c62828"},footerRow:{background:"#f5f5f5",fontWeight:"500"},footerLabel:{padding:"0.5rem",textAlign:"left",fontWeight:"bold",fontSize:"0.85rem"},footerTd:{padding:"0.5rem",textAlign:"center",fontSize:"0.85rem"},chartContainer:{height:"300px",background:"white",padding:"1rem",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},snapshotBtn:{padding:"0.75rem 1.5rem",background:"#3498db",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.95rem",fontWeight:"600"},snapshotInfoBar:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0.75rem",background:"#f0f7ff",borderRadius:"6px",fontSize:"0.85rem",color:"#555",marginBottom:"0.75rem",marginTop:"0.75rem"},resnapshotBtn:{background:"none",border:"1px solid #aaa",borderRadius:"4px",padding:"0.25rem 0.5rem",cursor:"pointer",fontSize:"0.8rem",color:"#666"},overrideTableContainer:{background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",marginBottom:"0.75rem",overflow:"hidden"},overrideSectionHeader:{padding:"0.5rem 0.75rem",fontSize:"0.85rem",fontWeight:"600",color:"#555",borderBottom:"1px solid #e0e0e0",background:"#fafafa"},spendInput:{width:"65px",textAlign:"center",border:"1px solid #ddd",borderRadius:"3px",padding:"3px 4px",fontSize:"0.8rem"},spendInputOverridden:{fontWeight:"bold",borderColor:"#3498db",background:"#f0f7ff"},stepperCell:{display:"flex",alignItems:"center",justifyContent:"center",gap:"4px"},stepperBtn:{width:"22px",height:"22px",border:"1px solid #ccc",borderRadius:"3px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.85rem",display:"flex",alignItems:"center",justifyContent:"center",padding:0,lineHeight:"1"},overriddenValue:{fontWeight:"bold",textDecoration:"underline"},deleteOverrideBtn:{background:"none",border:"none",color:"#e74c3c",cursor:"pointer",fontSize:"0.85rem",padding:"0 2px",lineHeight:"1"},saveOverrideBtn:{padding:"0.25rem 0.75rem",background:"#27ae60",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontWeight:"600"},discardBtn:{padding:"0.25rem 0.75rem",background:"#f0f0f0",color:"#666",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},spreadCostBtnActive:{padding:"0.5rem 1rem",background:"#e3f2fd",border:"1px solid #42a5f5",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:500,color:"#1565c0",boxShadow:"0 0 0 2px rgba(66,165,245,0.3)"},selectModeHint:{padding:"0.4rem 0.75rem",background:"#e3f2fd",borderRadius:"4px",color:"#1565c0",fontSize:"0.8rem"},invoiceBtnSelectMode:{cursor:"crosshair",boxShadow:"0 0 0 2px rgba(66,165,245,0.5)",border:"2px solid #42a5f5"},addDistributionBtn:{padding:"0.4rem 0.75rem",background:"none",border:"1px dashed #aaa",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontWeight:500,color:"#666"},distributionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.6rem 0.75rem",background:"#f5f5f5",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},distributionSummary:{fontSize:"0.8rem",color:"#666",fontWeight:400}},Au=n=>n.toISOString().split("T")[0],XP=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Au(t),end:Au(r)}},Afe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()},BK="gp-report-from-date",IK="gp-report-to-date",Tfe=()=>{const n=sessionStorage.getItem(BK),e=sessionStorage.getItem(IK);if(n&&e)return{from:n,to:e};const t=new Date;t.setDate(t.getDate()-1);const r=new Date(t);return r.setDate(t.getDate()-30),{from:Au(r),to:Au(t)}};function Ffe(){var Le,rt,$e,ce,Je,jt,ct;const{token:n}=gn(),e=Tfe(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(""),[d,c]=k.useState("custom"),[u,f]=k.useState(e.from),[p,g]=k.useState(e.to);k.useEffect(()=>{sessionStorage.setItem(BK,u),sessionStorage.setItem(IK,p)},[u,p]);const m=Afe(),[y,v]=k.useState({wastage:!1,transfer:!0,staffFood:!0,manualAdjustment:!0,disputes:!0,cdDeductions:!0,cdReallocations:!0}),x=t!==u||i!==p,w=()=>{f(t),g(i)};k.useEffect(()=>{if(a){const[Se,ot]=a.split("-").map(Number),ut=XP(Se,ot);r(ut.start),o(ut.end),f(ut.start),g(ut.end)}},[a]);const S=Se=>{r(Se),Se>i&&o(Se),l(""),c("custom")},_=Se=>{o(Se),Se{l(Se),c(Se?"month":"custom")},C=()=>{const Se=new Date;Se.setDate(Se.getDate()-1);const ot=new Date(Se);ot.setDate(Se.getDate()-30);const ut=Au(ot),Ot=Au(Se);r(ut),o(Ot),f(ut),g(Ot),l(""),c("last30")},T=()=>{const Se=new Date,ot=`${Se.getFullYear()}-${Se.getMonth()}`,ut=XP(Se.getFullYear(),Se.getMonth());r(ut.start),o(ut.end),f(ut.start),g(ut.end),l(ot),c("month")},F=()=>{const Se=new Date,ot=new Date(Se.getFullYear(),Se.getMonth()-1,1),ut=`${ot.getFullYear()}-${ot.getMonth()}`,Ot=XP(ot.getFullYear(),ot.getMonth());r(Ot.start),o(Ot.end),f(Ot.start),g(Ot.end),l(ut),c("month")},A=()=>{const Se=new Date,ot=Se.getDay(),ut=new Date(Se);ut.setDate(Se.getDate()-(ot===0?6:ot-1));const Ot=new Date;Ot.setDate(Ot.getDate()-1);const An=Au(ut),on=Au(Ot);r(An),o(on),f(An),g(on),l(""),c("week")},D=()=>{const Se=new Date,ot=Se.getDay(),ut=new Date(Se);ut.setDate(Se.getDate()-(ot===0?6:ot-1)-7);const Ot=new Date(ut);Ot.setDate(ut.getDate()+6);const An=Au(ut),on=Au(Ot);r(An),o(on),f(An),g(on),l(""),c("week")},P=()=>{if(d==="last30")return"Last 30 Days: ";if(d==="week")return"Week: ";if(d==="month"&&a){const[Se,ot]=a.split("-").map(Number);return`Month of ${new Date(Se,ot,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},{data:L,isLoading:W,error:O}=Oe({queryKey:["gp-range",u,p],queryFn:async()=>{const Se=await fetch(`/api/reports/gp/range?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!Se.ok)throw new Error("Failed to fetch GP data");return Se.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:U}=Oe({queryKey:["gp-daily",u,p],queryFn:async()=>{const Se=await fetch(`/api/reports/gp/daily?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!Se.ok)throw new Error("Failed to fetch chart data");return Se.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:M,isLoading:I}=Oe({queryKey:["gp-top-sellers",u,p],queryFn:async()=>{const Se=await fetch(`/api/reports/gp/top-sellers?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});return Se.ok?Se.json():{from_date:u,to_date:p,source:"newbook",categories:[],top_by_qty:[],top_by_revenue:[],package_favorites:[],total_charges_processed:0,total_items_aggregated:0}},staleTime:5*60*1e3,gcTime:30*60*1e3}),H=(Se,ot=!1)=>{const ut=Number(Se);return ut<0&&ot?`-£${Math.abs(ut).toFixed(2)} CR`:`£${ut.toFixed(2)}`},z=()=>{var Ai,Ks;if(!((Ai=U==null?void 0:U.data)!=null&&Ai.length))return null;const Se=500,ot=200,ut={top:20,right:20,bottom:30,left:50},Ot=Se-ut.left-ut.right,An=ot-ut.top-ut.bottom,on=U.data,Ke=Math.max(...on.map(un=>Math.max(un.net_sales,un.net_purchases)),1),Rt=un=>ut.left+un/(on.length-1||1)*Ot,vt=un=>ut.top+An-un/Ke*An,Cr=on.map((un,Fr)=>`${Fr===0?"M":"L"} ${Rt(Fr)} ${vt(un.net_sales)}`).join(" "),Qt=on.map((un,Fr)=>`${Fr===0?"M":"L"} ${Rt(Fr)} ${vt(un.net_purchases)}`).join(" "),Ci=[0,Ke/2,Ke].map(un=>({value:un,y:vt(un),label:`£${(un/1e3).toFixed(un>=1e3?0:1)}k`})),Lr=[{index:0,label:new Date(on[0].date).toLocaleDateString("en-GB",{day:"numeric",month:"short"})},{index:Math.floor(on.length/2),label:new Date((Ks=on[Math.floor(on.length/2)])==null?void 0:Ks.date).toLocaleDateString("en-GB",{day:"numeric",month:"short"})},{index:on.length-1,label:new Date(on[on.length-1].date).toLocaleDateString("en-GB",{day:"numeric",month:"short"})}],Gs=[];return on.forEach((un,Fr)=>{new Date(un.date).getDay()===1&&Fr>0&&Gs.push(Fr)}),s.jsxs("div",{style:Ee.chartContainer,children:[s.jsx("h4",{style:Ee.chartTitle,children:"Daily Sales & Purchases"}),s.jsxs("svg",{width:Se,height:ot,style:Ee.chartSvg,children:[Ci.map((un,Fr)=>s.jsxs("g",{children:[s.jsx("line",{x1:ut.left,y1:un.y,x2:Se-ut.right,y2:un.y,stroke:"#eee",strokeDasharray:"4,4"}),s.jsx("text",{x:ut.left-5,y:un.y+4,textAnchor:"end",fontSize:"10",fill:"#666",children:un.label})]},Fr)),Gs.map((un,Fr)=>s.jsx("line",{x1:Rt(un),y1:ut.top,x2:Rt(un),y2:ot-ut.bottom,stroke:"#ccc",strokeDasharray:"4,4"},`week-${Fr}`)),Lr.map((un,Fr)=>s.jsx("text",{x:Rt(un.index),y:ot-8,textAnchor:"middle",fontSize:"10",fill:"#666",children:un.label},Fr)),s.jsx("path",{d:Cr,fill:"none",stroke:"#28a745",strokeWidth:"2"}),s.jsx("path",{d:Qt,fill:"none",stroke:"#dc3545",strokeWidth:"2"})]}),s.jsxs("div",{style:Ee.chartLegend,children:[s.jsxs("span",{style:Ee.legendItem,children:[s.jsx("span",{style:{...Ee.legendColor,background:"#28a745"}})," Net Sales"]}),s.jsxs("span",{style:Ee.legendItem,children:[s.jsx("span",{style:{...Ee.legendColor,background:"#dc3545"}})," Net Purchases"]})]})]})};if(W)return s.jsx("div",{style:Ee.loading,children:"Loading GP data..."});if(O)return s.jsxs("div",{style:Ee.error,children:["Error loading GP data: ",O.message]});const{period_label:G="",net_food_sales:te=0,net_food_purchases:re=0,gross_profit:me=0,gross_profit_percent:J=0,wastage_total:ne=null,transfer_total:ye=null,staff_food_total:ke=null,manual_adjustment_total:Ye=null,disputes_total:De=null,cd_deductions_total:qe=null,cd_reallocations_total:ue=null}=L||{},Ze=me<0,ee=ne!==null&&ne>0,Z=ye!==null&&ye>0,ge=ke!==null&&ke>0,Te=Ye!==null&&Ye>0,Be=De!==null&&De>0,he=qe!==null&&qe!==0,He=ue!==null&&ue!==0,Ge=ee||Z||ge||Te||Be||he||He,ae=Number(te)||0,K=Number(re)||0,de=Number(qe)||0,Y=Number(ue)||0,Q=()=>{let Se=0;return y.cdDeductions&&he&&(Se+=de),y.cdReallocations&&He&&(Se+=Y),Se},X=()=>{let Se=0;return y.wastage&&ee&&(Se+=Number(ne)||0),y.transfer&&Z&&(Se+=Number(ye)||0),y.staffFood&&ge&&(Se+=Number(ke)||0),y.manualAdjustment&&Te&&(Se+=Number(Ye)||0),y.disputes&&Be&&(Se+=Number(De)||0),Se},pe=Q(),we=X(),Ne=K+pe,st=we>0||pe!==0,Ve=ae>0?(ae-Ne+we)/ae*100:0,Re=Se=>{v(ot=>({...ot,[Se]:!ot[Se]}))};return s.jsxs("div",{children:[s.jsx("div",{style:Ee.header,children:s.jsx("h2",{style:Ee.title,children:"Kitchen Flash Report"})}),s.jsxs("div",{style:Ee.dateControls,children:[s.jsxs("div",{style:Ee.dateRow,children:[s.jsxs("div",{style:Ee.dateField,children:[s.jsx("label",{style:Ee.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:t,onChange:Se=>S(Se.target.value),style:Ee.dateInput})]}),s.jsxs("div",{style:Ee.dateField,children:[s.jsx("label",{style:Ee.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:i,onChange:Se=>_(Se.target.value),style:Ee.dateInput})]}),s.jsxs("div",{style:Ee.dateField,children:[s.jsx("label",{style:Ee.dateLabel,children:"Month"}),s.jsxs("select",{value:a,onChange:Se=>b(Se.target.value),style:Ee.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),m.map(Se=>s.jsx("option",{value:`${Se.year}-${Se.month}`,children:Se.label},`${Se.year}-${Se.month}`))]})]})]}),s.jsxs("div",{style:Ee.presetRow,children:[s.jsx("button",{onClick:C,style:Ee.presetBtn,children:"Last 30 Days"}),s.jsx("button",{onClick:A,style:Ee.presetBtn,children:"This Week"}),s.jsx("button",{onClick:D,style:Ee.presetBtn,children:"Last Week"}),s.jsx("button",{onClick:T,style:Ee.presetBtn,children:"This Month"}),s.jsx("button",{onClick:F,style:Ee.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:w,disabled:!x,style:{...Ee.generateBtn,...x?{}:Ee.generateBtnDisabled},children:x?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:Ee.periodLabel,children:[P(),G]}),s.jsxs("div",{style:Ee.mainContent,children:[s.jsxs("div",{style:Ee.sectionContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Gross Profit Estimate"}),s.jsxs("div",{style:Ee.calculationContainer,children:[s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Net Food Sales"}),s.jsx("span",{style:Ee.calcValue,children:H(te)})]}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Net Food Purchases"}),s.jsx("span",{style:Ee.calcValue,children:H(re)})]}),s.jsx("div",{style:Ee.divider}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabelBold,children:"Gross Profit"}),s.jsx("span",{style:{...Ee.calcValueBold,...Ze?Ee.negativeValue:Ee.positiveValue},children:H(me)})]}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabelBold,children:"Gross Profit %"}),s.jsxs("span",{style:{...Ee.calcValueBold,...Ze?Ee.negativeValue:Ee.positiveValue},children:[Number(J).toFixed(1),"%"]})]}),Ge&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:Ee.wastageSection}),s.jsx("div",{style:Ee.allowancesHeader,children:"Adjustments"}),he&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.cdDeductions,onChange:()=>Re("cdDeductions")}),s.jsx("span",{children:"Distributed Deductions"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#2e7d32"},children:H(qe||0)})]}),He&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.cdReallocations,onChange:()=>Re("cdReallocations")}),s.jsx("span",{children:"Distributed Reallocations"})]}),s.jsxs("span",{style:{...Ee.calcValue,color:"#e65100"},children:["+",H(ue||0)]})]}),ee&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.wastage,onChange:()=>Re("wastage")}),s.jsx("span",{children:"Wastage"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#e74c3c"},children:H(ne||0)})]}),Z&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.transfer,onChange:()=>Re("transfer")}),s.jsx("span",{children:"Transfers"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#3498db"},children:H(ye||0)})]}),ge&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.staffFood,onChange:()=>Re("staffFood")}),s.jsx("span",{children:"Staff Food"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#9b59b6"},children:H(ke||0)})]}),Te&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.manualAdjustment,onChange:()=>Re("manualAdjustment")}),s.jsx("span",{children:"Manual Adjustments"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#34495e"},children:H(Ye||0)})]}),Be&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.disputes,onChange:()=>Re("disputes")}),s.jsx("span",{children:"Open Disputes"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#e67e22"},children:H(De||0)})]}),s.jsx("div",{style:Ee.divider}),pe!==0&&s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Adjusted Purchases"}),s.jsx("span",{style:Ee.calcValue,children:H(Ne)})]}),we>0&&s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Selected Allowances"}),s.jsx("span",{style:{...Ee.calcValue,color:"#27ae60"},children:H(we)})]}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabelBold,children:"Adjusted GP %"}),s.jsxs("span",{style:{...Ee.calcValueBold,color:st?"#27ae60":"#999"},children:[Ve.toFixed(1),"%"]})]})]})]})]}),s.jsx("div",{style:Ee.sectionContainer,children:z()})]}),s.jsxs("div",{style:Ee.breakdownRow,children:[s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Supplier Breakdown"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Supplier"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Purchases"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"%"})]})}),s.jsx("tbody",{children:(Le=L==null?void 0:L.supplier_breakdown)!=null&&Le.length?L.supplier_breakdown.map((Se,ot)=>{const ut=Se.net_purchases<0;return s.jsxs("tr",{style:ut?{background:"#d4edda"}:{},children:[s.jsxs("td",{style:Ee.tableCell,children:[Se.supplier_name,ut&&s.jsx("span",{style:{color:"#28a745",fontWeight:"bold",marginLeft:"0.5rem"},children:"(CR)"})]}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",...ut?{color:"#28a745",fontWeight:"bold"}:{}},children:H(Se.net_purchases,!0)}),s.jsxs("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:[Number(Se.percentage).toFixed(1),"%"]})]},Se.supplier_id||`unknown-${ot}`)}):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No supplier data"})})})]})]}),s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Revenue Breakdown"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"GL Account"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Revenue"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"%"})]})}),s.jsx("tbody",{children:(rt=L==null?void 0:L.gl_account_breakdown)!=null&&rt.length?L.gl_account_breakdown.map(Se=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:Se.gl_account_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:H(Se.net_revenue)}),s.jsxs("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:[Number(Se.percentage).toFixed(1),"%"]})]},Se.gl_account_id)):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No revenue data"})})})]})]})]}),I?s.jsx("div",{style:{...Ee.breakdownContainer,textAlign:"center",marginBottom:"1.5rem"},children:s.jsx("div",{style:{color:"#666",padding:"2rem"},children:"Loading top sellers..."})}):(M==null?void 0:M.source)==="sambapos"&&(($e=M==null?void 0:M.categories)==null?void 0:$e.length)>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Ee.topSellersSection,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Quantity"}),s.jsx("div",{style:Ee.categoryGrid,children:M.categories.map(Se=>s.jsxs("div",{style:Ee.categoryColumn,children:[s.jsx("h4",{style:Ee.categoryHeader,children:Se.category}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:Se.top_by_qty.length>0?Se.top_by_qty.map(ot=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:ot.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:ot.qty})]},ot.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:2,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]},Se.category))})]}),s.jsxs("div",{style:Ee.topSellersSection,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Gross Revenue"}),s.jsx("div",{style:Ee.categoryGrid,children:M.categories.map(Se=>s.jsxs("div",{style:Ee.categoryColumn,children:[s.jsx("h4",{style:Ee.categoryHeader,children:Se.category}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Gross"})]})}),s.jsx("tbody",{children:Se.top_by_revenue.length>0?Se.top_by_revenue.map(ot=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:ot.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:H(ot.revenue)})]},ot.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:2,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]},Se.category))})]})]}):(M==null?void 0:M.source)==="sambapos"&&(!(M!=null&&M.categories)||M.categories.length===0)?s.jsxs("div",{style:{...Ee.breakdownContainer,textAlign:"center",marginBottom:"1.5rem"},children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers"}),s.jsxs("p",{style:{color:"#666",margin:"2rem 0"},children:["No categories configured. ",s.jsx("a",{href:"/sambapos",style:{color:"#e94560"},children:"Configure SambaPOS categories"})," to see top sellers by category."]})]}):s.jsxs("div",{style:Ee.breakdownRow,children:[s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Quantity"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"#"}),s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Revenue"})]})}),s.jsx("tbody",{children:(ce=M==null?void 0:M.top_by_qty)!=null&&ce.length?M.top_by_qty.map((Se,ot)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Ee.tableCell,color:"#999",width:"30px"},children:ot+1}),s.jsx("td",{style:Ee.tableCell,children:Se.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:Se.qty}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:H(Se.revenue)})]},Se.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No top sellers data"})})})]})]}),s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Gross Revenue"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"#"}),s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Gross"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:(Je=M==null?void 0:M.top_by_revenue)!=null&&Je.length?M.top_by_revenue.map((Se,ot)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Ee.tableCell,color:"#999",width:"30px"},children:ot+1}),s.jsx("td",{style:Ee.tableCell,children:Se.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:H(Se.revenue)}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:Se.qty})]},Se.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No top sellers data"})})})]})]}),s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Package Guest Favorites"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"#"}),s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:(jt=M==null?void 0:M.package_favorites)!=null&&jt.length?M.package_favorites.map((Se,ot)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Ee.tableCell,color:"#999",width:"30px"},children:ot+1}),s.jsx("td",{style:Ee.tableCell,children:Se.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:Se.qty})]},Se.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No package data"})})})]})]})]}),s.jsxs("div",{style:Ee.dailyTableContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Daily Breakdown"}),s.jsx("div",{style:Ee.tableWrapper,children:s.jsxs("table",{style:Ee.dailyTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Date"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Sales"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Purchases"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Occupancy"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Lunch Covers"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Dinner Covers"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Total Covers"})]})}),s.jsx("tbody",{children:(ct=U==null?void 0:U.data)!=null&&ct.length?[...U.data].reverse().map(Se=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:new Date(Se.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:H(Se.net_sales)}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:H(Se.net_purchases)}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.occupancy??"—"}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.lunch_covers??"—"}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.dinner_covers??"—"}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.total_covers??"—"})]},Se.date)):s.jsx("tr",{children:s.jsx("td",{colSpan:7,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No daily data"})})})]})})]})]})}const Ee={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},mainContent:{display:"flex",gap:"1.5rem",flexWrap:"wrap",alignItems:"stretch"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem",flex:"1 1 auto",minWidth:"300px"},sectionTitle:{margin:"0 0 1.5rem 0",color:"#1a1a2e"},calculationContainer:{maxWidth:"400px"},calcRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 0"},calcLabel:{color:"#555",fontSize:"1rem"},calcValue:{fontSize:"1rem",fontFamily:"monospace"},calcLabelBold:{color:"#1a1a2e",fontSize:"1.1rem",fontWeight:"bold"},calcValueBold:{fontSize:"1.2rem",fontWeight:"bold",fontFamily:"monospace"},divider:{borderTop:"2px solid #dee2e6",margin:"0.5rem 0"},wastageSection:{borderTop:"1px dashed #e67e22",margin:"0.75rem 0 0.5rem 0"},allowancesHeader:{fontSize:"0.9rem",fontWeight:600,color:"#666",marginBottom:"0.5rem",textTransform:"uppercase",letterSpacing:"0.5px"},allowanceRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.4rem 0"},allowanceCheckbox:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer",fontSize:"0.95rem",color:"#444"},positiveValue:{color:"#155724"},negativeValue:{color:"#dc3545"},chartContainer:{width:"100%"},chartTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1rem",fontWeight:600},chartSvg:{display:"block",maxWidth:"100%"},chartLegend:{display:"flex",gap:"1.5rem",marginTop:"0.75rem",justifyContent:"center"},legendItem:{display:"flex",alignItems:"center",gap:"0.4rem",fontSize:"0.85rem",color:"#555"},legendColor:{width:"12px",height:"12px",borderRadius:"2px",display:"inline-block"},breakdownRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1.5rem"},breakdownContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",flex:"1 1 300px",minWidth:"280px"},breakdownTable:{width:"100%",borderCollapse:"collapse"},tableHeader:{textAlign:"left",padding:"0.75rem 0.5rem",borderBottom:"2px solid #dee2e6",color:"#1a1a2e",fontWeight:600,fontSize:"0.85rem"},tableCell:{padding:"0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},dailyTableContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem"},tableWrapper:{overflowX:"auto"},dailyTable:{width:"100%",borderCollapse:"collapse",minWidth:"700px"},topSellersSection:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1.5rem"},categoryGrid:{display:"flex",gap:"1rem",flexWrap:"wrap"},categoryColumn:{flex:"1 1 180px",minWidth:"160px",maxWidth:"250px"},categoryHeader:{margin:"0 0 0.75rem 0",padding:"0.5rem 0.75rem",background:"#f8f9fa",borderRadius:"6px",fontSize:"0.95rem",fontWeight:600,color:"#1a1a2e",borderLeft:"3px solid #e94560"}},Tu=n=>n.toISOString().split("T")[0],YP=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Tu(t),end:Tu(r)}},UN=n=>n?n.split(` `)[0].trim():"",Dfe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()},MK="purchases-report-from-date",zK="purchases-report-to-date",Efe=()=>{const n=sessionStorage.getItem(MK),e=sessionStorage.getItem(zK);if(n&&e)return{from:n,to:e};const t=new Date;t.setDate(t.getDate()-1);const r=new Date(t);return r.setDate(t.getDate()-30),{from:Tu(r),to:Tu(t)}},HN=["#e94560","#0ea5e9","#22c55e","#f59e0b","#8b5cf6","#ec4899","#14b8a6","#f97316","#6366f1","#84cc16"];function Pfe(){var G,te,re,me;const{token:n}=gn(),e=Efe(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(""),[d,c]=k.useState("custom"),[u,f]=k.useState(e.from),[p,g]=k.useState(e.to),[m,y]=k.useState(null);k.useEffect(()=>{sessionStorage.setItem(MK,u),sessionStorage.setItem(zK,p)},[u,p]);const v=Dfe(),x=t!==u||i!==p,w=()=>{f(t),g(i)};k.useEffect(()=>{if(a){const[J,ne]=a.split("-").map(Number),ye=YP(J,ne);r(ye.start),o(ye.end),f(ye.start),g(ye.end)}},[a]);const S=J=>{r(J),J>i&&o(J),l(""),c("custom")},_=J=>{o(J),J{l(J),c(J?"month":"custom")},C=()=>{const J=new Date;J.setDate(J.getDate()-1);const ne=new Date(J);ne.setDate(J.getDate()-30);const ye=Tu(ne),ke=Tu(J);r(ye),o(ke),f(ye),g(ke),l(""),c("last30")},T=()=>{const J=new Date,ne=`${J.getFullYear()}-${J.getMonth()}`,ye=YP(J.getFullYear(),J.getMonth());r(ye.start),o(ye.end),f(ye.start),g(ye.end),l(ne),c("month")},F=()=>{const J=new Date,ne=new Date(J.getFullYear(),J.getMonth()-1,1),ye=`${ne.getFullYear()}-${ne.getMonth()}`,ke=YP(ne.getFullYear(),ne.getMonth());r(ke.start),o(ke.end),f(ke.start),g(ke.end),l(ye),c("month")},A=()=>{const J=new Date,ne=J.getDay(),ye=new Date(J);ye.setDate(J.getDate()-(ne===0?6:ne-1));const ke=new Date;ke.setDate(ke.getDate()-1);const Ye=Tu(ye),De=Tu(ke);r(Ye),o(De),f(Ye),g(De),l(""),c("week")},D=()=>{const J=new Date,ne=J.getDay(),ye=new Date(J);ye.setDate(J.getDate()-(ne===0?6:ne-1)-7);const ke=new Date(ye);ke.setDate(ye.getDate()+6);const Ye=Tu(ye),De=Tu(ke);r(Ye),o(De),f(Ye),g(De),l(""),c("week")},P=()=>{if(d==="last30")return"Last 30 Days: ";if(d==="week")return"Week: ";if(d==="month"&&a){const[J,ne]=a.split("-").map(Number);return`Month of ${new Date(J,ne,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},{data:L,isLoading:W,error:O}=Oe({queryKey:["purchases-summary",u,p],queryFn:async()=>{const J=await fetch(`/api/reports/purchases/summary?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!J.ok)throw new Error("Failed to fetch purchases summary");return J.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:U}=Oe({queryKey:["purchases-daily-supplier",u,p],queryFn:async()=>{const J=await fetch(`/api/reports/purchases/daily-by-supplier?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!J.ok)throw new Error("Failed to fetch chart data");return J.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:M}=Oe({queryKey:["purchases-top-items",u,p,m],queryFn:async()=>{let J=`/api/reports/purchases/top-items?from_date=${u}&to_date=${p}`;m!==null&&(J+=`&supplier_id=${m}`);const ne=await fetch(J,{headers:{Authorization:`Bearer ${n}`}});if(!ne.ok)throw new Error("Failed to fetch top items");return ne.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),I=(J,ne=!1)=>{const ye=Number(J);return ye<0&&ne?`-£${Math.abs(ye).toFixed(2)} CR`:`£${ye.toFixed(2)}`},H=J=>{const ne=new Date(J),ye=ne.getDay(),ke=ne.getDate()-ye+(ye===0?-6:1);return new Date(ne.setDate(ke)).toISOString().split("T")[0]},z=()=>{var He,Ge;if(!((He=U==null?void 0:U.data)!=null&&He.length)||!((Ge=U==null?void 0:U.suppliers)!=null&&Ge.length))return s.jsx("div",{style:Et.noData,children:"No chart data available"});const J=650,ne=280,ye={top:20,right:20,bottom:40,left:60},ke=J-ye.left-ye.right,Ye=ne-ye.top-ye.bottom,De=U.suppliers,qe={};De.forEach((ae,K)=>{qe[ae]=HN[K%HN.length]});const ue={};U.data.forEach(ae=>{const K=H(ae.date);ue[K]||(ue[K]={},De.forEach(de=>{ue[K][de]=0})),ue[K][ae.supplier_name]=(ue[K][ae.supplier_name]||0)+(Number(ae.net_purchases)||0)});const Ze=Object.keys(ue).sort();if(Ze.length===0)return s.jsx("div",{style:Et.noData,children:"No chart data available"});let ee=1;Ze.forEach(ae=>{De.forEach(K=>{const de=ue[ae][K]||0;de>ee&&(ee=de)})});const Z=ke/Ze.length,ge=Z*.8,Te=Math.min(ge/De.length,25),Be=ae=>ye.top+Ye-ae/ee*Ye,he=[0,ee/2,ee].map(ae=>({value:ae,y:Be(ae),label:`£${(Number(ae)/1e3).toFixed(Number(ae)>=1e3?0:1)}k`}));return s.jsxs("div",{style:Et.chartContainer,children:[s.jsx("h4",{style:Et.chartTitle,children:"Weekly Purchases by Supplier"}),s.jsxs("svg",{width:J,height:ne,style:Et.chartSvg,children:[he.map((ae,K)=>s.jsxs("g",{children:[s.jsx("line",{x1:ye.left,y1:ae.y,x2:J-ye.right,y2:ae.y,stroke:"#eee",strokeDasharray:"4,4"}),s.jsx("text",{x:ye.left-5,y:ae.y+4,textAnchor:"end",fontSize:"10",fill:"#666",children:ae.label})]},K)),Ze.map((ae,K)=>{const de=ye.left+(K+.5)*Z,Y=de-De.length*Te/2;return s.jsxs("g",{children:[s.jsx("text",{x:de,y:ne-8,textAnchor:"middle",fontSize:"9",fill:"#666",children:new Date(ae).toLocaleDateString("en-GB",{day:"numeric",month:"short"})}),De.map((Q,X)=>{const pe=ue[ae][Q]||0;if(pe<=0)return null;const we=pe/ee*Ye,Ne=Y+X*Te;return s.jsx("rect",{x:Ne,y:ye.top+Ye-we,width:Te-1,height:we,fill:qe[Q]},`${ae}-${Q}`)})]},ae)})]}),s.jsx("div",{style:Et.chartLegend,children:De.map(ae=>s.jsxs("span",{style:Et.legendItem,children:[s.jsx("span",{style:{...Et.legendColor,background:qe[ae]}}),ae]},ae))})]})};return W?s.jsx("div",{style:Et.loading,children:"Loading purchases data..."}):O?s.jsxs("div",{style:Et.error,children:["Error loading purchases data: ",O.message]}):s.jsxs("div",{children:[s.jsx("div",{style:Et.header,children:s.jsx("h2",{style:Et.title,children:"Purchases Report"})}),s.jsxs("div",{style:Et.dateControls,children:[s.jsxs("div",{style:Et.dateRow,children:[s.jsxs("div",{style:Et.dateField,children:[s.jsx("label",{style:Et.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:t,onChange:J=>S(J.target.value),style:Et.dateInput})]}),s.jsxs("div",{style:Et.dateField,children:[s.jsx("label",{style:Et.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:i,onChange:J=>_(J.target.value),style:Et.dateInput})]}),s.jsxs("div",{style:Et.dateField,children:[s.jsx("label",{style:Et.dateLabel,children:"Month"}),s.jsxs("select",{value:a,onChange:J=>b(J.target.value),style:Et.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),v.map(J=>s.jsx("option",{value:`${J.year}-${J.month}`,children:J.label},`${J.year}-${J.month}`))]})]})]}),s.jsxs("div",{style:Et.presetRow,children:[s.jsx("button",{onClick:C,style:Et.presetBtn,children:"Last 30 Days"}),s.jsx("button",{onClick:A,style:Et.presetBtn,children:"This Week"}),s.jsx("button",{onClick:D,style:Et.presetBtn,children:"Last Week"}),s.jsx("button",{onClick:T,style:Et.presetBtn,children:"This Month"}),s.jsx("button",{onClick:F,style:Et.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:w,disabled:!x,style:{...Et.generateBtn,...x?{}:Et.generateBtnDisabled},children:x?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:Et.periodLabel,children:[P(),L==null?void 0:L.period_label]}),s.jsxs("div",{style:Et.mainContent,children:[s.jsxs("div",{style:Et.sectionContainer,children:[s.jsx("h3",{style:Et.sectionTitle,children:"Supplier Breakdown"}),s.jsxs("div",{style:Et.totalRow,children:[s.jsx("span",{children:"Total Purchases:"}),s.jsx("span",{style:{...Et.totalValue,...((L==null?void 0:L.total_purchases)||0)<0?{color:"#28a745"}:{}},children:I((L==null?void 0:L.total_purchases)||0,!0)})]}),s.jsxs("table",{style:Et.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Et.tableHeader,children:"Supplier"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Net Purchases"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"%"})]})}),s.jsx("tbody",{children:(G=L==null?void 0:L.supplier_breakdown)!=null&&G.length?L.supplier_breakdown.map((J,ne)=>{const ye=J.net_purchases<0;return s.jsxs("tr",{style:ye?{background:"#d4edda"}:{},children:[s.jsxs("td",{style:Et.tableCell,children:[J.supplier_name,ye&&s.jsx("span",{style:{color:"#28a745",fontWeight:"bold",marginLeft:"0.5rem"},children:"(CR)"})]}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",...ye?{color:"#28a745",fontWeight:"bold"}:{}},children:I(J.net_purchases,!0)}),s.jsxs("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace"},children:[Number(J.percentage).toFixed(1),"%"]})]},J.supplier_id||`unknown-${ne}`)}):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Et.tableCell,textAlign:"center",color:"#999"},children:"No supplier data"})})})]})]}),s.jsx("div",{style:Et.sectionContainer,children:z()})]}),s.jsxs("div",{style:Et.topItemsFilterRow,children:[s.jsx("span",{style:Et.filterLabel,children:"Filter by Supplier:"}),s.jsxs("select",{value:m===null?"":m,onChange:J=>y(J.target.value===""?null:Number(J.target.value)),style:Et.supplierSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),(te=L==null?void 0:L.supplier_breakdown)==null?void 0:te.map(J=>s.jsx("option",{value:J.supplier_id??"",children:J.supplier_name},J.supplier_id??"unknown"))]})]}),s.jsxs("div",{style:Et.breakdownRow,children:[s.jsxs("div",{style:Et.breakdownContainer,children:[s.jsx("h3",{style:Et.sectionTitle,children:"Top 10 Line Items by Quantity"}),s.jsxs("table",{style:Et.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Et.tableHeader,children:"#"}),s.jsx("th",{style:Et.tableHeader,children:"Item"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Value"})]})}),s.jsx("tbody",{children:(re=M==null?void 0:M.top_by_quantity)!=null&&re.length?M.top_by_quantity.map((J,ne)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Et.tableCell,color:"#999",width:"30px"},children:ne+1}),s.jsx("td",{style:Et.tableCell,children:UN(J.description)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:Number(J.total_quantity).toFixed(1)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:I(J.total_value)})]},`qty-${ne}`)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Et.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]}),s.jsxs("div",{style:Et.breakdownContainer,children:[s.jsx("h3",{style:Et.sectionTitle,children:"Top 10 Line Items by Value"}),s.jsxs("table",{style:Et.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Et.tableHeader,children:"#"}),s.jsx("th",{style:Et.tableHeader,children:"Item"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Value"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:(me=M==null?void 0:M.top_by_value)!=null&&me.length?M.top_by_value.map((J,ne)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Et.tableCell,color:"#999",width:"30px"},children:ne+1}),s.jsx("td",{style:Et.tableCell,children:UN(J.description)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:I(J.total_value)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:Number(J.total_quantity).toFixed(1)})]},`val-${ne}`)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Et.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]})]})]})}const Et={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},noData:{padding:"2rem",textAlign:"center",color:"#999"},header:{marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},mainContent:{display:"flex",gap:"1.5rem",flexWrap:"wrap",alignItems:"stretch"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem",flex:"1 1 auto",minWidth:"300px"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e"},totalRow:{display:"flex",justifyContent:"space-between",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",marginBottom:"1rem",fontWeight:600},totalValue:{fontFamily:"monospace",color:"#e94560"},breakdownTable:{width:"100%",borderCollapse:"collapse"},tableHeader:{textAlign:"left",padding:"0.75rem 0.5rem",borderBottom:"2px solid #dee2e6",color:"#1a1a2e",fontWeight:600,fontSize:"0.85rem"},tableCell:{padding:"0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},chartContainer:{width:"100%"},chartTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1rem",fontWeight:600},chartSvg:{display:"block",maxWidth:"100%"},chartLegend:{display:"flex",gap:"0.5rem 1rem",marginTop:"0.75rem",flexWrap:"wrap",justifyContent:"center",padding:"0.25rem",maxWidth:"450px",margin:"0.75rem auto 0"},legendItem:{display:"flex",alignItems:"center",gap:"0.25rem",fontSize:"0.7rem",color:"#555",whiteSpace:"nowrap"},legendColor:{width:"10px",height:"10px",borderRadius:"2px",display:"inline-block",flexShrink:0},breakdownRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1.5rem"},breakdownContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",flex:"1 1 300px",minWidth:"280px"},topItemsFilterRow:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem",padding:"0.75rem 1rem",background:"white",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},filterLabel:{fontSize:"0.9rem",color:"#555",fontWeight:500},supplierSelect:{padding:"0.5rem 0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.9rem",minWidth:"200px",cursor:"pointer"}},Fu=n=>n.toISOString().split("T")[0],QP=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Fu(t),end:Fu(r)}},Rfe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()},OK="allowances-report-from-date",LK="allowances-report-to-date",Bfe=()=>{const n=sessionStorage.getItem(OK),e=sessionStorage.getItem(LK);if(n&&e)return{from:n,to:e};const t=new Date;t.setDate(t.getDate()-1);const r=new Date(t);return r.setDate(t.getDate()-30),{from:Fu(r),to:Fu(t)}},sd={wastage:"#e74c3c",transfer:"#3498db",staff_food:"#9b59b6",manual_adjustment:"#34495e"};function Ife(){var H;const{token:n}=gn(),e=Bfe(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(""),[d,c]=k.useState("custom"),[u,f]=k.useState(e.from),[p,g]=k.useState(e.to);k.useEffect(()=>{sessionStorage.setItem(OK,u),sessionStorage.setItem(LK,p)},[u,p]);const m=Rfe(),y=t!==u||i!==p,v=()=>{f(t),g(i)};k.useEffect(()=>{if(a){const[z,G]=a.split("-").map(Number),te=QP(z,G);r(te.start),o(te.end),f(te.start),g(te.end)}},[a]);const x=z=>{r(z),z>i&&o(z),l(""),c("custom")},w=z=>{o(z),z{l(z),c(z?"month":"custom")},_=()=>{const z=new Date;z.setDate(z.getDate()-1);const G=new Date(z);G.setDate(z.getDate()-30);const te=Fu(G),re=Fu(z);r(te),o(re),f(te),g(re),l(""),c("last30")},b=()=>{const z=new Date,G=`${z.getFullYear()}-${z.getMonth()}`,te=QP(z.getFullYear(),z.getMonth());r(te.start),o(te.end),f(te.start),g(te.end),l(G),c("month")},C=()=>{const z=new Date,G=new Date(z.getFullYear(),z.getMonth()-1,1),te=`${G.getFullYear()}-${G.getMonth()}`,re=QP(G.getFullYear(),G.getMonth());r(re.start),o(re.end),f(re.start),g(re.end),l(te),c("month")},T=()=>{const z=new Date,G=z.getDay(),te=new Date(z);te.setDate(z.getDate()-(G===0?6:G-1));const re=new Date;re.setDate(re.getDate()-1);const me=Fu(te),J=Fu(re);r(me),o(J),f(me),g(J),l(""),c("week")},F=()=>{const z=new Date,G=z.getDay(),te=new Date(z);te.setDate(z.getDate()-(G===0?6:G-1)-7);const re=new Date(te);re.setDate(te.getDate()+6);const me=Fu(te),J=Fu(re);r(me),o(J),f(me),g(J),l(""),c("week")},A=()=>{if(d==="last30")return"Last 30 Days: ";if(d==="week")return"Week: ";if(d==="month"&&a){const[z,G]=a.split("-").map(Number);return`Month of ${new Date(z,G,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},{data:D,isLoading:P,error:L}=Oe({queryKey:["allowances-summary",u,p],queryFn:async()=>{const z=await fetch(`/api/reports/allowances/summary?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch allowances summary");return z.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:W}=Oe({queryKey:["allowances-daily",u,p],queryFn:async()=>{const z=await fetch(`/api/reports/allowances/daily?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch chart data");return z.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:O}=Oe({queryKey:["disputes-period-summary",u,p],queryFn:async()=>{const z=await fetch(`/api/reports/disputes/period-summary?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch disputes summary");return z.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),U=z=>`£${Number(z).toFixed(2)}`,M=z=>{const G=new Date(z),te=G.getDay(),re=G.getDate()-te+(te===0?-6:1);return new Date(G.setDate(re)).toISOString().split("T")[0]},I=()=>{var ee;if(!((ee=W==null?void 0:W.data)!=null&&ee.length))return s.jsx("div",{style:Bt.noData,children:"No chart data available"});const z=550,G=250,te={top:20,right:20,bottom:40,left:60},re=z-te.left-te.right,me=G-te.top-te.bottom,J=[{key:"wastage",color:sd.wastage,label:"Wastage"},{key:"transfer",color:sd.transfer,label:"Transfers"},{key:"staff_food",color:sd.staff_food,label:"Staff Food"},{key:"manual_adjustment",color:sd.manual_adjustment,label:"Manual Adj."}],ne={};W.data.forEach(Z=>{const ge=M(Z.date);ne[ge]||(ne[ge]={wastage:0,transfer:0,staff_food:0,manual_adjustment:0}),ne[ge].wastage+=Number(Z.wastage)||0,ne[ge].transfer+=Number(Z.transfer)||0,ne[ge].staff_food+=Number(Z.staff_food)||0,ne[ge].manual_adjustment+=Number(Z.manual_adjustment)||0});const ye=Object.keys(ne).sort();if(ye.length===0)return s.jsx("div",{style:Bt.noData,children:"No chart data available"});let ke=1;ye.forEach(Z=>{J.forEach(ge=>{const Te=ne[Z][ge.key]||0;Te>ke&&(ke=Te)})});const Ye=re/ye.length,De=Ye*.8,qe=Math.min(De/J.length,25),ue=Z=>te.top+me-Z/ke*me,Ze=[0,ke/2,ke].map(Z=>({value:Z,y:ue(Z),label:`£${Number(Z).toFixed(0)}`}));return s.jsxs("div",{style:Bt.chartContainer,children:[s.jsx("h4",{style:Bt.chartTitle,children:"Weekly Allowances"}),s.jsxs("svg",{width:z,height:G,style:Bt.chartSvg,children:[Ze.map((Z,ge)=>s.jsxs("g",{children:[s.jsx("line",{x1:te.left,y1:Z.y,x2:z-te.right,y2:Z.y,stroke:"#eee",strokeDasharray:"4,4"}),s.jsx("text",{x:te.left-5,y:Z.y+4,textAnchor:"end",fontSize:"10",fill:"#666",children:Z.label})]},ge)),ye.map((Z,ge)=>{const Te=te.left+(ge+.5)*Ye,Be=Te-J.length*qe/2;return s.jsxs("g",{children:[s.jsx("text",{x:Te,y:G-8,textAnchor:"middle",fontSize:"9",fill:"#666",children:new Date(Z).toLocaleDateString("en-GB",{day:"numeric",month:"short"})}),J.map((he,He)=>{const Ge=ne[Z][he.key]||0;if(Ge<=0)return null;const ae=Ge/ke*me,K=Be+He*qe;return s.jsx("rect",{x:K,y:te.top+me-ae,width:qe-1,height:ae,fill:he.color},`${Z}-${he.key}`)})]},Z)})]}),s.jsx("div",{style:Bt.chartLegend,children:J.map(({key:Z,color:ge,label:Te})=>s.jsxs("span",{style:Bt.legendItem,children:[s.jsx("span",{style:{...Bt.legendColor,background:ge}}),Te]},Z))})]})};return P?s.jsx("div",{style:Bt.loading,children:"Loading allowances data..."}):L?s.jsxs("div",{style:Bt.error,children:["Error loading allowances data: ",L.message]}):s.jsxs("div",{children:[s.jsx("div",{style:Bt.header,children:s.jsx("h2",{style:Bt.title,children:"Allowances Report"})}),s.jsxs("div",{style:Bt.dateControls,children:[s.jsxs("div",{style:Bt.dateRow,children:[s.jsxs("div",{style:Bt.dateField,children:[s.jsx("label",{style:Bt.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:t,onChange:z=>x(z.target.value),style:Bt.dateInput})]}),s.jsxs("div",{style:Bt.dateField,children:[s.jsx("label",{style:Bt.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:i,onChange:z=>w(z.target.value),style:Bt.dateInput})]}),s.jsxs("div",{style:Bt.dateField,children:[s.jsx("label",{style:Bt.dateLabel,children:"Month"}),s.jsxs("select",{value:a,onChange:z=>S(z.target.value),style:Bt.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),m.map(z=>s.jsx("option",{value:`${z.year}-${z.month}`,children:z.label},`${z.year}-${z.month}`))]})]})]}),s.jsxs("div",{style:Bt.presetRow,children:[s.jsx("button",{onClick:_,style:Bt.presetBtn,children:"Last 30 Days"}),s.jsx("button",{onClick:T,style:Bt.presetBtn,children:"This Week"}),s.jsx("button",{onClick:F,style:Bt.presetBtn,children:"Last Week"}),s.jsx("button",{onClick:b,style:Bt.presetBtn,children:"This Month"}),s.jsx("button",{onClick:C,style:Bt.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:v,disabled:!y,style:{...Bt.generateBtn,...y?{}:Bt.generateBtnDisabled},children:y?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:Bt.periodLabel,children:[A(),D==null?void 0:D.period_label]}),s.jsxs("div",{style:Bt.mainContent,children:[s.jsxs("div",{style:Bt.sectionContainer,children:[s.jsx("h3",{style:Bt.sectionTitle,children:"Allowances Breakdown"}),s.jsxs("table",{style:Bt.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Bt.tableHeader,children:"Type"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Entries"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Total"})]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.wastage}}),"Wastage"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.wastage_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.wastage},children:U((D==null?void 0:D.wastage_total)||0)})]}),s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.transfer}}),"Transfers"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.transfer_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.transfer},children:U((D==null?void 0:D.transfer_total)||0)})]}),s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.staff_food}}),"Staff Food"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.staff_food_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.staff_food},children:U((D==null?void 0:D.staff_food_total)||0)})]}),s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.manual_adjustment}}),"Manual Adjustments"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.manual_adjustment_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.manual_adjustment},children:U((D==null?void 0:D.manual_adjustment_total)||0)})]})]}),s.jsx("tfoot",{children:s.jsxs("tr",{style:{borderTop:"2px solid #dee2e6"},children:[s.jsx("td",{style:{...Bt.tableCell,fontWeight:"bold"},children:"Total"}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:((D==null?void 0:D.wastage_count)||0)+((D==null?void 0:D.transfer_count)||0)+((D==null?void 0:D.staff_food_count)||0)+((D==null?void 0:D.manual_adjustment_count)||0)}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold",color:"#27ae60"},children:U((D==null?void 0:D.total_allowances)||0)})]})})]})]}),s.jsx("div",{style:Bt.sectionContainer,children:I()})]}),s.jsxs("div",{style:Bt.disputesSection,children:[s.jsx("h3",{style:Bt.sectionTitle,children:"Disputes Summary"}),s.jsx("p",{style:Bt.disputesSubtitle,children:"Cases opened in selected period (by invoice date)"}),s.jsxs("table",{style:Bt.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Bt.tableHeader,children:"Status"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Count"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Difference Value"})]})}),s.jsx("tbody",{children:((H=O==null?void 0:O.rows)==null?void 0:H.map((z,G)=>s.jsxs("tr",{style:z.label==="Total Cases"?{background:"#f8f9fa"}:{},children:[s.jsx("td",{style:{...Bt.tableCell,fontWeight:z.label==="Total Cases"?"bold":"normal"},children:z.label}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:z.label==="Total Cases"?"bold":"normal"},children:z.count}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:z.label==="Total Cases"?"bold":"normal",color:z.label==="Resolved"?"#27ae60":z.label==="Still Open"?"#e67e22":void 0},children:U(z.difference_value)})]},G)))||s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Bt.tableCell,textAlign:"center",color:"#999"},children:"No disputes data"})})})]})]})]})}const Bt={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},noData:{padding:"2rem",textAlign:"center",color:"#999"},header:{marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},mainContent:{display:"flex",gap:"1.5rem",flexWrap:"wrap",alignItems:"stretch"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem",flex:"1 1 auto",minWidth:"300px"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e"},breakdownTable:{width:"100%",borderCollapse:"collapse"},tableHeader:{textAlign:"left",padding:"0.75rem 0.5rem",borderBottom:"2px solid #dee2e6",color:"#1a1a2e",fontWeight:600,fontSize:"0.85rem"},tableCell:{padding:"0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},typeDot:{display:"inline-block",width:"10px",height:"10px",borderRadius:"50%",marginRight:"8px"},chartContainer:{width:"100%"},chartTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1rem",fontWeight:600},chartSvg:{display:"block",maxWidth:"100%"},chartLegend:{display:"flex",gap:"0.5rem 0.75rem",marginTop:"0.5rem",flexWrap:"wrap",justifyContent:"center",maxHeight:"60px",overflowY:"auto",padding:"0.25rem"},legendItem:{display:"flex",alignItems:"center",gap:"0.25rem",fontSize:"0.7rem",color:"#555",whiteSpace:"nowrap"},legendColor:{width:"10px",height:"10px",borderRadius:"2px",display:"inline-block",flexShrink:0},disputesSection:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem"},disputesSubtitle:{color:"#666",fontSize:"0.85rem",margin:"0 0 1rem 0"}};function Mfe(){const{token:n}=gn(),e=go(),t=pi(),r=new Date().toISOString().slice(0,10),i=new Date(Date.now()-7*864e5).toISOString().slice(0,10),[o,a]=k.useState(i),[l,d]=k.useState(r),[c,u]=k.useState(!1),[f,p]=k.useState(i),[g,m]=k.useState(r),[y,v]=k.useState(new Set),[x,w]=k.useState(null),[S,_]=k.useState(""),{data:b,isLoading:C,error:T}=Oe({queryKey:["sales-gp",f,g],queryFn:async()=>{const U=await fetch(`/api/reports/sales-gp?from_date=${f}&to_date=${g}`,{headers:{Authorization:`Bearer ${n}`}});if(!U.ok){const M=await U.json().catch(()=>({detail:"Request failed"}));throw new Error(M.detail||"Request failed")}return U.json()},enabled:!!n&&c}),{data:F}=Oe({queryKey:["recipes-for-mapping",S],queryFn:async()=>{const U=`/api/recipes?recipe_type=dish${S?`&search=${encodeURIComponent(S)}`:""}`;return(await fetch(U,{headers:{Authorization:`Bearer ${n}`}})).json()},enabled:!!n&&!!x}),A=Ue({mutationFn:async({recipeId:U,menuItemName:M,portionName:I})=>{if(!(await fetch(`/api/recipes/${U}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({kds_menu_item_name:M,sambapos_portion_name:I==="Normal"?null:I})})).ok)throw new Error("Failed to update recipe")},onSuccess:()=>{w(null),_(""),t.invalidateQueries({queryKey:["sales-gp"]})}}),D=()=>{p(o),m(l),u(!0)},P=U=>{v(M=>{const I=new Set(M);return I.has(U)?I.delete(U):I.add(U),I})},L=U=>Number(U).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2}),W=U=>U!=null?`${Number(U).toFixed(1)}%`:"—",O=U=>U==null?"#888":U>=70?"#16a34a":U>=60?"#ca8a04":"#dc2626";return s.jsxs("div",{style:Ct.container,children:[s.jsx("h2",{style:Ct.pageTitle,children:"Sales GP% Report"}),s.jsxs("div",{style:Ct.dateBar,children:[s.jsxs("div",{style:Ct.dateGroup,children:[s.jsx("label",{style:Ct.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:o,onChange:U=>a(U.target.value),style:Ct.dateInput})]}),s.jsxs("div",{style:Ct.dateGroup,children:[s.jsx("label",{style:Ct.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:l,onChange:U=>d(U.target.value),style:Ct.dateInput})]}),s.jsx("button",{onClick:D,style:Ct.generateBtn,children:"Generate"})]}),C&&s.jsx("div",{style:Ct.loading,children:"Loading sales data from SambaPOS..."}),T&&s.jsx("div",{style:Ct.error,children:T.message}),b&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Ct.summaryBanner,children:[s.jsxs("div",{style:Ct.summaryMain,children:[s.jsx("div",{style:Ct.summaryLabel,children:"Estimated Sales GP%"}),s.jsx("div",{style:{...Ct.summaryValue,color:O(b.mapped_gp_percent)},children:W(b.mapped_gp_percent)}),s.jsx("div",{style:Ct.summarySubtext,children:"mapped items only"})]}),s.jsxs("div",{style:Ct.summaryStats,children:[s.jsxs("div",{style:Ct.statBox,children:[s.jsx("div",{style:Ct.statLabel,children:"Mapped Revenue"}),s.jsxs("div",{style:Ct.statValue,children:["£",L(b.mapped_revenue_net)]})]}),s.jsxs("div",{style:Ct.statBox,children:[s.jsx("div",{style:Ct.statLabel,children:"Mapped Cost"}),s.jsxs("div",{style:Ct.statValue,children:["£",L(b.mapped_total_cost)]})]}),s.jsxs("div",{style:Ct.statBox,children:[s.jsx("div",{style:Ct.statLabel,children:"Total Revenue"}),s.jsxs("div",{style:Ct.statValue,children:["£",L(b.total_all_revenue_net)]})]})]}),s.jsxs("div",{style:Ct.coverageSection,children:[s.jsxs("div",{style:Ct.coverageLabel,children:["Coverage: ",Number(b.mapped_revenue_percent).toFixed(1),"% of food sales revenue is costed",s.jsxs("span",{style:{color:"#888",marginLeft:"0.5rem"},children:["(",b.mapped_item_count," mapped, ",b.unmapped_item_count," unmapped)"]})]}),s.jsx("div",{style:Ct.coverageBarBg,children:s.jsx("div",{style:{...Ct.coverageBarFill,width:`${Math.min(Number(b.mapped_revenue_percent),100)}%`}})})]})]}),b.courses.map(U=>s.jsxs("div",{style:Ct.courseSection,children:[s.jsxs("div",{style:Ct.courseHeader,onClick:()=>P(U.course_name),children:[s.jsxs("div",{style:Ct.courseTitle,children:[s.jsx("span",{style:Ct.collapseIcon,children:y.has(U.course_name)?"▸":"▾"}),U.course_name]}),s.jsxs("div",{style:Ct.courseStats,children:[s.jsxs("span",{style:{marginRight:"1.5rem"},children:["Revenue: £",L(U.course_revenue)]}),s.jsxs("span",{style:{marginRight:"1.5rem"},children:["Cost: £",L(U.course_cost)]}),s.jsxs("span",{style:{fontWeight:700,color:O(U.course_gp_percent)},children:["GP: ",W(U.course_gp_percent)]})]})]}),!y.has(U.course_name)&&s.jsxs("table",{style:Ct.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ct.th,children:"Item"}),s.jsx("th",{style:Ct.th,children:"Portion"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Net Revenue"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Cost/Portion"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Total Cost"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"GP%"})]})}),s.jsx("tbody",{children:U.items.map((M,I)=>s.jsxs("tr",{style:Ct.tr,children:[s.jsx("td",{style:Ct.td,children:M.recipe_id?s.jsx("span",{title:`Recipe: ${M.recipe_name}`,onClick:()=>e(`/dishes/${M.recipe_id}`),style:{cursor:"pointer",color:"#3b82f6",textDecoration:"underline dotted",textUnderlineOffset:"3px"},children:M.menu_item_name}):M.menu_item_name}),s.jsx("td",{style:{...Ct.td,color:M.portion_name==="Normal"?"#ccc":"#555"},children:M.portion_name==="Normal"?"—":M.portion_name}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:[M.total_qty,M.dbb_qty>0&&s.jsxs("span",{title:`${M.dbb_qty} of ${M.total_qty} sold as DBB package — original price used for GP calculation`,style:Ct.dbbBadge,children:[M.dbb_qty," DBB"]})]}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:["£",L(M.total_revenue_net)]}),s.jsx("td",{style:{...Ct.td,textAlign:"right"},children:M.cost_per_portion!=null?`£${L(M.cost_per_portion)}`:"—"}),s.jsx("td",{style:{...Ct.td,textAlign:"right"},children:M.total_cost!=null?`£${L(M.total_cost)}`:"—"}),s.jsx("td",{style:{...Ct.td,textAlign:"right",fontWeight:600,color:O(M.item_gp_percent)},children:W(M.item_gp_percent)})]},I))})]})]},U.course_name)),b.unmapped_items.length>0&&s.jsxs("div",{style:Ct.unmappedSection,children:[s.jsxs("div",{style:Ct.unmappedHeader,children:[s.jsx("span",{children:"Unmapped Items"}),s.jsxs("span",{style:Ct.unmappedSubtext,children:["£",L(b.unmapped_revenue_net)," unmapped (",(100-Number(b.mapped_revenue_percent)).toFixed(1),"% of sales)"]})]}),s.jsxs("table",{style:Ct.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ct.th,children:"Item"}),s.jsx("th",{style:Ct.th,children:"Portion"}),s.jsx("th",{style:Ct.th,children:"Category"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Net Revenue"}),s.jsx("th",{style:{...Ct.th,textAlign:"center"},children:"Action"})]})}),s.jsx("tbody",{children:b.unmapped_items.map((U,M)=>s.jsxs("tr",{style:Ct.tr,children:[s.jsx("td",{style:Ct.td,children:U.menu_item_name}),s.jsx("td",{style:{...Ct.td,color:U.portion_name==="Normal"?"#ccc":"#555"},children:U.portion_name==="Normal"?"—":U.portion_name}),s.jsx("td",{style:{...Ct.td,color:"#888"},children:U.category}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:[U.total_qty,U.dbb_qty>0&&s.jsxs("span",{title:`${U.dbb_qty} of ${U.total_qty} sold as DBB package — original price used`,style:Ct.dbbBadge,children:[U.dbb_qty," DBB"]})]}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:["£",L(U.total_revenue_net)]}),s.jsx("td",{style:{...Ct.td,textAlign:"center"},children:s.jsx("button",{onClick:()=>{w(U),_("")},style:Ct.mapBtn,children:"Map"})})]},M))})]})]})]}),x&&s.jsx("div",{style:Ct.overlay,children:s.jsxs("div",{style:Ct.modal,children:[s.jsxs("div",{style:Ct.modalHeader,children:[s.jsxs("h3",{style:{margin:0},children:["Map: ",x.menu_item_name,x.portion_name!=="Normal"&&` (${x.portion_name})`]}),s.jsx("button",{onClick:()=>{w(null),_("")},style:Ct.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ct.modalBody,children:[s.jsx("input",{value:S,onChange:U=>_(U.target.value),style:{...Ct.searchInput,marginBottom:"0.75rem"},placeholder:"Search dish recipes...",autoFocus:!0}),F?F.length===0?s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"No dish recipes found."}):s.jsx("div",{style:{maxHeight:"350px",overflow:"auto"},children:F.map(U=>s.jsxs("div",{onClick:()=>A.mutate({recipeId:U.id,menuItemName:x.menu_item_name,portionName:x.portion_name}),style:Ct.recipeRow,onMouseEnter:M=>M.currentTarget.style.background="#f0f7ff",onMouseLeave:M=>M.currentTarget.style.background="transparent",children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600},children:U.name}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#888"},children:[U.menu_section_name||"No course",U.cost_per_portion!=null&&` • Cost: £${Number(U.cost_per_portion).toFixed(2)}`]})]}),U.kds_menu_item_name&&s.jsxs("div",{style:{fontSize:"0.7rem",color:"#999"},children:["Already mapped: ",U.kds_menu_item_name]})]},U.id))}):s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"Loading recipes..."})]})]})})]})}const Ct={container:{maxWidth:"1100px",margin:"0 auto",padding:"1.5rem"},pageTitle:{fontSize:"1.4rem",fontWeight:700,marginBottom:"1rem"},dateBar:{display:"flex",gap:"1rem",alignItems:"flex-end",marginBottom:"1.5rem",flexWrap:"wrap"},dateGroup:{display:"flex",flexDirection:"column",gap:"0.2rem"},dateLabel:{fontSize:"0.75rem",fontWeight:600,color:"#666"},dateInput:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},generateBtn:{padding:"0.5rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},loading:{padding:"2rem",textAlign:"center",color:"#888"},error:{padding:"1rem",color:"#dc3545",background:"#fde8e8",borderRadius:"6px",marginBottom:"1rem"},summaryBanner:{background:"#f8f9fa",padding:"1.25rem",borderRadius:"8px",border:"2px solid #e0e0e0",marginBottom:"1.5rem"},summaryMain:{textAlign:"center",marginBottom:"1rem"},summaryLabel:{fontSize:"0.85rem",fontWeight:600,color:"#666",textTransform:"uppercase"},summaryValue:{fontSize:"2.5rem",fontWeight:800,lineHeight:1.2},summarySubtext:{fontSize:"0.75rem",color:"#999"},summaryStats:{display:"flex",justifyContent:"center",gap:"2rem",marginBottom:"1rem",flexWrap:"wrap"},statBox:{textAlign:"center"},statLabel:{fontSize:"0.75rem",color:"#666",fontWeight:600},statValue:{fontSize:"1.1rem",fontWeight:700},coverageSection:{borderTop:"1px solid #e0e0e0",paddingTop:"0.75rem"},coverageLabel:{fontSize:"0.8rem",color:"#555",marginBottom:"0.4rem"},coverageBarBg:{height:"8px",background:"#e0e0e0",borderRadius:"4px",overflow:"hidden"},coverageBarFill:{height:"100%",background:"#16a34a",borderRadius:"4px",transition:"width 0.3s"},courseSection:{marginBottom:"1rem",border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},courseHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",cursor:"pointer",flexWrap:"wrap",gap:"0.5rem"},courseTitle:{fontWeight:700,fontSize:"1rem"},collapseIcon:{marginRight:"0.5rem",fontSize:"0.85rem"},courseStats:{fontSize:"0.85rem",color:"#555"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666",background:"#fafafa"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.75rem",fontSize:"0.85rem"},unmappedSection:{marginTop:"1.5rem",border:"1px solid #f0c040",borderRadius:"8px",overflow:"hidden"},unmappedHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#fffbeb",fontWeight:700,fontSize:"1rem",flexWrap:"wrap",gap:"0.5rem"},unmappedSubtext:{fontSize:"0.85rem",fontWeight:400,color:"#92400e"},mapBtn:{padding:"0.25rem 0.75rem",background:"#3b82f6",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},dbbBadge:{display:"inline-block",marginLeft:"0.35rem",padding:"0.1rem 0.35rem",background:"#ede9fe",color:"#6d28d9",borderRadius:"4px",fontSize:"0.7rem",fontWeight:700,cursor:"default",whiteSpace:"nowrap"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"500px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},searchInput:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},recipeRow:{padding:"0.6rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",display:"flex",justifyContent:"space-between",alignItems:"center"}};function zfe(){const{token:n}=gn(),e=k.useRef(null),[t,r]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(!1),[d,c]=k.useState(!0),[u,f]=k.useState(new Set),p=Ue({mutationFn:async b=>{const C=new FormData;C.append("file",b);const T=await fetch("/api/reports/purchases/reconcile",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:C});if(!T.ok){const F=await T.json().catch(()=>({detail:"Upload failed"}));throw new Error(F.detail||"Upload failed")}return T.json()},onSuccess:b=>{o(b),l(b.matched_count>20)}}),g=k.useCallback(b=>{if(!b.name.toLowerCase().endsWith(".xlsx")){alert("Please upload an XLSX file");return}p.mutate(b)},[p]),m=k.useCallback(b=>{var T;b.preventDefault(),r(!1);const C=(T=b.dataTransfer.files)==null?void 0:T[0];C&&g(C)},[g]),y=k.useCallback(b=>{var T;const C=(T=b.target.files)==null?void 0:T[0];C&&g(C),b.target.value=""},[g]),v=(b,C,T)=>{const F=[C.join(","),...T.map(L=>L.map(W=>`"${W}"`).join(","))].join(` `),A=new Blob([F],{type:"text/csv"}),D=URL.createObjectURL(A),P=document.createElement("a");P.href=D,P.download=b,P.click(),URL.revokeObjectURL(D)},x=b=>new Date(b+"T00:00:00").toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}),w=i,S=(w==null?void 0:w.xero_only.filter(b=>b.is_expected_external))||[],_=(w==null?void 0:w.xero_only.filter(b=>!b.is_expected_external))||[];return s.jsxs("div",{style:Xe.container,children:[s.jsx("h2",{style:Xe.pageTitle,children:"Xero Reconciliation"}),!p.isPending&&s.jsxs("div",{style:{...Xe.dropZone,...t?Xe.dropZoneActive:{}},onDragOver:b=>{b.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:m,onClick:()=>{var b;return(b=e.current)==null?void 0:b.click()},children:[s.jsx("input",{ref:e,type:"file",accept:".xlsx",style:{display:"none"},onChange:y}),s.jsx("div",{style:Xe.dropIcon,children:"📄"}),s.jsx("div",{style:Xe.dropText,children:w?"Drop a new Xero XLSX to re-run":"Drop Xero Account Transactions XLSX here"}),s.jsx("div",{style:Xe.dropSubtext,children:"or click to browse"})]}),p.isPending&&s.jsx("div",{style:Xe.loading,children:"Parsing XLSX and reconciling against Flash invoices..."}),p.isError&&s.jsx("div",{style:Xe.error,children:p.error.message}),w&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Xe.summaryBar,children:[s.jsxs("div",{style:Xe.summaryPeriod,children:["Period: ",x(w.period_start)," – ",x(w.period_end)]}),s.jsxs("div",{style:Xe.summaryGrid,children:[s.jsxs("div",{style:Xe.summaryItem,children:[s.jsx("div",{style:Xe.summaryLabel,children:"Flash Total (net stock)"}),s.jsx("div",{style:Xe.summaryValue,children:w.flash_total})]}),s.jsxs("div",{style:Xe.summaryItem,children:[s.jsx("div",{style:Xe.summaryLabel,children:"Xero Total (net)"}),s.jsx("div",{style:Xe.summaryValue,children:w.xero_total})]}),s.jsxs("div",{style:Xe.summaryItem,children:[s.jsx("div",{style:Xe.summaryLabel,children:"Difference"}),s.jsx("div",{style:{...Xe.summaryValue,color:w.difference==="£0.00"?"#16a34a":"#dc2626"},children:w.difference})]})]}),s.jsxs("div",{style:Xe.summaryCounts,children:[s.jsxs("span",{style:Xe.countBadgeGreen,children:["✅ ",w.matched_count," matched"]}),s.jsxs("span",{style:Xe.countBadgeAmber,children:["⚠️ ",w.discrepancy_count," discrepancies"]}),s.jsxs("span",{style:Xe.countBadgeBlue,children:["❓ ",w.flash_only_count," Flash-only"]}),s.jsxs("span",{style:Xe.countBadgeBlue,children:["❓ ",w.xero_only_count," Xero-only"]})]}),w.non_stock_excluded_count>0&&s.jsxs("div",{style:Xe.footnote,children:[w.non_stock_excluded_count," non-stock Flash entries excluded (",w.non_stock_excluded_total,") — these post to other Xero accounts"]}),w.llm_matches_attempted&&s.jsx("div",{style:Xe.footnote,children:"AI-assisted matching was used for some discrepancies"})]}),s.jsxs("div",{style:Xe.section,children:[s.jsxs("div",{style:Xe.sectionHeader,onClick:()=>l(!a),children:[s.jsxs("span",{children:[s.jsx("span",{style:Xe.collapseIcon,children:a?"▸":"▾"}),"✅ Matched (",w.matched_count,")"]}),s.jsx("button",{onClick:b=>{b.stopPropagation(),v("reconciliation_matched.csv",["Date","Supplier","Ref","Amount"],w.matched.map(C=>[C.date,C.supplier,C.ref,C.amount]))},style:Xe.csvBtn,children:"Download CSV"})]}),!a&&w.matched.length>0&&s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Supplier"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Amount"}),s.jsx("th",{style:{...Xe.th,textAlign:"center",width:"40px"},children:"✓"})]})}),s.jsx("tbody",{children:w.matched.map((b,C)=>s.jsxs("tr",{style:Xe.tr,children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:b.supplier}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.amount}),s.jsxs("td",{style:{...Xe.td,textAlign:"center"},children:[s.jsx("span",{style:{color:"#16a34a"},children:"✓"}),b.match_source==="ai"&&s.jsx("span",{style:Xe.aiBadge,children:"AI"})]})]},C))})]}),!a&&w.matched.length===0&&s.jsx("div",{style:Xe.emptyMsg,children:"No exact matches found."})]}),s.jsxs("div",{style:{...Xe.section,borderColor:"#f59e0b"},children:[s.jsxs("div",{style:Xe.sectionHeaderAmber,children:[s.jsxs("span",{children:["⚠️ Discrepancies (",w.discrepancy_count,")"]}),s.jsx("button",{onClick:()=>v("reconciliation_discrepancies.csv",["Date","Supplier","Ref","Flash Amount","Xero Amount","Difference","Differs"],w.discrepancies.map(b=>[b.date,b.supplier,b.ref,b.flash_amount,b.xero_amount,b.difference,b.differs.join("; ")])),style:Xe.csvBtn,children:"Download CSV"})]}),w.discrepancies.length>0?s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...Xe.th,width:"30px"}}),s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Supplier"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Flash"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Xero"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Diff"}),s.jsx("th",{style:Xe.th,children:"What differs"})]})}),s.jsx("tbody",{children:w.discrepancies.map((b,C)=>{const T=u.has(C);return s.jsxs(k.Fragment,{children:[s.jsxs("tr",{style:{...Xe.tr,cursor:"pointer"},onClick:()=>f(F=>{const A=new Set(F);return A.has(C)?A.delete(C):A.add(C),A}),children:[s.jsx("td",{style:{...Xe.td,color:"#999",fontSize:"0.75rem"},children:T?"▾":"▸"}),s.jsx("td",{style:Xe.td,children:b.differs.includes("date")?s.jsxs("span",{children:[s.jsx("span",{style:Xe.amberHighlight,children:b.flash_date?x(b.flash_date):"—"}),s.jsx("span",{style:{color:"#999",margin:"0 0.25rem"},children:"/"}),s.jsx("span",{style:Xe.amberHighlight,children:b.xero_date?x(b.xero_date):"—"})]}):x(b.date)}),s.jsx("td",{style:Xe.td,children:b.flash_id?s.jsx("span",{title:"Open invoice",onClick:F=>{F.stopPropagation(),window.open(`/invoice/${b.flash_id}`,"_blank")},style:{cursor:"pointer",color:"#3b82f6",textDecoration:"underline dotted",textUnderlineOffset:"3px"},children:b.supplier}):b.supplier}),s.jsx("td",{style:Xe.td,children:b.differs.includes("ref")?s.jsxs("span",{children:[s.jsx("span",{style:Xe.amberHighlight,children:b.flash_ref||"—"}),s.jsx("span",{style:{color:"#999",margin:"0 0.25rem"},children:"/"}),s.jsx("span",{style:Xe.amberHighlight,children:b.xero_ref||"—"})]}):b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.flash_amount}),s.jsx("td",{style:{...Xe.td,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.xero_amount}),s.jsx("td",{style:{...Xe.td,textAlign:"right",fontWeight:600,color:"#dc2626"},children:b.difference}),s.jsxs("td",{style:Xe.td,children:[b.differs.map(F=>s.jsx("span",{style:Xe.differBadge,children:F},F)),b.match_source==="ai"&&s.jsx("span",{style:Xe.aiBadge,children:"AI"})]})]}),T&&s.jsx("tr",{style:{background:"#f8f9fa"},children:s.jsxs("td",{colSpan:8,style:{padding:0},children:[s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.8rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.detailTh,children:"Source"}),s.jsx("th",{style:Xe.detailTh,children:"Date"}),s.jsx("th",{style:Xe.detailTh,children:"Supplier / Description"}),s.jsx("th",{style:Xe.detailTh,children:"Ref"}),s.jsx("th",{style:{...Xe.detailTh,textAlign:"right"},children:"Net Amount"})]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{style:Xe.detailRow,children:[s.jsx("td",{style:Xe.detailTd,children:s.jsx("span",{style:Xe.flashBadge,children:"Flash"})}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("date")?{background:"#fef3c7"}:{}},children:b.flash_date?x(b.flash_date):"—"}),s.jsx("td",{style:Xe.detailTd,children:b.flash_supplier||b.supplier}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("ref")?{background:"#fef3c7"}:{}},children:b.flash_ref||"—"}),s.jsx("td",{style:{...Xe.detailTd,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.flash_amount})]}),s.jsxs("tr",{style:Xe.detailRow,children:[s.jsx("td",{style:Xe.detailTd,children:s.jsx("span",{style:Xe.xeroBadge,children:"Xero"})}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("date")?{background:"#fef3c7"}:{}},children:b.xero_date?x(b.xero_date):"—"}),s.jsx("td",{style:Xe.detailTd,children:b.xero_description||b.supplier}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("ref")?{background:"#fef3c7"}:{}},children:b.xero_ref||"—"}),s.jsx("td",{style:{...Xe.detailTd,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.xero_amount})]})]})]}),b.amount_insight&&s.jsxs("div",{style:Xe.insightBar,children:[s.jsx("span",{style:Xe.insightIcon,children:"💡"}),b.amount_insight]})]})})]},C)})})]}):s.jsx("div",{style:Xe.emptyMsg,children:"No discrepancies found — all matches are exact."})]}),s.jsxs("div",{style:Xe.section,children:[s.jsxs("div",{style:Xe.sectionHeader,children:[s.jsxs("span",{children:["❓ In Flash but not in Xero (",w.flash_only_count,")"]}),s.jsx("button",{onClick:()=>v("reconciliation_flash_only.csv",["Date","Supplier","Ref","Net Stock"],w.flash_only.map(b=>[b.date,b.supplier,b.ref,b.net_stock])),style:Xe.csvBtn,children:"Download CSV"})]}),w.flash_only.length>0?s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Supplier"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Flash Net Stock"})]})}),s.jsx("tbody",{children:w.flash_only.map((b,C)=>s.jsxs("tr",{style:Xe.tr,children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:s.jsx("span",{title:"Open invoice",onClick:()=>window.open(`/invoice/${b.flash_id}`,"_blank"),style:{cursor:"pointer",color:"#3b82f6",textDecoration:"underline dotted",textUnderlineOffset:"3px"},children:b.supplier})}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.net_stock})]},C))})]}):s.jsx("div",{style:Xe.emptyMsg,children:"All Flash invoices matched."})]}),s.jsxs("div",{style:Xe.section,children:[s.jsxs("div",{style:Xe.sectionHeader,children:[s.jsxs("span",{children:["❓ In Xero but not in Flash (",_.length,S.length>0?` + ${S.length} expected`:"",")"]}),s.jsx("button",{onClick:()=>v("reconciliation_xero_only.csv",["Date","Description","Ref","Net","Expected External"],w.xero_only.map(b=>[b.date,b.description,b.ref,b.net,b.is_expected_external?"Yes":"No"])),style:Xe.csvBtn,children:"Download CSV"})]}),_.length>0?s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Description"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Xero Net"})]})}),s.jsx("tbody",{children:_.map((b,C)=>s.jsxs("tr",{style:Xe.tr,children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:b.description}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.net})]},C))})]}):s.jsx("div",{style:Xe.emptyMsg,children:"No unexpected Xero-only entries."}),S.length>0&&s.jsxs("div",{style:Xe.externalSection,children:[s.jsxs("div",{style:Xe.externalHeader,onClick:()=>c(!d),children:[s.jsx("span",{style:Xe.collapseIcon,children:d?"▸":"▾"}),"Expected external (",S.length,") — Tesco, JVs, petty cash etc."]}),!d&&s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Description"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Xero Net"})]})}),s.jsx("tbody",{children:S.map((b,C)=>s.jsxs("tr",{style:{...Xe.tr,opacity:.6},children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:b.description}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.net})]},C))})]})]})]})]})]})}const Xe={container:{maxWidth:"1100px",margin:"0 auto",padding:"1.5rem"},pageTitle:{fontSize:"1.4rem",fontWeight:700,marginBottom:"1rem"},dropZone:{border:"2px dashed #ddd",borderRadius:"12px",padding:"2.5rem",textAlign:"center",cursor:"pointer",marginBottom:"1.5rem",background:"#fafafa",transition:"all 0.2s"},dropZoneActive:{borderColor:"#e94560",background:"#fff5f7"},dropIcon:{fontSize:"2.5rem",marginBottom:"0.5rem"},dropText:{fontSize:"1rem",fontWeight:600,color:"#333"},dropSubtext:{fontSize:"0.8rem",color:"#999",marginTop:"0.3rem"},loading:{padding:"2rem",textAlign:"center",color:"#888"},error:{padding:"1rem",color:"#dc3545",background:"#fde8e8",borderRadius:"6px",marginBottom:"1rem"},summaryBar:{background:"#1a1a2e",color:"white",padding:"1.25rem",borderRadius:"10px",marginBottom:"1.5rem"},summaryPeriod:{fontSize:"0.85rem",color:"#aaa",marginBottom:"0.75rem"},summaryGrid:{display:"flex",gap:"2rem",marginBottom:"0.75rem",flexWrap:"wrap"},summaryItem:{},summaryLabel:{fontSize:"0.7rem",textTransform:"uppercase",color:"#888",fontWeight:600},summaryValue:{fontSize:"1.3rem",fontWeight:700},summaryCounts:{display:"flex",gap:"0.75rem",flexWrap:"wrap",marginTop:"0.5rem"},countBadgeGreen:{fontSize:"0.8rem",background:"rgba(22,163,74,0.2)",color:"#4ade80",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeAmber:{fontSize:"0.8rem",background:"rgba(245,158,11,0.2)",color:"#fbbf24",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeBlue:{fontSize:"0.8rem",background:"rgba(59,130,246,0.2)",color:"#60a5fa",padding:"0.2rem 0.6rem",borderRadius:"4px"},footnote:{fontSize:"0.75rem",color:"#888",marginTop:"0.5rem",fontStyle:"italic"},section:{marginBottom:"1rem",border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",cursor:"pointer",fontWeight:700,fontSize:"0.95rem"},sectionHeaderAmber:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#fffbeb",fontWeight:700,fontSize:"0.95rem"},collapseIcon:{marginRight:"0.5rem",fontSize:"0.85rem"},csvBtn:{padding:"0.25rem 0.65rem",background:"transparent",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.75rem",cursor:"pointer",color:"#666"},emptyMsg:{padding:"1rem",textAlign:"center",color:"#999",fontSize:"0.85rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666",background:"#fafafa"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.75rem",fontSize:"0.85rem"},amberHighlight:{background:"#fef3c7",padding:"0.1rem 0.3rem",borderRadius:"3px"},differBadge:{display:"inline-block",background:"#fef3c7",color:"#92400e",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.7rem",fontWeight:600,marginRight:"0.3rem"},externalSection:{borderTop:"1px solid #e0e0e0",marginTop:"0.5rem"},externalHeader:{padding:"0.6rem 1rem",fontSize:"0.8rem",color:"#888",cursor:"pointer",fontStyle:"italic"},detailTh:{padding:"0.35rem 0.75rem",textAlign:"left",fontSize:"0.7rem",fontWeight:600,color:"#888",borderBottom:"1px solid #e0e0e0",background:"#f0f0f0"},detailRow:{borderBottom:"1px solid #eee"},detailTd:{padding:"0.35rem 0.75rem",fontSize:"0.8rem"},flashBadge:{display:"inline-block",background:"#dbeafe",color:"#1d4ed8",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.65rem",fontWeight:700},xeroBadge:{display:"inline-block",background:"#e0e7ff",color:"#4338ca",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.65rem",fontWeight:700},insightBar:{padding:"0.5rem 0.75rem",background:"#f0fdf4",borderTop:"1px solid #bbf7d0",fontSize:"0.8rem",color:"#166534",lineHeight:1.4},insightIcon:{marginRight:"0.4rem"},aiBadge:{display:"inline-block",background:"#f3e8ff",color:"#7c3aed",padding:"0.1rem 0.35rem",borderRadius:"3px",fontSize:"0.6rem",fontWeight:700,marginLeft:"0.3rem",verticalAlign:"middle"}};function qN(n,e){return e==="g"&&Math.abs(n)>=1e3?`${(n/1e3).toFixed(2)} kg`:e==="ml"&&Math.abs(n)>=1e3?`${(n/1e3).toFixed(2)} ltr`:e==="g"?`${n.toFixed(0)} g`:e==="ml"?`${n.toFixed(0)} ml`:e==="kg"?`${n.toFixed(2)} kg`:e==="ltr"?`${n.toFixed(2)} ltr`:e==="each"?`${n.toFixed(1)}`:`${n.toFixed(2)} ${e}`}function vx(n){return n==null?"—":`£${Number(n).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Ofe(n){if(n==null)return"—";const e=Number(n);return`${e>0?"+":""}${e.toFixed(1)}%`}function Lfe(n,e){if(n==null&&e==null)return"#666";const t=Math.abs(n??0),r=Math.abs(e??0);return t>50||r>50?"#dc2626":t>15||r>15?"#d97706":"#16a34a"}function Nfe(n,e){if(n==null&&e==null)return"transparent";const t=Math.abs(n??0),r=Math.abs(e??0);return t>50||r>50?"#fef2f2":t>15||r>15?"#fffbeb":"transparent"}function Wfe(){const{token:n}=gn(),e=new Date().toISOString().slice(0,10),t=new Date(Date.now()-30*864e5).toISOString().slice(0,10),[r,i]=k.useState(t),[o,a]=k.useState(e),[l,d]=k.useState(null),[c,u]=k.useState(!1),[f,p]=k.useState(null),[g,m]=k.useState(""),[y,v]=k.useState(!0),[x,w]=k.useState("variance_value"),[S,_]=k.useState(!0),b=async()=>{u(!0),p(null);try{const A=await fetch(`/api/reports/usage-variance?from_date=${r}&to_date=${o}`,{headers:{Authorization:`Bearer ${n}`}});if(!A.ok){const P=await A.json().catch(()=>({detail:"Request failed"}));throw new Error(P.detail||"Request failed")}const D=await A.json();d(D)}catch(A){p(A.message)}finally{u(!1)}},C=A=>new Date(A+"T00:00:00").toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"});let T=(l==null?void 0:l.items)??[];if(g){const A=g.toLowerCase();T=T.filter(D=>D.ingredient_name.toLowerCase().includes(A)||(D.category||"").toLowerCase().includes(A))}y||(T=T.filter(A=>Math.abs(A.variance_pct??0)>10||Math.abs(A.variance_value??0)>5)),T=[...T].sort((A,D)=>x==="name"?A.ingredient_name.localeCompare(D.ingredient_name):x==="variance_pct"?Math.abs(D.variance_pct??0)-Math.abs(A.variance_pct??0):Math.abs(D.variance_value??0)-Math.abs(A.variance_value??0));const F=l;return s.jsxs("div",{style:Mt.container,children:[s.jsx("h2",{style:Mt.pageTitle,children:"Theoretical vs Actual Usage"}),s.jsxs("div",{style:Mt.dateBar,children:[s.jsxs("label",{style:Mt.dateLabel,children:["From",s.jsx("input",{type:"date",value:r,onChange:A=>i(A.target.value),style:Mt.dateInput})]}),s.jsxs("label",{style:Mt.dateLabel,children:["To",s.jsx("input",{type:"date",value:o,onChange:A=>a(A.target.value),style:Mt.dateInput})]}),s.jsx("button",{onClick:b,disabled:c,style:Mt.generateBtn,children:c?"Loading...":"Generate"})]}),f&&s.jsx("div",{style:Mt.error,children:f}),F&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Mt.summaryBar,children:[s.jsxs("div",{style:Mt.summaryPeriod,children:[C(F.from_date)," – ",C(F.to_date)]}),s.jsxs("div",{style:Mt.summaryGrid,children:[s.jsxs("div",{style:Mt.summaryItem,children:[s.jsx("div",{style:Mt.summaryLabel,children:"Theoretical Cost"}),s.jsx("div",{style:Mt.summaryValue,children:vx(F.total_theoretical_value)})]}),s.jsxs("div",{style:Mt.summaryItem,children:[s.jsx("div",{style:Mt.summaryLabel,children:"Actual Purchased"}),s.jsx("div",{style:Mt.summaryValue,children:vx(F.total_actual_value)})]}),s.jsxs("div",{style:Mt.summaryItem,children:[s.jsx("div",{style:Mt.summaryLabel,children:"Variance"}),s.jsx("div",{style:{...Mt.summaryValue,color:F.total_variance_value>50?"#f87171":F.total_variance_value<-50?"#fbbf24":"#4ade80"},children:vx(F.total_variance_value)})]})]}),s.jsxs("div",{style:Mt.summaryCounts,children:[s.jsxs("span",{style:Mt.countBadgeGreen,children:[F.mapped_dish_count," dishes mapped"]}),F.unmapped_dish_count>0&&s.jsxs("span",{style:Mt.countBadgeAmber,children:[F.unmapped_dish_count," unmapped"]}),s.jsxs("span",{style:Mt.countBadgeBlue,children:[F.ingredients_with_purchases," ingredients with purchases"]}),F.ingredients_without_purchases>0&&s.jsxs("span",{style:Mt.countBadgeBlue,children:[F.ingredients_without_purchases," theoretical only"]})]}),s.jsx("div",{style:Mt.footnote,children:"Variance = Actual - Theoretical. Positive = over-purchased. This report estimates usage from recipes and may not account for stock carried forward, staff meals, or wastage."})]}),s.jsxs("div",{style:Mt.controlsBar,children:[s.jsx("input",{type:"text",placeholder:"Search ingredient...",value:g,onChange:A=>m(A.target.value),style:Mt.searchInput}),s.jsxs("label",{style:Mt.toggleLabel,children:[s.jsx("input",{type:"checkbox",checked:!y,onChange:A=>v(!A.target.checked)})," ","Variances only"]}),s.jsxs("select",{value:x,onChange:A=>w(A.target.value),style:Mt.sortSelect,children:[s.jsx("option",{value:"variance_value",children:"Sort: Variance £"}),s.jsx("option",{value:"variance_pct",children:"Sort: Variance %"}),s.jsx("option",{value:"name",children:"Sort: Name"})]})]}),s.jsx("div",{style:Mt.tableWrap,children:s.jsxs("table",{style:Mt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Mt.th,children:"Ingredient"}),s.jsx("th",{style:Mt.th,children:"Category"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Theo. Qty"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Theo. £"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Actual Qty"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Actual £"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Variance £"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Variance %"}),s.jsx("th",{style:{...Mt.th,textAlign:"center"},children:"Dishes"}),s.jsx("th",{style:{...Mt.th,textAlign:"center"},children:"Invoices"})]})}),s.jsxs("tbody",{children:[T.map(A=>{const D=Nfe(A.variance_pct,A.variance_value),P=Lfe(A.variance_pct,A.variance_value);return s.jsxs("tr",{style:{...Mt.tr,background:D},children:[s.jsx("td",{style:Mt.td,children:s.jsx("span",{style:{fontWeight:600},children:A.ingredient_name})}),s.jsx("td",{style:{...Mt.td,color:"#888",fontSize:"0.8rem"},children:A.category||"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.theoretical_qty>0?qN(A.theoretical_qty,A.standard_unit):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.theoretical_value>0?vx(A.theoretical_value):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},title:A.actual_qty==null?"No mapped purchases in period":void 0,children:A.actual_qty!=null?qN(A.actual_qty,A.standard_unit):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.actual_value!=null?vx(A.actual_value):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right",fontWeight:600,color:P},children:A.variance_value!=null?vx(A.variance_value):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right",fontWeight:600,color:P},children:Ofe(A.variance_pct)}),s.jsx("td",{style:{...Mt.td,textAlign:"center",color:"#888",fontSize:"0.8rem"},children:A.dishes_using}),s.jsx("td",{style:{...Mt.td,textAlign:"center",color:"#888",fontSize:"0.8rem"},children:A.invoice_count||"—"})]},A.ingredient_id)}),T.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:10,style:{...Mt.td,textAlign:"center",color:"#999"},children:g||!y?"No items match filters.":"No data."})})]})]})}),F.unmapped_sales.length>0&&s.jsxs("div",{style:Mt.section,children:[s.jsx("div",{style:Mt.sectionHeader,onClick:()=>_(!S),children:s.jsxs("span",{children:[s.jsx("span",{style:Mt.collapseIcon,children:S?"▸":"▾"}),"Unmapped Sales Items (",F.unmapped_sales.length,") — no recipe, can't calculate theoretical usage"]})}),!S&&s.jsxs("table",{style:Mt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Mt.th,children:"Menu Item"}),s.jsx("th",{style:Mt.th,children:"Portion"}),s.jsx("th",{style:Mt.th,children:"Category"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Qty Sold"})]})}),s.jsx("tbody",{children:F.unmapped_sales.map((A,D)=>s.jsxs("tr",{style:Mt.tr,children:[s.jsx("td",{style:Mt.td,children:A.menu_item_name}),s.jsx("td",{style:{...Mt.td,color:"#888"},children:A.portion_name!=="Normal"?A.portion_name:"—"}),s.jsx("td",{style:{...Mt.td,color:"#888"},children:A.category||"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.total_qty})]},D))})]})]})]})]})}const Mt={container:{maxWidth:"1200px",margin:"0 auto",padding:"1.5rem"},pageTitle:{fontSize:"1.4rem",fontWeight:700,marginBottom:"1rem"},dateBar:{display:"flex",gap:"1rem",alignItems:"flex-end",marginBottom:"1.5rem",flexWrap:"wrap"},dateLabel:{fontSize:"0.8rem",fontWeight:600,color:"#666",display:"flex",flexDirection:"column",gap:"0.25rem"},dateInput:{padding:"0.4rem 0.5rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.85rem"},generateBtn:{padding:"0.45rem 1.2rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",fontWeight:600,cursor:"pointer",fontSize:"0.85rem"},error:{padding:"1rem",color:"#dc3545",background:"#fde8e8",borderRadius:"6px",marginBottom:"1rem"},summaryBar:{background:"#1a1a2e",color:"white",padding:"1.25rem",borderRadius:"10px",marginBottom:"1.5rem"},summaryPeriod:{fontSize:"0.85rem",color:"#aaa",marginBottom:"0.75rem"},summaryGrid:{display:"flex",gap:"2rem",marginBottom:"0.75rem",flexWrap:"wrap"},summaryItem:{},summaryLabel:{fontSize:"0.7rem",textTransform:"uppercase",color:"#888",fontWeight:600},summaryValue:{fontSize:"1.3rem",fontWeight:700},summaryCounts:{display:"flex",gap:"0.75rem",flexWrap:"wrap",marginTop:"0.5rem"},countBadgeGreen:{fontSize:"0.8rem",background:"rgba(22,163,74,0.2)",color:"#4ade80",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeAmber:{fontSize:"0.8rem",background:"rgba(245,158,11,0.2)",color:"#fbbf24",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeBlue:{fontSize:"0.8rem",background:"rgba(59,130,246,0.2)",color:"#60a5fa",padding:"0.2rem 0.6rem",borderRadius:"4px"},footnote:{fontSize:"0.72rem",color:"#777",marginTop:"0.75rem",fontStyle:"italic",lineHeight:1.5},controlsBar:{display:"flex",gap:"1rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.4rem 0.6rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.85rem",width:"200px"},toggleLabel:{fontSize:"0.85rem",color:"#555",cursor:"pointer",userSelect:"none"},sortSelect:{padding:"0.35rem 0.5rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.8rem",color:"#555"},tableWrap:{overflowX:"auto"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.72rem",fontWeight:600,color:"#666",background:"#fafafa",whiteSpace:"nowrap"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.75rem",fontSize:"0.83rem",whiteSpace:"nowrap"},section:{marginTop:"1.5rem",border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",cursor:"pointer",fontWeight:600,fontSize:"0.9rem",color:"#888"},collapseIcon:{marginRight:"0.5rem",fontSize:"0.85rem"}},oh=TK.invoices;function Ufe(){const{token:n}=gn(),e=k.useMemo(()=>wM(),[]),[t,r]=co(oh.query,""),[i,o]=co(oh.includeLineItems,!1),[a,l]=co(oh.supplier,""),[d,c]=co(oh.status,""),[u,f]=co(oh.dateFrom,e.from),[p,g]=co(oh.dateTo,e.to),[m,y]=co(oh.groupBy,""),[v,x]=co(oh.sortColumn,""),[w,S]=co(oh.sortDirection,"asc"),[_,b]=k.useState(new Set),C=Rg(t,300),{data:T}=Oe({queryKey:["suppliers"],queryFn:async()=>{const z=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch suppliers");return z.json()}}),{data:F,isLoading:A,error:D}=Oe({queryKey:["search-invoices",C,i,a,d,u,p,m],queryFn:async()=>{const z=new URLSearchParams;C&&z.set("q",C),i&&z.set("include_line_items","true"),a&&z.set("supplier_id",a),d&&z.set("status",d),u&&z.set("date_from",u),p&&z.set("date_to",p),m&&z.set("group_by",m),z.set("limit","200");const G=await fetch(`/api/search/invoices?${z}`,{headers:{Authorization:`Bearer ${n}`}});if(!G.ok)throw new Error("Search failed");return G.json()},enabled:!!n}),P=z=>{b(G=>{const te=new Set(G);return te.has(z)?te.delete(z):te.add(z),te})},L=z=>{v===z?S(w==="asc"?"desc":"asc"):(x(z),S("asc"))},W=z=>v!==z?null:w==="asc"?" ▲":" ▼",O=z=>{const G={pending:"#f59e0b",processed:"#3b82f6",reviewed:"#8b5cf6",confirmed:"#22c55e"};return s.jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"12px",backgroundColor:G[z]||"#9ca3af",color:"white"},children:z})},U=z=>z.net_total!==null?z.net_total:z.total!==null?z.total:null,M=z=>z.total!==null?z.total:z.net_total!==null?z.net_total:null,I=k.useMemo(()=>!(F!=null&&F.items)||!v?(F==null?void 0:F.items)||[]:[...F.items].sort((G,te)=>{let re,me;switch(v){case"invoice_number":re=G.invoice_number||"",me=te.invoice_number||"";break;case"supplier":re=G.supplier_name||G.vendor_name||"",me=te.supplier_name||te.vendor_name||"";break;case"date":re=G.invoice_date||"",me=te.invoice_date||"";break;case"net_total":re=U(G)??-1/0,me=U(te)??-1/0;break;case"gross_total":re=M(G)??-1/0,me=M(te)??-1/0;break;case"status":re=G.status||"",me=te.status||"";break;default:return 0}return typeof re=="string"&&typeof me=="string"?w==="asc"?re.localeCompare(me):me.localeCompare(re):w==="asc"?re-me:me-re}),[F==null?void 0:F.items,v,w]),H=k.useMemo(()=>{var G;if(!I||!m||!(F!=null&&F.groups))return null;const z={};for(const te of I){let re;m==="supplier"?re=te.supplier_name||"Unknown":m==="month"?re=((G=te.invoice_date)==null?void 0:G.substring(0,7))||"Unknown":re="All",z[re]||(z[re]=[]),z[re].push(te)}return z},[I,m,F==null?void 0:F.groups]);return s.jsxs("div",{style:{padding:"20px",maxWidth:"1400px",margin:"0 auto"},children:[s.jsx("h1",{style:{marginBottom:"20px"},children:"Search Invoices"}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"12px",marginBottom:"20px",padding:"16px",backgroundColor:"#f8fafc",borderRadius:"8px"},children:[s.jsx("input",{type:"text",placeholder:"Search invoice number, vendor...",value:t,onChange:z=>r(z.target.value),style:{flex:"1 1 250px",padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"4px",fontSize:"14px"}}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"14px",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:i,onChange:z=>o(z.target.checked)}),"Include line items"]}),s.jsxs("select",{value:a,onChange:z=>l(z.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Suppliers"}),T==null?void 0:T.map(z=>s.jsx("option",{value:z.id,children:z.name},z.id))]}),s.jsxs("select",{value:d,onChange:z=>c(z.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Statuses"}),s.jsx("option",{value:"pending",children:"Pending"}),s.jsx("option",{value:"processed",children:"Processed"}),s.jsx("option",{value:"reviewed",children:"Reviewed"}),s.jsx("option",{value:"confirmed",children:"Confirmed"})]}),s.jsxs("select",{value:m,onChange:z=>y(z.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"No Grouping"}),s.jsx("option",{value:"supplier",children:"Group by Supplier"}),s.jsx("option",{value:"month",children:"Group by Month"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("label",{style:{fontSize:"14px"},children:"From:"}),s.jsx("input",{type:"date",value:u,onChange:z=>f(z.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}}),s.jsx("label",{style:{fontSize:"14px"},children:"To:"}),s.jsx("input",{type:"date",value:p,onChange:z=>g(z.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}})]})]}),A&&s.jsx("p",{children:"Loading..."}),D&&s.jsxs("p",{style:{color:"red"},children:["Error: ",D.message]}),F&&s.jsxs("div",{children:[s.jsxs("p",{style:{marginBottom:"12px",color:"#6b7280"},children:["Found ",F.total_count," invoice",F.total_count!==1?"s":""]}),m&&F.groups?s.jsx("div",{children:F.groups.map(z=>s.jsxs("div",{style:{marginBottom:"16px",border:"1px solid #e5e7eb",borderRadius:"8px",overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>P(z.name),style:{padding:"12px 16px",backgroundColor:"#f1f5f9",cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{style:{fontWeight:600},children:[_.has(z.name)?"▸":"▾"," ",z.name]}),s.jsxs("span",{style:{color:"#6b7280"},children:[z.count," invoice",z.count!==1?"s":"",z.total!==null&&` • ${Td(z.total)}`]})]}),!_.has(z.name)&&(H==null?void 0:H[z.name])&&s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f8fafc"},children:[s.jsxs("th",{style:od,onClick:()=>L("invoice_number"),children:["Invoice #",W("invoice_number")]}),s.jsxs("th",{style:od,onClick:()=>L("supplier"),children:["Supplier",W("supplier")]}),s.jsxs("th",{style:od,onClick:()=>L("date"),children:["Date",W("date")]}),s.jsxs("th",{style:od,onClick:()=>L("net_total"),children:["Net Total",W("net_total")]}),s.jsxs("th",{style:od,onClick:()=>L("gross_total"),children:["Gross Total",W("gross_total")]}),s.jsxs("th",{style:od,onClick:()=>L("status"),children:["Status",W("status")]})]})}),s.jsx("tbody",{children:H[z.name].map(G=>s.jsxs("tr",{style:{borderBottom:"1px solid #e5e7eb"},children:[s.jsx("td",{style:ad,children:s.jsx("a",{href:`/invoice/${G.id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none"},children:G.invoice_number||"-"})}),s.jsx("td",{style:ad,children:G.supplier_name||G.vendor_name||"-"}),s.jsx("td",{style:ad,children:Cm(G.invoice_date)}),s.jsx("td",{style:ad,children:Td(U(G))}),s.jsx("td",{style:ad,children:Td(M(G))}),s.jsx("td",{style:ad,children:O(G.status)})]},G.id))})]})]},z.name))}):s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f1f5f9"},children:[s.jsxs("th",{style:od,onClick:()=>L("invoice_number"),children:["Invoice #",W("invoice_number")]}),s.jsxs("th",{style:od,onClick:()=>L("supplier"),children:["Supplier",W("supplier")]}),s.jsxs("th",{style:od,onClick:()=>L("date"),children:["Date",W("date")]}),s.jsxs("th",{style:od,onClick:()=>L("net_total"),children:["Net Total",W("net_total")]}),s.jsxs("th",{style:od,onClick:()=>L("gross_total"),children:["Gross Total",W("gross_total")]}),s.jsxs("th",{style:od,onClick:()=>L("status"),children:["Status",W("status")]})]})}),s.jsx("tbody",{children:I.map(z=>s.jsxs("tr",{style:{borderBottom:"1px solid #e5e7eb"},children:[s.jsx("td",{style:ad,children:s.jsx("a",{href:`/invoice/${z.id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none"},children:z.invoice_number||"-"})}),s.jsx("td",{style:ad,children:z.supplier_name||z.vendor_name||"-"}),s.jsx("td",{style:ad,children:Cm(z.invoice_date)}),s.jsx("td",{style:ad,children:Td(U(z))}),s.jsx("td",{style:ad,children:Td(M(z))}),s.jsx("td",{style:ad,children:O(z.status)})]},z.id))})]})]})]})}const Hfe={padding:"12px",textAlign:"left",fontWeight:600,fontSize:"14px"},od={...Hfe,cursor:"pointer",userSelect:"none"},ad={padding:"12px",fontSize:"14px"},ah=TK.lineItems;function qfe(){const{token:n}=gn(),e=pi(),t=k.useMemo(()=>wM(),[]),[r,i]=co(ah.query,""),[o,a]=co(ah.supplier,""),[l,d]=co(ah.dateFrom,t.from),[c,u]=co(ah.dateTo,t.to),[f,p]=co(ah.groupBy,""),[g,m]=co(ah.priceChangeFilter,""),[y,v]=co(ah.mappedFilter,""),[x,w]=co(ah.sortColumn,""),[S,_]=co(ah.sortDirection,"asc"),[b,C]=k.useState(null),[T,F]=k.useState(null),[A,D]=k.useState({}),[P,L]=k.useState(""),[W,O]=k.useState([]),[U,M]=k.useState(!1),[I,H]=k.useState(null),[z,G]=k.useState(""),[te,re]=k.useState(""),[me,J]=k.useState(!1),[ne,ye]=k.useState(""),[ke,Ye]=k.useState(!1),[De,qe]=k.useState({}),[ue,Ze]=k.useState(null),ee=Rg(r,300),{data:Z}=Oe({queryKey:["suppliers"],queryFn:async()=>{const ce=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!ce.ok)throw new Error("Failed to fetch suppliers");return ce.json()}}),{data:ge}=Oe({queryKey:["search-settings"],queryFn:async()=>{const ce=await fetch("/api/search/settings",{headers:{Authorization:`Bearer ${n}`}});if(!ce.ok)throw new Error("Failed to fetch search settings");return ce.json()},staleTime:6e4}),{data:Te,isLoading:Be,error:he}=Oe({queryKey:["search-line-items",ee,o,l,c,f,y],queryFn:async()=>{const ce=new URLSearchParams;ee&&ce.set("q",ee),o&&ce.set("supplier_id",o),l&&ce.set("date_from",l),c&&ce.set("date_to",c),f&&ce.set("group_by",f),y&&ce.set("mapped",y),ce.set("limit","200");const Je=await fetch(`/api/search/line-items?${ce}`,{headers:{Authorization:`Bearer ${n}`}});if(!Je.ok)throw new Error("Search failed");return Je.json()},enabled:!!n});k.useEffect(()=>{if(!(Te!=null&&Te.items)||!n)return;const ce=new Map;for(const ct of Te.items)!ct.ingredient_id&&!ct.product_code&&ct.description&&ct.supplier_id&&(ce.has(ct.supplier_id)||ce.set(ct.supplier_id,[]),ce.get(ct.supplier_id).push({description:ct.description,price:ct.most_recent_price??void 0}));if(ce.size===0){qe({});return}const Je={},jt=Array.from(ce.entries()).map(([ct,Se])=>fetch("/api/ingredients/sources/alias-suggestions",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({supplier_id:ct,items:Se})}).then(ot=>ot.ok?ot.json():[]).then(ot=>{for(const ut of ot)Je[`${ct}:${ut.description.toLowerCase()}`]=ut}).catch(()=>{}));Promise.all(jt).then(()=>qe({...Je}))},[Te==null?void 0:Te.items,n]);const He=Ue({mutationFn:async({sourceId:ce,alias:Je})=>{const jt=await fetch(`/api/ingredients/sources/${ce}/aliases`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({alias:Je})});if(!jt.ok)throw new Error("Failed to add alias");return jt.json()},onSuccess:(ce,Je)=>{qe(jt=>{const ct={...jt};for(const Se of Object.keys(ct))Se.endsWith(`:${Je.alias.toLowerCase()}`)&&delete ct[Se];return ct}),Ze(null),e.invalidateQueries({queryKey:["search-line-items"]})}}),Ge=ce=>{ce.supplier_id&&C({isOpen:!0,productCode:ce.product_code,description:ce.description,unit:ce.unit,supplierId:ce.supplier_id,supplierName:ce.supplier_name||"Unknown"})},ae=async ce=>{F(ce),D({pack_quantity:ce.most_recent_pack_quantity?Number(ce.most_recent_pack_quantity):null,unit_size:ce.most_recent_unit_size?Number(ce.most_recent_unit_size):null,unit_size_type:ce.most_recent_unit_size_type,unit_price:ce.most_recent_price!=null?Number(ce.most_recent_price):null}),H(ce.ingredient_id||null),G(ce.ingredient_name||""),re(ce.ingredient_standard_unit||""),J(!1),L(""),O([]),ye(""),Ye(!1),ce.most_recent_unit_size&&ce.most_recent_unit_size_type&&Q(ce.ingredient_standard_unit||void 0,{pack_quantity:ce.most_recent_pack_quantity,unit_size:ce.most_recent_unit_size,unit_size_type:ce.most_recent_unit_size_type,unit_price:ce.most_recent_price}),ce.description&&!ce.ingredient_id&&K(ce.description)},K=async ce=>{if(!ce||ce.length<2){O([]);return}M(!0);try{const Je=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(ce)}`,{headers:{Authorization:`Bearer ${n}`}});Je.ok&&O(await Je.json())}catch{}M(!1)},de=ce=>{H(ce.id),G(ce.name),re(ce.standard_unit),L(""),O([]),A.unit_size_type||D(Je=>({...Je,unit_size_type:ce.standard_unit})),Q(ce.standard_unit)},Y=ce=>{e.invalidateQueries({queryKey:["search-line-items"]}),X()},Q=(ce,Je)=>{var Qt;const jt=Je?{...A,...Je}:A,ct=ce||te||jt.unit_size_type,Se=jt.pack_quantity||1,ot=jt.unit_size,ut=jt.unit_size_type,Ot=jt.unit_price;if(!ot||!ut||!ct){ye("");return}const on=(Qt={g:{g:1,kg:.001},kg:{g:1e3,kg:1},oz:{g:28.3495,kg:.0283495},ml:{ml:1,ltr:.001},cl:{ml:10,ltr:.01},ltr:{ml:1e3,ltr:1},each:{each:1}}[ut])==null?void 0:Qt[ct];if(!on){ye(ut!==ct?`Cannot convert ${ut} → ${ct}`:`${ot}${ut}`);return}const Ke=Se*ot*on,Rt=Ot?Ot/Ke:null;let Cr=`${Se>1?`${Se} × ${ot}${ut} = `:""}${Ke.toFixed(Ke%1?2:0)} ${ct}`;Rt&&(Cr+=` → £${Rt.toFixed(4)} per ${ct}`,ct==="g"?Cr+=` (£${(Rt*1e3).toFixed(2)}/kg)`:ct==="ml"&&(Cr+=` (£${(Rt*1e3).toFixed(2)}/ltr)`)),ye(Cr)},X=()=>{F(null),D({}),H(null),G(""),re(""),J(!1),L(""),O([]),ye("")},pe=async()=>{if(T){Ye(!0);try{if(T.most_recent_line_item_id&&T.most_recent_invoice_id&&await fetch(`/api/invoices/${T.most_recent_invoice_id}/line-items/${T.most_recent_line_item_id}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({pack_quantity:A.pack_quantity||null,unit_size:A.unit_size||null,unit_size_type:A.unit_size_type||null,...I?{ingredient_id:I}:{}})}),I&&T.supplier_id){const ce={supplier_id:T.supplier_id,pack_quantity:A.pack_quantity||1,unit_size:A.unit_size||null,unit_size_type:A.unit_size_type||te||null};T.product_code?ce.product_code=T.product_code:T.description&&(ce.description_pattern=T.description.substring(0,100).toLowerCase().trim()),A.unit_price&&(ce.latest_unit_price=A.unit_price),T.most_recent_invoice_id&&(ce.invoice_id=T.most_recent_invoice_id),await fetch(`/api/ingredients/${I}/sources`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(ce)})}e.invalidateQueries({queryKey:["search-line-items"]}),X()}catch(ce){console.error("Failed to save mapping:",ce)}Ye(!1)}},we=ce=>{x===ce?_(S==="asc"?"desc":"asc"):(w(ce),_("asc"))},Ne=ce=>x!==ce?null:S==="asc"?" ▲":" ▼",st=k.useMemo(()=>Te!=null&&Te.items?g?Te.items.filter(ce=>g==="no_history"?ce.price_change_status==="no_history":g==="no_change"?ce.price_change_status==="consistent"||ce.price_change_status==="acknowledged":g==="increase"?ce.price_change_percent!==null&&ce.price_change_percent>0:g==="decrease"?ce.price_change_percent!==null&&ce.price_change_percent<0:!0):Te.items:[],[Te==null?void 0:Te.items,g]),Ve=k.useMemo(()=>!st.length||!x?st:[...st].sort((Je,jt)=>{let ct,Se;switch(x){case"code":ct=Je.product_code||"",Se=jt.product_code||"";break;case"description":ct=Je.description||"",Se=jt.description||"";break;case"supplier":ct=Je.supplier_name||"",Se=jt.supplier_name||"";break;case"price":ct=Je.most_recent_price??-1/0,Se=jt.most_recent_price??-1/0;break;case"ingredient_rate":ct=Je.price_per_std_unit!=null?typeof Je.price_per_std_unit=="string"?parseFloat(Je.price_per_std_unit):Je.price_per_std_unit:-1/0,Se=jt.price_per_std_unit!=null?typeof jt.price_per_std_unit=="string"?parseFloat(jt.price_per_std_unit):jt.price_per_std_unit:-1/0;break;case"total_quantity":ct=Je.total_quantity??-1/0,Se=jt.total_quantity??-1/0;break;case"occurrence_count":ct=Je.occurrence_count??0,Se=jt.occurrence_count??0;break;case"last_invoice":ct=Je.most_recent_invoice_number||"",Se=jt.most_recent_invoice_number||"";break;case"last_date":ct=Je.most_recent_date||"",Se=jt.most_recent_date||"";break;default:return 0}return typeof ct=="string"&&typeof Se=="string"?S==="asc"?ct.localeCompare(Se):Se.localeCompare(ct):S==="asc"?ct-Se:Se-ct}),[st,x,S]),Re=ce=>{const Je=Khe(ce.price_change_status);if(!Je.icon)return null;if(ce.price_change_status==="consistent"||ce.price_change_status==="acknowledged"){const ct=Math.ceil((new Date(c).getTime()-new Date(l).getTime())/864e5)+30;return s.jsx("div",{style:{fontSize:"0.75rem",marginTop:"2px",color:Je.color,cursor:"help"},title:`Price stable over last ${ct} days Click 📊 to see full 12-month history`,children:s.jsx("span",{style:{fontWeight:"bold"},children:Je.icon})})}if((ce.price_change_status==="amber"||ce.price_change_status==="red")&&ce.price_change_percent!==null&&ce.price_change_percent!==0){const jt=ce.price_change_percent>0,ct=jt?"▲":"▼",Se=jt?"#ef4444":"#22c55e",ot=jt?"increased":"decreased",Ot=Math.ceil((new Date(c).getTime()-new Date(l).getTime())/(1e3*60*60*24))+30;return s.jsxs("div",{style:{fontSize:"0.75rem",marginTop:"2px",color:Se,cursor:"help"},title:`Price ${ot} ${Math.abs(ce.price_change_percent).toFixed(1)}% over last ${Ot} days Click 📊 to see full history`,children:[s.jsx("span",{style:{fontWeight:"bold"},children:ct})," ",Math.abs(ce.price_change_percent).toFixed(1),"%"]})}return ce.price_change_status==="amber"||ce.price_change_status==="red"?s.jsx("div",{style:{fontSize:"0.75rem",marginTop:"2px",color:Je.color},children:s.jsx("span",{style:{fontWeight:"bold"},children:Je.icon})}):null},Le=ce=>{if(ce.price_per_std_unit==null)return null;const Je=typeof ce.price_per_std_unit=="string"?parseFloat(ce.price_per_std_unit):ce.price_per_std_unit,jt=ce.ingredient_standard_unit||"?";if(jt==="g"&&Je<1)return`£${(Je*1e3).toFixed(2)}/kg`;if(jt==="ml"&&Je<1)return`£${(Je*1e3).toFixed(2)}/ltr`;const ct=Je>=1?2:4;return`£${Je.toFixed(ct)}/${jt}`},rt=()=>{i(""),a(""),m(""),v(""),p("");const ce=wM();d(ce.from),u(ce.to)},$e=r||o||g||y||f;return s.jsxs("div",{style:{padding:"20px",maxWidth:"1600px",margin:"0 auto"},children:[s.jsx("h1",{style:{marginBottom:"20px"},children:"Search Line Items"}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"12px",marginBottom:"20px",padding:"16px",backgroundColor:"#f8fafc",borderRadius:"8px"},children:[s.jsx("input",{type:"text",placeholder:"Search product code, description...",value:r,onChange:ce=>i(ce.target.value),style:{flex:"1 1 300px",padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"4px",fontSize:"14px"}}),s.jsxs("select",{value:o,onChange:ce=>a(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Suppliers"}),Z==null?void 0:Z.map(ce=>s.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),s.jsxs("select",{value:g,onChange:ce=>m(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Price Changes"}),s.jsx("option",{value:"no_history",children:"No History"}),s.jsx("option",{value:"no_change",children:"✓ No Change"}),s.jsx("option",{value:"increase",children:"▲ Price Increase"}),s.jsx("option",{value:"decrease",children:"▼ Price Decrease"})]}),s.jsxs("select",{value:y,onChange:ce=>v(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Mapping"}),s.jsx("option",{value:"yes",children:"Mapped to Ingredient"}),s.jsx("option",{value:"no",children:"Not Mapped"})]}),s.jsxs("select",{value:f,onChange:ce=>p(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"No Grouping"}),s.jsx("option",{value:"supplier",children:"Group by Supplier"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("label",{style:{fontSize:"14px"},children:"From:"}),s.jsx("input",{type:"date",value:l,onChange:ce=>d(ce.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}}),s.jsx("label",{style:{fontSize:"14px"},children:"To:"}),s.jsx("input",{type:"date",value:c,onChange:ce=>u(ce.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}})]}),$e&&s.jsx("button",{onClick:rt,style:{padding:"8px 16px",background:"#ef4444",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},children:"Clear Filters"})]}),s.jsxs("div",{style:{display:"flex",gap:"16px",marginBottom:"16px",fontSize:"13px",color:"#6b7280",flexWrap:"wrap"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#22c55e",fontWeight:"bold"},children:"✓"})," Price consistent"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#ef4444",fontWeight:"bold"},children:"▲"})," Price increase"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#22c55e",fontWeight:"bold"},children:"▼"})," Price decrease"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#28a745"},children:"⚖"})," Mapped to ingredient"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#ccc"},children:"⚖"})," Not mapped"]})]}),Be&&s.jsx("p",{children:"Loading..."}),he&&s.jsxs("p",{style:{color:"red"},children:["Error: ",he.message]}),Te&&s.jsxs("div",{children:[s.jsxs("p",{style:{marginBottom:"12px",color:"#6b7280"},children:["Found ",Te.total_count," unique item",Te.total_count!==1?"s":"",(g||y)&&` (showing ${Ve.length} filtered)`]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:"1000px"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f1f5f9"},children:[s.jsxs("th",{style:lh,onClick:()=>we("code"),children:["Code",Ne("code")]}),s.jsxs("th",{style:{...lh,minWidth:"150px"},onClick:()=>we("description"),children:["Description",Ne("description")]}),s.jsxs("th",{style:lh,onClick:()=>we("supplier"),children:["Supplier",Ne("supplier")]}),s.jsxs("th",{style:lh,onClick:()=>we("price"),children:["Price",Ne("price")]}),s.jsx("th",{style:{...NK,textAlign:"center",width:"40px"},children:"⚖"}),s.jsxs("th",{style:{...lh,textAlign:"right"},onClick:()=>we("ingredient_rate"),children:["Ingredient Rate",Ne("ingredient_rate")]}),s.jsxs("th",{style:lh,onClick:()=>we("total_quantity"),children:["Total Qty",Ne("total_quantity")]}),s.jsxs("th",{style:lh,onClick:()=>we("occurrence_count"),children:["#",Ne("occurrence_count")]}),s.jsxs("th",{style:lh,onClick:()=>we("last_invoice"),children:["Last Invoice",Ne("last_invoice")]}),s.jsxs("th",{style:lh,onClick:()=>we("last_date"),children:["Last Date",Ne("last_date")]})]})}),s.jsx("tbody",{children:Ve.map((ce,Je)=>s.jsxs("tr",{style:{borderBottom:"1px solid #e5e7eb"},children:[s.jsx("td",{style:Yc,children:ce.product_code||"-"}),s.jsxs("td",{style:Yc,children:[s.jsxs("div",{children:[ce.description||"-",ce.has_definition&&s.jsx("span",{title:`${ce.portions_per_unit||"?"} portions per unit`,style:{marginLeft:"6px",color:"#8b5cf6"},children:"📦"})]}),!ce.ingredient_id&&!ce.product_code&&ce.description&&ce.supplier_id&&(()=>{const jt=`${ce.supplier_id}:${ce.description.toLowerCase()}`,ct=De[jt];if(!ct)return null;const Se=ue===jt;return s.jsxs("div",{style:{fontSize:"0.7rem",color:"#0c5460",background:"#d1ecf1",padding:"0.2rem 0.4rem",borderRadius:"3px",marginTop:"3px",border:"1px solid #bee5eb",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.4rem"},children:[s.jsxs("span",{children:['Similar to "',ct.canonical_description,'"',ct.ingredient_name&&s.jsxs(s.Fragment,{children:[" → ",ct.ingredient_name]})," ","(",Math.round(ct.similarity*100),"%)"]}),s.jsx("button",{type:"button",onClick:ot=>{ot.stopPropagation(),Ze(jt),He.mutate({sourceId:ct.source_id,alias:ce.description})},disabled:Se,style:{padding:"0.15rem 0.4rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"3px",cursor:Se?"default":"pointer",fontSize:"0.65rem",fontWeight:"500",whiteSpace:"nowrap",opacity:Se?.6:1},children:Se?"Adding...":"+ Alias"})]})})()]}),s.jsx("td",{style:Yc,children:ce.supplier_name||"-"}),s.jsx("td",{style:Yc,children:s.jsxs("div",{children:[s.jsxs("div",{children:[Td(ce.most_recent_price),s.jsx("span",{onClick:()=>Ge(ce),style:{marginLeft:"6px",cursor:"pointer"},title:"View price history",children:"📊"})]}),Re(ce)]})}),s.jsx("td",{style:{...Yc,textAlign:"center",padding:"4px"},children:s.jsx("button",{type:"button",onClick:()=>ae(ce),style:{padding:"4px 6px",background:"transparent",border:`1px solid ${ce.ingredient_id?"#28a745":"#ddd"}`,borderRadius:"4px",cursor:"pointer",color:ce.ingredient_id?"#28a745":"#999",fontSize:"16px",lineHeight:1,...ce.ingredient_id?{background:"#e8f5e9"}:{}},title:ce.ingredient_id?`Mapped to: ${ce.ingredient_name} Click to view/edit mapping`:"Click to map to an ingredient",children:"⚖"})}),s.jsx("td",{style:{...Yc,textAlign:"right"},children:ce.ingredient_id?s.jsxs("div",{children:[s.jsx("span",{style:{color:"#16a34a",fontWeight:600},children:Le(ce)||"-"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#6b7280",marginTop:"2px"},children:ce.ingredient_name})]}):s.jsx("span",{style:{color:"#d1d5db"},children:"-"})}),s.jsx("td",{style:Yc,children:Ex(ce.total_quantity)}),s.jsx("td",{style:Yc,children:ce.occurrence_count}),s.jsx("td",{style:Yc,children:s.jsx("a",{href:`/invoice/${ce.most_recent_invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none"},children:ce.most_recent_invoice_number||"-"})}),s.jsx("td",{style:Yc,children:Cm(ce.most_recent_date)})]},`${ce.product_code}-${ce.description}-${ce.supplier_id}-${Je}`))})]})})]}),b&&s.jsx(FK,{isOpen:b.isOpen,onClose:()=>C(null),productCode:b.productCode,description:b.description,unit:b.unit,supplierId:b.supplierId,supplierName:b.supplierName}),T&&s.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:X,children:s.jsxs("div",{style:{background:"#fff",borderRadius:"12px",padding:"1.5rem",width:"650px",maxWidth:"95vw",maxHeight:"90vh",overflowY:"auto"},onClick:ce=>ce.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsx("h3",{style:{margin:0},children:"Ingredient Mapping"}),s.jsx("button",{onClick:X,style:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666"},children:"×"})]}),s.jsxs("div",{style:{padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:T.description||T.product_code||"Unknown item"}),T.supplier_name&&s.jsxs("span",{style:{marginLeft:"0.75rem",color:"#666"},children:["(",T.supplier_name,")"]}),T.most_recent_price!=null&&s.jsxs("span",{style:{marginLeft:"0.75rem",color:"#666"},children:["£",Number(T.most_recent_price).toFixed(2)]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("label",{style:{fontWeight:600,fontSize:"0.9rem",display:"block",marginBottom:"0.5rem"},children:["Ingredient ",I&&s.jsxs("span",{style:{color:"#28a745",fontWeight:"normal"},children:["(",z,")"]})]}),I?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"#d4edda",borderRadius:"6px",border:"1px solid #c3e6cb"},children:[s.jsxs("span",{style:{flex:1},children:[z," ",s.jsxs("span",{style:{color:"#666",fontSize:"0.85rem"},children:["(",te,")"]})]}),s.jsx("button",{onClick:()=>{H(null),G(""),re(""),ye("")},style:{background:"none",border:"none",cursor:"pointer",color:"#666",fontSize:"1.1rem"},children:"×"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{type:"text",value:P,onChange:ce=>{L(ce.target.value),K(ce.target.value)},placeholder:"Search ingredients...",style:{padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"4px",fontSize:"14px",width:"100%",boxSizing:"border-box"}}),U&&s.jsx("span",{style:{position:"absolute",right:"10px",top:"10px",color:"#999"},children:"..."})]}),W.length>0&&s.jsx("div",{style:{border:"1px solid #ddd",borderRadius:"0 0 6px 6px",maxHeight:"200px",overflowY:"auto",background:"#fff"},children:W.map(ce=>s.jsxs("div",{onClick:()=>de(ce),style:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem",display:"flex",justifyContent:"space-between"},onMouseOver:Je=>Je.currentTarget.style.background="#f0f7ff",onMouseOut:Je=>Je.currentTarget.style.background="#fff",children:[s.jsxs("span",{children:[ce.name," ",s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:["(",ce.standard_unit,")"]})]}),s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:[ce.category_name||""," ",ce.similarity?`${(ce.similarity*100).toFixed(0)}%`:""]})]},ce.id))}),s.jsx("button",{onClick:()=>J(!0),style:{marginTop:"0.5rem",padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"+ Create new ingredient"})]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("label",{style:{fontWeight:600,fontSize:"0.9rem",display:"block",marginBottom:"0.25rem"},children:I?`How much ${z} is in this line item?`:"Unit size & pricing"}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#888",marginBottom:"0.5rem"},children:[T.description,T.most_recent_price!=null?` @ £${Number(T.most_recent_price).toFixed(2)}`:""]}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem",alignItems:"flex-end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",display:"block"},children:"Contains"}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",step:"0.1",value:A.unit_size||"",onChange:ce=>{const Je={...A,unit_size:parseFloat(ce.target.value)||null};D(Je),Q(void 0,Je)},onFocus:ce=>ce.target.select(),style:{padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:"4px",width:"70px",fontSize:"14px"},placeholder:"e.g., 2"}),s.jsxs("select",{value:A.unit_size_type||te||"",onChange:ce=>{const Je={...A,unit_size_type:ce.target.value||null};D(Je),Q(void 0,Je)},style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px",width:"60px",fontSize:"14px"},children:[s.jsx("option",{value:"",children:"--"}),s.jsx("option",{value:"each",children:"each"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"}),s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"oz",children:"oz"}),s.jsx("option",{value:"cl",children:"cl"})]}),te&&A.unit_size_type&&A.unit_size_type!==te&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#999"},children:["→ ",te]})]})]}),s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",display:"block"},children:"Pack of"}),s.jsx("input",{type:"number",value:A.pack_quantity||"",onChange:ce=>{const Je={...A,pack_quantity:parseInt(ce.target.value)||null};D(Je),Q(void 0,Je)},onFocus:ce=>ce.target.select(),style:{padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:"4px",width:"50px",fontSize:"14px"},placeholder:"1"})]}),s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",display:"block"},children:"Line Price"}),s.jsx("span",{style:{fontSize:"0.9rem",fontWeight:500},children:A.unit_price?`£${Number(A.unit_price).toFixed(2)}`:"--"})]})]}),ne&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.5rem 0.75rem",background:"#e8f5e9",borderRadius:"6px",fontSize:"0.9rem",color:"#2e7d32",fontWeight:500},children:ne})]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:X,style:{padding:"0.5rem 1.25rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer"},children:"Cancel"}),s.jsx("button",{onClick:pe,disabled:ke,style:{padding:"0.5rem 1.25rem",background:"#28a745",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:ke?.6:1},children:ke?"Saving...":I?"Save & Map Ingredient":"Save"})]})]})}),s.jsx(A0,{open:me,onClose:()=>J(!1),onSaved:Y,prePopulateName:P||"",preSelectLineItem:T?{product_code:T.product_code,description:T.description,supplier_id:T.supplier_id,supplier_name:T.supplier_name,unit:T.unit,most_recent_price:T.most_recent_price!=null?Number(T.most_recent_price):null,total_quantity:T.total_quantity,occurrence_count:T.occurrence_count,most_recent_invoice_id:T.most_recent_invoice_id,most_recent_line_number:T.most_recent_line_number,most_recent_pack_quantity:T.most_recent_pack_quantity,most_recent_unit_size:T.most_recent_unit_size,most_recent_unit_size_type:T.most_recent_unit_size_type,ingredient_id:T.ingredient_id,ingredient_name:T.ingredient_name}:null})]})}const NK={padding:"12px",textAlign:"left",fontWeight:600,fontSize:"14px"},lh={...NK,cursor:"pointer",userSelect:"none"},Yc={padding:"12px",fontSize:"14px"},VN={DRAFT:{bg:"#e0e0e0",color:"#555"},PENDING:{bg:"#e3f2fd",color:"#1565c0"},LINKED:{bg:"#d4edda",color:"#155724"},CLOSED:{bg:"#f5f5f5",color:"#666"},CANCELLED:{bg:"#ffebee",color:"#c62828"}};function Vfe(){var m;const{token:n}=gn(),[e,t]=k.useState("DRAFT,PENDING"),[r,i]=k.useState(""),[o,a]=k.useState(null),[l,d]=k.useState(!1),{data:c}=Oe({queryKey:["suppliers"],queryFn:async()=>{const y=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!y.ok)throw new Error("Failed to fetch suppliers");return y.json()},enabled:!!n}),u=new URLSearchParams;e&&u.append("status",e),r&&u.append("supplier_id",r);const{data:f,refetch:p}=Oe({queryKey:["purchase-orders",e,r],queryFn:async()=>{const y=await fetch(`/api/purchase-orders/?${u}`,{headers:{Authorization:`Bearer ${n}`}});if(!y.ok)throw new Error("Failed to fetch purchase orders");return y.json()},enabled:!!n}),g=y=>new Date(y+"T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"});return s.jsxs("div",{children:[s.jsxs("div",{style:ti.headerRow,children:[s.jsx("h2",{style:ti.pageTitle,children:"Purchase Orders"}),s.jsx("button",{style:ti.newBtn,onClick:()=>d(!0),children:"+ New PO"})]}),s.jsxs("div",{style:ti.filterBar,children:[s.jsx("div",{style:ti.statusTabs,children:[{label:"Open",value:"DRAFT,PENDING"},{label:"All",value:""},{label:"Draft",value:"DRAFT"},{label:"Pending",value:"PENDING"},{label:"Linked",value:"LINKED"},{label:"Closed",value:"CLOSED"}].map(y=>s.jsx("button",{style:{...ti.filterTab,...e===y.value?ti.filterTabActive:{}},onClick:()=>t(y.value),children:y.label},y.value))}),s.jsxs("select",{value:r,onChange:y=>i(y.target.value),style:ti.filterSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),(m=c==null?void 0:c.suppliers)==null?void 0:m.map(y=>s.jsx("option",{value:y.id,children:y.name},y.id))]})]}),s.jsx("div",{style:ti.tableContainer,children:s.jsxs("table",{style:ti.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:ti.th,children:"Date"}),s.jsx("th",{style:ti.th,children:"Supplier"}),s.jsx("th",{style:ti.th,children:"Type"}),s.jsx("th",{style:ti.th,children:"Reference"}),s.jsx("th",{style:{...ti.th,textAlign:"right"},children:"Total"}),s.jsx("th",{style:ti.th,children:"Status"}),s.jsx("th",{style:ti.th,children:"Created"})]})}),s.jsx("tbody",{children:!f||f.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:7,style:ti.emptyTd,children:"No purchase orders found"})}):f.map(y=>{const v=VN[y.status]||VN.DRAFT;return s.jsxs("tr",{style:ti.row,onClick:()=>a(y.id),children:[s.jsx("td",{style:ti.td,children:g(y.order_date)}),s.jsx("td",{style:ti.td,children:y.supplier_name||"-"}),s.jsx("td",{style:ti.td,children:s.jsx("span",{style:ti.typeBadge,children:y.order_type==="itemised"?"Itemised":"Single Value"})}),s.jsx("td",{style:ti.td,children:y.order_reference||"-"}),s.jsx("td",{style:{...ti.td,textAlign:"right",fontWeight:500},children:y.total_amount!=null?`£${y.total_amount.toFixed(2)}`:"-"}),s.jsx("td",{style:ti.td,children:s.jsx("span",{style:{...ti.statusBadge,background:v.bg,color:v.color},children:y.status})}),s.jsx("td",{style:{...ti.td,fontSize:"0.8rem",color:"#888"},children:y.created_by_name||""})]},y.id)})})]})}),s.jsx(TT,{isOpen:!!o,onClose:()=>a(null),onSaved:()=>p(),poId:o}),s.jsx(TT,{isOpen:l,onClose:()=>d(!1),onSaved:()=>p()})]})}const ti={headerRow:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},pageTitle:{margin:0,color:"#1a1a2e"},newBtn:{padding:"0.6rem 1.2rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},filterBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem",gap:"1rem",flexWrap:"wrap"},statusTabs:{display:"flex",gap:"0.25rem"},filterTab:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",background:"white",cursor:"pointer",fontSize:"0.85rem",fontWeight:500},filterTabActive:{background:"#1a1a2e",color:"white",borderColor:"#1a1a2e"},filterSelect:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.85rem"},tableContainer:{background:"white",borderRadius:"8px",boxShadow:"0 1px 4px rgba(0,0,0,0.08)",overflow:"auto"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"0.75rem 1rem",borderBottom:"2px solid #eee",fontWeight:600,color:"#666",fontSize:"0.85rem",whiteSpace:"nowrap"},td:{padding:"0.75rem 1rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},emptyTd:{padding:"2rem",textAlign:"center",color:"#999"},row:{cursor:"pointer",transition:"background 0.15s"},statusBadge:{display:"inline-block",padding:"0.2rem 0.6rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:600},typeBadge:{fontSize:"0.8rem",color:"#666"}};function T0({flags:n,size:e="small",source_ingredients:t}){const r=n.filter(a=>(a.active??a.is_active)!==!1);if(!r.length)return null;const i=e==="small"?"0.7rem":"0.8rem",o=e==="small"?"1px 5px":"2px 8px";return s.jsx("div",{style:GN.container,children:r.map((a,l)=>{const d=a.name||a.flag_name||"",c=a.code||a.flag_code||"",u=a.icon||a.flag_icon||"",f=a.propagation||a.propagation_type||"contains",p=a.excludable??a.excludable_on_request??!1,g=f==="contains"?"#dc3545":"#28a745",m=t==null?void 0:t[d];let y=d;return m&&m.length>0&&(y+=` — from: ${m.join(", ")}`),p&&(y+=" (excludable on request)"),s.jsxs("span",{title:y,style:{...GN.badge,background:g,fontSize:i,padding:o,border:p?"1.5px dashed rgba(255,255,255,0.6)":"none",opacity:p?.85:1},children:[u?`${u} `:"",c||d.substring(0,3)]},l)})})}const GN={container:{display:"flex",flexWrap:"wrap",gap:"3px",alignItems:"center"},badge:{display:"inline-block",borderRadius:"10px",color:"white",fontWeight:600,whiteSpace:"nowrap",lineHeight:1.4}};function Gfe(){const{token:n}=gn(),e=pi(),[t,r]=k.useState(""),[i,o]=k.useState(""),[a,l]=k.useState(!1),[d,c]=k.useState(!1),[u,f]=k.useState(null),[p,g]=k.useState(!1),[m,y]=k.useState(null),{data:v}=Oe({queryKey:["ingredient-categories"],queryFn:async()=>{const T=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${n}`}});if(!T.ok)throw new Error("Failed to fetch categories");return T.json()},enabled:!!n}),{data:x,isLoading:w}=Oe({queryKey:["ingredients",t,i,a,d],queryFn:async()=>{const T=new URLSearchParams;t&&T.set("search",t),i&&T.set("category_id",i),a&&T.set("unmapped","true"),d&&T.set("archived","true");const F=await fetch(`/api/ingredients?${T}`,{headers:{Authorization:`Bearer ${n}`}});if(!F.ok)throw new Error("Failed to fetch ingredients");return F.json()},enabled:!!n}),{data:S}=Oe({queryKey:["ingredient-sources",u],queryFn:async()=>{const T=await fetch(`/api/ingredients/${u}/sources`,{headers:{Authorization:`Bearer ${n}`}});if(!T.ok)throw new Error("Failed to fetch sources");return T.json()},enabled:!!n&&!!u}),_=Ue({mutationFn:async T=>{if(!(await fetch(`/api/ingredients/${T}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to archive")},onSuccess:()=>e.invalidateQueries({queryKey:["ingredients"]})}),b=Ue({mutationFn:async T=>{if(!(await fetch(`/api/ingredients/${T}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_archived:!1})})).ok)throw new Error("Failed to unarchive")},onSuccess:()=>e.invalidateQueries({queryKey:["ingredients"]})}),C=T=>{y({id:T.id,name:T.name,category_id:T.category_id,standard_unit:T.standard_unit,yield_percent:T.yield_percent,manual_price:T.manual_price,notes:T.notes,is_prepackaged:T.is_prepackaged,is_free:T.is_free,product_ingredients:T.product_ingredients,has_label_image:T.has_label_image}),g(!0)};return s.jsxs("div",{style:vn.page,children:[s.jsxs("div",{style:vn.header,children:[s.jsx("h2",{style:{margin:0},children:"Ingredient Library"}),s.jsx("button",{onClick:()=>{y(null),g(!0)},style:vn.primaryBtn,children:"+ Create Ingredient"})]}),s.jsxs("div",{style:vn.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search ingredients...",value:t,onChange:T=>r(T.target.value),style:vn.searchInput}),s.jsxs("select",{value:i,onChange:T=>o(T.target.value),style:vn.select,children:[s.jsx("option",{value:"",children:"All Categories"}),v==null?void 0:v.map(T=>s.jsxs("option",{value:T.id,children:[T.name," (",T.ingredient_count,")"]},T.id))]}),s.jsxs("label",{style:vn.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:a,onChange:T=>l(T.target.checked)}),"Unmapped only"]}),s.jsxs("label",{style:vn.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:d,onChange:T=>c(T.target.checked)}),"Show Archived"]})]}),s.jsxs("div",{style:vn.statsBar,children:[s.jsxs("span",{children:[(x==null?void 0:x.length)||0," ",d?"archived":""," ingredients"]}),s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{children:[(x==null?void 0:x.filter(T=>T.source_count===0).length)||0," unmapped"]})]}),w?s.jsx("div",{style:vn.loading,children:"Loading ingredients..."}):s.jsxs("table",{style:vn.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:vn.th,children:"Name"}),s.jsx("th",{style:vn.th,children:"Category"}),s.jsx("th",{style:vn.th,children:"Unit"}),s.jsx("th",{style:vn.th,children:"Yield %"}),s.jsx("th",{style:vn.th,children:"Sources"}),s.jsx("th",{style:vn.th,children:"Price/Unit"}),s.jsx("th",{style:vn.th,children:"Flags"}),s.jsx("th",{style:vn.th,children:"Actions"})]})}),s.jsx("tbody",{children:x==null?void 0:x.map(T=>{var F;return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{style:{...vn.tr,cursor:"pointer",...T.is_archived?{opacity:.5}:{}},onClick:()=>f(u===T.id?null:T.id),children:[s.jsxs("td",{style:vn.td,children:[s.jsx("span",{style:{fontWeight:500,...T.is_archived?{textDecoration:"line-through"}:{}},children:T.name}),T.is_archived&&s.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.7rem",color:"#999",fontStyle:"italic"},children:"archived"})]}),s.jsx("td",{style:vn.td,children:T.category_name||"-"}),s.jsx("td",{style:vn.td,children:T.standard_unit}),s.jsx("td",{style:vn.td,children:s.jsxs("span",{style:{color:T.yield_percent<100?"#e94560":"#666"},children:[T.yield_percent,"%"]})}),s.jsx("td",{style:vn.td,children:s.jsx("span",{style:{background:T.source_count>0?"#22c55e":"#f59e0b",color:"white",padding:"2px 8px",borderRadius:"10px",fontSize:"0.75rem",fontWeight:600},children:T.source_count})}),s.jsx("td",{style:vn.td,children:T.effective_price!=null?(()=>{const A=T.effective_price,D=T.standard_unit;return D==="g"&&A<1?`£${(A*1e3).toFixed(2)}/kg`:D==="ml"&&A<1?`£${(A*1e3).toFixed(2)}/ltr`:`£${A>=1?A.toFixed(2):A.toFixed(4)}/${D}`})():s.jsx("span",{style:{color:"#aaa"},children:"-"})}),s.jsx("td",{style:vn.td,children:s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"3px",alignItems:"center"},children:[s.jsx(T0,{flags:T.flags.map(A=>({name:A.flag_name,code:A.flag_code||void 0,category_name:A.category_name,propagation:A.propagation_type}))}),(F=T.none_categories)==null?void 0:F.map(A=>s.jsxs("span",{title:`${A}: None apply`,style:{display:"inline-block",borderRadius:"10px",color:"white",fontWeight:600,whiteSpace:"nowrap",lineHeight:1.4,fontSize:"0.7rem",padding:"1px 5px",background:"#999"},children:[A.substring(0,3),": None"]},A))]})}),s.jsxs("td",{style:vn.td,children:[s.jsx("button",{onClick:A=>{A.stopPropagation(),C(T)},style:vn.smallBtn,children:"Edit"}),T.is_archived?s.jsx("button",{onClick:A=>{A.stopPropagation(),b.mutate(T.id)},style:{...vn.smallBtn,color:"#22c55e"},children:"Unarchive"}):s.jsx("button",{onClick:A=>{A.stopPropagation(),_.mutate(T.id)},style:{...vn.smallBtn,color:"#e94560"},children:"Archive"})]})]},T.id),u===T.id&&s.jsx("tr",{children:s.jsx("td",{colSpan:8,style:vn.expandedTd,children:s.jsxs("div",{style:vn.sourcesSection,children:[s.jsx("h4",{style:{margin:"0 0 8px 0"},children:"Supplier Sources"}),S&&S.length>0?s.jsxs("table",{style:{...vn.table,margin:0},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:vn.thSmall,children:"Supplier"}),s.jsx("th",{style:vn.thSmall,children:"Code/Pattern"}),s.jsx("th",{style:vn.thSmall,children:"Pack"}),s.jsx("th",{style:vn.thSmall,children:"Last Price"}),s.jsxs("th",{style:vn.thSmall,children:["Price/",T.standard_unit]}),s.jsx("th",{style:vn.thSmall,children:"Last Invoice"})]})}),s.jsx("tbody",{children:S.map(A=>{var D;return s.jsxs("tr",{children:[s.jsx("td",{style:vn.tdSmall,children:A.supplier_name}),s.jsx("td",{style:vn.tdSmall,children:A.product_code&&((D=A.supplier_name)!=null&&D.toLowerCase().includes("brakes"))?s.jsx("a",{href:`https://www.brake.co.uk/p/${A.product_code}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"underline"},title:"View on Brakes website",children:A.product_code}):A.product_code||A.description_pattern||"-"}),s.jsx("td",{style:vn.tdSmall,children:A.pack_quantity&&A.unit_size?`${A.pack_quantity}×${A.unit_size}${A.unit_size_type||""}`:"-"}),s.jsx("td",{style:vn.tdSmall,children:A.latest_unit_price!=null?`£${A.latest_unit_price.toFixed(2)}`:"-"}),s.jsx("td",{style:vn.tdSmall,children:A.price_per_std_unit!=null?(()=>{const P=typeof A.price_per_std_unit=="string"?parseFloat(A.price_per_std_unit):A.price_per_std_unit,L=T.standard_unit;return L==="g"&&P<1?`£${(P*1e3).toFixed(2)}/kg`:L==="ml"&&P<1?`£${(P*1e3).toFixed(2)}/ltr`:`£${P>=1?P.toFixed(2):P.toFixed(4)}/${L}`})():"-"}),s.jsx("td",{style:vn.tdSmall,children:A.latest_invoice_date||"-"})]},A.id)})})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic"},children:"No supplier sources mapped yet"})]})})},`${T.id}-expanded`)]})})})]}),s.jsx(A0,{open:p,onClose:()=>{g(!1),y(null)},editingIngredient:m})]})}const vn={page:{padding:"1.5rem",maxWidth:"1400px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},checkLabel:{display:"flex",alignItems:"center",gap:"0.35rem",fontSize:"0.9rem",color:"#555"},statsBar:{display:"flex",gap:"0.75rem",fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},thSmall:{padding:"0.4rem 0.5rem",textAlign:"left",borderBottom:"1px solid #e0e0e0",background:"#f5f5f5",fontSize:"0.75rem",fontWeight:600,color:"#666"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},tdSmall:{padding:"0.35rem 0.5rem",fontSize:"0.8rem"},expandedTd:{padding:"0.75rem 1rem",background:"#f9f9f9"},sourcesSection:{padding:"0.5rem"},smallBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem",marginRight:"0.25rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},loading:{padding:"2rem",textAlign:"center",color:"#888"}};function Kfe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(""),[o,a]=k.useState(""),[l,d]=k.useState(!1),[c,u]=k.useState(!1),[f,p]=k.useState("list"),[g,m]=k.useState(!1),[y,v]=k.useState(!1),[x,w]=k.useState(""),[S,_]=k.useState(""),[b,C]=k.useState(""),[T,F]=k.useState({}),[A,D]=k.useState(null),[P,L]=k.useState(""),[W,O]=k.useState(""),[U,M]=k.useState(""),[I,H]=k.useState("1"),[z,G]=k.useState("portions"),[te,re]=k.useState(""),[me,J]=k.useState("ml"),[ne,ye]=k.useState(""),[ke,Ye]=k.useState(""),{data:De}=Oe({queryKey:["recipe-sections"],queryFn:async()=>{const K=await fetch("/api/recipes/menu-sections?section_type=recipe",{headers:{Authorization:`Bearer ${n}`}});if(!K.ok)throw new Error("Failed to fetch sections");return K.json()},enabled:!!n}),{data:qe,isLoading:ue}=Oe({queryKey:["recipes",r,o,y],queryFn:async()=>{const K=new URLSearchParams;K.set("recipe_type","component"),r&&K.set("search",r),o&&K.set("menu_section_id",o),y&&K.set("archived","true");const de=await fetch(`/api/recipes?${K}`,{headers:{Authorization:`Bearer ${n}`}});if(!de.ok)throw new Error("Failed to fetch recipes");return de.json()},enabled:!!n}),Ze=Ue({mutationFn:async K=>{const de=await fetch("/api/recipes",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(K)});if(!de.ok)throw new Error("Failed to create recipe");return de.json()},onSuccess:K=>{t.invalidateQueries({queryKey:["recipes"]}),d(!1),e(`/recipes/${K.id}`)}}),ee=Ue({mutationFn:async K=>{const de=await fetch(`/api/recipes/${K}/duplicate`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!de.ok)throw new Error("Failed to duplicate");return de.json()},onSuccess:K=>{t.invalidateQueries({queryKey:["recipes"]}),e(`/recipes/${K.id}`)}}),Z=Ue({mutationFn:async K=>{if(!(await fetch(`/api/recipes/${K}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to archive")},onSuccess:()=>t.invalidateQueries({queryKey:["recipes"]})}),ge=Ue({mutationFn:async K=>{if(!(await fetch(`/api/recipes/${K}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_archived:!1})})).ok)throw new Error("Failed to unarchive")},onSuccess:()=>t.invalidateQueries({queryKey:["recipes"]})}),Te=Ue({mutationFn:async K=>{const de=await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:K,section_type:"recipe"})});if(!de.ok)throw new Error("Failed to create section");return de.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["recipe-sections"]}),Ye(""),u(!1)}}),Be=Ue({mutationFn:async({id:K,name:de})=>{const Y=await fetch(`/api/recipes/menu-sections/${K}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:de})});if(!Y.ok)throw new Error("Failed to update section");return Y.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["recipe-sections"]}),t.invalidateQueries({queryKey:["recipes"]}),D(null),L("")}}),he=Ue({mutationFn:async K=>{const de=await fetch(`/api/recipes/menu-sections/${K}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!de.ok)throw new Error("Failed to delete section");return de.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["recipe-sections"]}),t.invalidateQueries({queryKey:["recipes"]})}}),{data:He}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const K=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${n}`}});if(!K.ok)throw new Error("Failed to fetch flag categories");return K.json()},enabled:!!n&&g}),Ge=(()=>{let K=qe||[];if(x.trim()){const Q=x.toLowerCase();K=K.filter(X=>X.name.toLowerCase().includes(Q)||X.flag_summary.some(pe=>pe.name.toLowerCase().includes(Q)))}if(S){const Q=parseFloat(S);isNaN(Q)||(K=K.filter(X=>X.cost_per_portion!=null&&X.cost_per_portion>=Q))}if(b){const Q=parseFloat(b);isNaN(Q)||(K=K.filter(X=>X.cost_per_portion!=null&&X.cost_per_portion<=Q))}const de=Object.entries(T).filter(([,Q])=>Q==="include").map(([Q])=>Q),Y=Object.entries(T).filter(([,Q])=>Q==="exclude").map(([Q])=>Q);return de.length>0&&(K=K.filter(Q=>de.every(X=>Q.flag_summary.some(pe=>pe.name===X&&pe.active)))),Y.length>0&&(K=K.filter(Q=>!Y.some(X=>Q.flag_summary.some(pe=>pe.name===X&&pe.active)))),K})(),ae=()=>{Ze.mutate({name:W,recipe_type:"component",menu_section_id:U?parseInt(U):null,batch_portions:z==="portions"&&parseInt(I)||1,batch_output_type:z,batch_yield_qty:z==="bulk"&&parseFloat(te)||null,batch_yield_unit:z==="bulk"?me:null,description:ne||null})};return s.jsxs("div",{style:wt.page,children:[s.jsxs("div",{style:wt.header,children:[s.jsx("h2",{style:{margin:0},children:"Recipes"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>u(!0),style:wt.secondaryBtn,children:"+ Section"}),s.jsx("button",{onClick:()=>{d(!0),O(""),M(""),H("1"),G("portions"),re(""),J("ml"),ye("")},style:wt.primaryBtn,children:"+ New Recipe"})]})]}),s.jsx("div",{style:wt.statsBar,children:s.jsxs("span",{children:[Ge.length," ",y?"archived ":"","recipes"]})}),s.jsxs("div",{style:wt.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search recipes...",value:r,onChange:K=>i(K.target.value),style:wt.searchInput}),s.jsxs("select",{value:o,onChange:K=>a(K.target.value),style:wt.select,children:[s.jsx("option",{value:"",children:"All Sections"}),De==null?void 0:De.map(K=>s.jsxs("option",{value:K.id,children:[K.name," (",K.recipe_count,")"]},K.id))]}),s.jsxs("label",{style:wt.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:y,onChange:K=>v(K.target.checked)}),"Show Archived"]}),s.jsx("button",{onClick:()=>m(!g),style:{...wt.secondaryBtn,padding:"0.5rem 0.75rem",fontSize:"0.85rem"},children:g?"Hide Filters":"Show Filters"}),s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"2px"},children:[s.jsx("button",{onClick:()=>p("card"),style:{...wt.viewToggleBtn,...f==="card"?wt.viewToggleBtnActive:{},borderRadius:"4px 0 0 4px"},children:"Cards"}),s.jsx("button",{onClick:()=>p("list"),style:{...wt.viewToggleBtn,...f==="list"?wt.viewToggleBtnActive:{},borderRadius:"0 4px 4px 0"},children:"List"})]})]}),g&&s.jsx("div",{style:wt.advancedFilterPanel,children:s.jsxs("div",{style:{display:"flex",gap:"1rem",flexWrap:"wrap",alignItems:"flex-start"},children:[s.jsxs("div",{style:{minWidth:"200px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Contains ingredient"}),s.jsx("input",{type:"text",placeholder:"Search by ingredient...",value:x,onChange:K=>w(K.target.value),style:{...wt.searchInput,width:"100%"}})]}),s.jsxs("div",{style:{minWidth:"150px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Cost/portion range"}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",placeholder:"Min",value:S,onChange:K=>_(K.target.value),style:{...wt.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"}),s.jsx("span",{style:{color:"#888"},children:"-"}),s.jsx("input",{type:"number",placeholder:"Max",value:b,onChange:K=>C(K.target.value),style:{...wt.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"})]})]}),He&&He.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"250px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Food flag filters"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:He.flatMap(K=>K.flags||[]).map(K=>{const de=T[K.name]||"neutral",Y=de==="neutral"?"include":de==="include"?"exclude":"neutral";return s.jsxs("button",{onClick:()=>F(Q=>{const X={...Q};return Y==="neutral"?delete X[K.name]:X[K.name]=Y,X}),style:{padding:"2px 8px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:600,cursor:"pointer",border:"1px solid",borderColor:de==="include"?"#22c55e":de==="exclude"?"#ef4444":"#ddd",background:de==="include"?"#dcfce7":de==="exclude"?"#fef2f2":"white",color:de==="include"?"#166534":de==="exclude"?"#991b1b":"#666"},title:`${K.name}: ${de} (click to cycle)`,children:[de==="include"?"+ ":de==="exclude"?"- ":"",K.code||K.name]},K.id)})})]})]})}),ue?s.jsx("div",{style:wt.loading,children:"Loading recipes..."}):f==="card"?s.jsx("div",{style:wt.grid,children:Ge.map(K=>s.jsxs("div",{style:{...wt.card,...K.is_archived?{opacity:.6}:{}},onClick:()=>e(`/recipes/${K.id}`),children:[s.jsxs("div",{style:wt.cardHeader,children:[s.jsx("span",{style:{fontWeight:600,fontSize:"1rem",...K.is_archived?{textDecoration:"line-through"}:{}},children:K.name}),s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[K.is_archived&&s.jsx("span",{style:{background:"#999",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"ARCHIVED"}),s.jsx("span",{style:{background:"#8b5cf6",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"RECIPE"})]})]}),K.menu_section_name&&s.jsx("div",{style:wt.sectionTag,children:K.menu_section_name}),(K.batch_output_type==="bulk"||K.batch_portions>1)&&s.jsx("div",{style:{fontSize:"0.8rem",color:"#666",marginTop:"4px"},children:K.batch_output_type==="bulk"?`Yield: ${K.batch_yield_qty}${K.batch_yield_unit}`:`Batch: ${K.batch_portions} portions`}),s.jsxs("div",{style:wt.cardMeta,children:[K.cost_per_portion!=null?s.jsxs("span",{style:wt.costBadge,children:["£",K.cost_per_portion.toFixed(K.batch_output_type==="bulk"?4:2),"/",K.output_unit||"portion"]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"No costing"}),(K.prep_time_minutes||K.cook_time_minutes)&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:[K.prep_time_minutes?`${K.prep_time_minutes}m prep`:"",K.prep_time_minutes&&K.cook_time_minutes?" + ":"",K.cook_time_minutes?`${K.cook_time_minutes}m cook`:""]})]}),K.flag_summary.length>0&&s.jsx("div",{style:{marginTop:"6px"},children:s.jsx(T0,{flags:K.flag_summary})}),s.jsxs("div",{style:wt.cardActions,children:[s.jsx("button",{onClick:de=>{de.stopPropagation(),ee.mutate(K.id)},style:wt.actionBtn,children:"Duplicate"}),K.is_archived?s.jsx("button",{onClick:de=>{de.stopPropagation(),ge.mutate(K.id)},style:{...wt.actionBtn,color:"#22c55e"},children:"Restore"}):s.jsx("button",{onClick:de=>{de.stopPropagation(),Z.mutate(K.id)},style:{...wt.actionBtn,color:"#e94560"},children:"Archive"})]})]},K.id))}):s.jsxs("table",{style:wt.listTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:wt.listTh,children:"Name"}),s.jsx("th",{style:wt.listTh,children:"Type"}),s.jsx("th",{style:wt.listTh,children:"Section"}),s.jsx("th",{style:wt.listTh,children:"Output"}),s.jsx("th",{style:wt.listTh,children:"Cost/Unit"}),s.jsx("th",{style:wt.listTh,children:"Flags"}),s.jsx("th",{style:wt.listTh,children:"Actions"})]})}),s.jsx("tbody",{children:Ge.map(K=>s.jsxs("tr",{style:{...wt.listTr,cursor:"pointer",...K.is_archived?{opacity:.6}:{}},onClick:()=>e(`/recipes/${K.id}`),children:[s.jsxs("td",{style:wt.listTd,children:[s.jsx("span",{style:{fontWeight:500,...K.is_archived?{textDecoration:"line-through"}:{}},children:K.name}),K.is_archived&&s.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.7rem",color:"#999",fontStyle:"italic"},children:"archived"})]}),s.jsx("td",{style:wt.listTd,children:s.jsx("span",{style:{background:"#8b5cf6",color:"white",padding:"1px 6px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"RECIPE"})}),s.jsx("td",{style:wt.listTd,children:K.menu_section_name||"-"}),s.jsx("td",{style:wt.listTd,children:K.batch_output_type==="bulk"?`${K.batch_yield_qty}${K.batch_yield_unit}`:K.batch_portions}),s.jsx("td",{style:wt.listTd,children:K.cost_per_portion!=null?s.jsxs("span",{style:wt.costBadge,children:["£",K.cost_per_portion.toFixed(K.batch_output_type==="bulk"?4:2),"/",K.output_unit||"portion"]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"})}),s.jsx("td",{style:wt.listTd,children:K.flag_summary.length>0&&s.jsx(T0,{flags:K.flag_summary})}),s.jsxs("td",{style:wt.listTd,children:[s.jsx("button",{onClick:de=>{de.stopPropagation(),ee.mutate(K.id)},style:wt.actionBtn,children:"Duplicate"}),K.is_archived?s.jsx("button",{onClick:de=>{de.stopPropagation(),ge.mutate(K.id)},style:{...wt.actionBtn,color:"#22c55e",marginLeft:"4px"},children:"Restore"}):s.jsx("button",{onClick:de=>{de.stopPropagation(),Z.mutate(K.id)},style:{...wt.actionBtn,color:"#e94560",marginLeft:"4px"},children:"Archive"})]})]},K.id))})]}),l&&s.jsx("div",{style:wt.overlay,children:s.jsxs("div",{style:wt.modal,children:[s.jsxs("div",{style:wt.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"New Recipe"}),s.jsx("button",{onClick:()=>d(!1),style:wt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:wt.modalBody,children:[s.jsx("label",{style:wt.label,children:"Name *"}),s.jsx("input",{value:W,onChange:K=>O(K.target.value),style:wt.input,placeholder:"e.g. Hollandaise Sauce, Pastry Base"}),s.jsx("label",{style:wt.label,children:"Section"}),s.jsxs("select",{value:U,onChange:K=>M(K.target.value),style:wt.input,children:[s.jsx("option",{value:"",children:"None"}),De==null?void 0:De.map(K=>s.jsx("option",{value:K.id,children:K.name},K.id))]}),s.jsx("label",{style:wt.label,children:"Output Type"}),s.jsxs("select",{value:z,onChange:K=>G(K.target.value),style:wt.input,children:[s.jsx("option",{value:"portions",children:"Portioned"}),s.jsx("option",{value:"bulk",children:"Bulk (volume/weight)"})]}),z==="portions"?s.jsxs(s.Fragment,{children:[s.jsx("label",{style:wt.label,children:"Batch Portions"}),s.jsx("input",{type:"number",value:I,onChange:K=>H(K.target.value),style:wt.input,min:"1"})]}):s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("label",{style:wt.label,children:"Yield Quantity"}),s.jsx("input",{type:"number",value:te,onChange:K=>re(K.target.value),style:wt.input,step:"0.1",min:"0.1",placeholder:"e.g. 500"})]}),s.jsxs("div",{style:{width:"90px"},children:[s.jsx("label",{style:wt.label,children:"Unit"}),s.jsxs("select",{value:me,onChange:K=>J(K.target.value),style:wt.input,children:[s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"})]})]})]}),s.jsx("label",{style:wt.label,children:"Description"}),s.jsx("textarea",{value:ne,onChange:K=>ye(K.target.value),style:{...wt.input,minHeight:"60px"},placeholder:"Brief description..."})]}),s.jsxs("div",{style:wt.modalFooter,children:[s.jsx("button",{onClick:()=>d(!1),style:wt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:ae,disabled:!W||Ze.isPending,style:wt.primaryBtn,children:Ze.isPending?"Creating...":"Create Recipe"})]})]})}),c&&s.jsx("div",{style:wt.overlay,children:s.jsxs("div",{style:{...wt.modal,width:"450px"},children:[s.jsxs("div",{style:wt.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Manage Recipe Sections"}),s.jsx("button",{onClick:()=>{u(!1),D(null)},style:wt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:wt.modalBody,children:[De&&De.length>0&&s.jsx("div",{style:{marginBottom:"1rem"},children:De.map(K=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.4rem 0",borderBottom:"1px solid #f0f0f0"},children:A===K.id?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:P,onChange:de=>L(de.target.value),style:{...wt.input,flex:1},autoFocus:!0}),s.jsx("button",{onClick:()=>Be.mutate({id:K.id,name:P}),disabled:!P.trim(),style:{...wt.actionBtn,color:"#22c55e"},children:"Save"}),s.jsx("button",{onClick:()=>{D(null),L("")},style:wt.actionBtn,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:"0.9rem"},children:K.name}),s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:["(",K.recipe_count,")"]}),s.jsx("button",{onClick:()=>{D(K.id),L(K.name)},style:wt.actionBtn,children:"Edit"}),s.jsx("button",{onClick:()=>{confirm(`Delete section "${K.name}"? Recipes in this section will be unassigned.`)&&he.mutate(K.id)},style:{...wt.actionBtn,color:"#e94560"},children:"Delete"})]})},K.id))}),s.jsx("label",{style:wt.label,children:"Add New Section"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{value:ke,onChange:K=>Ye(K.target.value),style:{...wt.input,flex:1},placeholder:"e.g. Protein, Garnish, Pastry, Baked"}),s.jsx("button",{onClick:()=>Te.mutate(ke),disabled:!ke,style:wt.primaryBtn,children:"Add"})]})]}),s.jsx("div",{style:wt.modalFooter,children:s.jsx("button",{onClick:()=>{u(!1),D(null)},style:wt.cancelBtn,children:"Close"})})]})})]})}const wt={page:{padding:"1.5rem",maxWidth:"1400px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},statsBar:{display:"flex",gap:"0.75rem",fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},checkLabel:{display:"flex",alignItems:"center",gap:"0.35rem",fontSize:"0.85rem",color:"#555",cursor:"pointer",whiteSpace:"nowrap"},grid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:"1rem"},card:{background:"white",borderRadius:"8px",padding:"1rem",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",cursor:"pointer",transition:"box-shadow 0.2s",border:"1px solid #eee"},cardHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"0.5rem"},sectionTag:{fontSize:"0.75rem",color:"#888",marginTop:"2px"},cardMeta:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"8px"},costBadge:{background:"#f0fdf4",color:"#166534",padding:"2px 8px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},cardActions:{display:"flex",gap:"0.5rem",marginTop:"10px",borderTop:"1px solid #f0f0f0",paddingTop:"8px"},actionBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},secondaryBtn:{padding:"0.6rem 1.25rem",background:"white",color:"#333",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},viewToggleBtn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",background:"white",cursor:"pointer",fontSize:"0.8rem",color:"#666"},viewToggleBtnActive:{background:"#e94560",color:"white",borderColor:"#e94560"},advancedFilterPanel:{background:"#fafafa",border:"1px solid #eee",borderRadius:"8px",padding:"1rem",marginBottom:"1rem"},listTable:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},listTh:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},listTr:{borderBottom:"1px solid #f0f0f0"},listTd:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"}};function WK({recipeId:n,categoryId:e}){const{token:t}=gn(),r=pi(),[i,o]=k.useState(new Set),{data:a,isLoading:l}=Oe({queryKey:["recipe-flag-matrix",n],queryFn:async()=>{const S=await fetch(`/api/food-flags/recipes/${n}/flags/matrix`,{headers:{Authorization:`Bearer ${t}`}});if(!S.ok)throw new Error("Failed to fetch matrix");return S.json()},enabled:!!t&&!!n}),d=a?{flags:e?a.flags.filter(S=>S.category_id===e):a.flags,ingredients:a.ingredients}:void 0,c=Ue({mutationFn:async({ingredientId:S,flagId:_,hasFlag:b})=>{if(!(await fetch(`/api/food-flags/recipes/${n}/flags/matrix`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({updates:[{ingredient_id:S,food_flag_id:_,has_flag:b}]})})).ok)throw new Error("Failed to update flag")},onMutate:({ingredientId:S,flagId:_})=>{o(b=>new Set(b).add(`${S}-${_}`))},onSettled:(S,_,{ingredientId:b,flagId:C})=>{o(T=>{const F=new Set(T);return F.delete(`${b}-${C}`),F}),r.invalidateQueries({queryKey:["recipe-flag-matrix",n]}),r.invalidateQueries({queryKey:["recipe-flags",n]}),r.invalidateQueries({queryKey:["ingredients"]})}}),u=Ue({mutationFn:async({ingredientId:S,catId:_})=>{if(!(await fetch(`/api/food-flags/recipes/${n}/flags/matrix/none`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_id:S,category_id:_})})).ok)throw new Error("Failed to toggle none")},onSettled:()=>{r.invalidateQueries({queryKey:["recipe-flag-matrix",n]}),r.invalidateQueries({queryKey:["recipe-flags",n]}),r.invalidateQueries({queryKey:["ingredients"]})}});if(l)return s.jsx("div",{style:{padding:"1rem",color:"#888"},children:"Loading matrix..."});if(!d||!d.flags.length)return s.jsx("div",{style:{padding:"1rem",color:"#888"},children:"No flags configured for this category"});const f={};for(const S of d.flags)f[S.category_id]||(f[S.category_id]={name:S.category_name,propagation:S.propagation_type,required:S.required,flags:[]}),f[S.category_id].flags.push(S);let p="";const g=[];for(const S of d.ingredients)S.is_sub_recipe&&S.sub_recipe_name!==p?(p=S.sub_recipe_name||"",g.push({type:"header",label:`▸ ${p}`})):!S.is_sub_recipe&&p&&(p=""),g.push({type:"ingredient",label:S.is_sub_recipe?` ↳ ${S.ingredient_name}`:S.ingredient_name,ingredient:S});const m={};for(const S of d.flags)if(f[S.category_id].propagation==="contains"){const b=d.ingredients.some(C=>{var T;return(T=C.flags[S.id])==null?void 0:T.has_flag});m[S.id]={has:b,unassessed:!1}}else{const b=d.ingredients.every(T=>{var F;return(F=T.flags[S.id])==null?void 0:F.has_flag}),C=d.ingredients.some(T=>{var F;return(F=T.flags[S.id])==null?void 0:F.is_unassessed});m[S.id]={has:b&&!C,unassessed:C}}const y=(S,_)=>{var C;const b=((C=f[_])==null?void 0:C.flags)||[];return b.length>0&&b.every(T=>{var F;return(F=S.flags[T.id])==null?void 0:F.is_none})},v=(S,_,b)=>{c.mutate({ingredientId:S,flagId:_,hasFlag:!b})},x=(S,_,b,C,T)=>{const F=i.has(`${S}-${_}`),A=(b==null?void 0:b.has_flag)??!1,D=(b==null?void 0:b.is_unassessed)??!1,P=(b==null?void 0:b.is_none)??!1,L=(b==null?void 0:b.has_open_suggestion)??!1,W={...Oa.cell,cursor:"pointer",opacity:F?.5:1,transition:"background 0.15s",position:"relative"},O=L&&!A&&!D?s.jsx("span",{style:{position:"absolute",top:"2px",right:"2px",width:"6px",height:"6px",borderRadius:"50%",background:"#f59e0b"},title:"Unreviewed allergen suggestion"}):null,U=()=>{F||(D?v(S,_,!1):v(S,_,A))};return D?s.jsxs("td",{style:{...W,color:"#f59e0b"},title:"Unassessed \\u2014 click to assess",onClick:U,children:["❓",O]}):P?s.jsxs("td",{style:{...W,color:"#94a3b8",background:"#f8fafc"},title:`None apply — click to set ${T||"this flag"}`,onClick:U,children:["—",O]}):C==="contains"?s.jsxs("td",{style:{...W,color:A?"#dc3545":"#ccc",background:A?"#fef2f2":L?"#fffbeb":void 0},title:A?`Contains ${T||""} — click to remove`:L?`Unreviewed suggestion: ${T||""} — click to set`:`Click to mark as contains ${T||""}`,onClick:U,children:[A?"✓":"·",O]}):s.jsxs("td",{style:{...W,color:A?"#22c55e":"#dc3545",background:A?"#f0fdf4":void 0},title:A?`${T||"Suitable"} — click to remove`:`Click to mark as ${T||"suitable"}`,onClick:U,children:[A?"✓":"✗",O]})},w=Object.values(f).some(S=>S.required);return s.jsxs("div",{style:Oa.container,children:[s.jsx("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:["Click cells to toggle flags",w?'. Use "N" column to mark "None apply".':"."]})}),s.jsx("div",{style:{overflowX:"auto",maxHeight:"70vh",overflowY:"auto"},children:s.jsxs("table",{style:Oa.table,children:[s.jsx("thead",{style:{position:"sticky",top:0,zIndex:2},children:s.jsxs("tr",{children:[s.jsx("th",{style:{...Oa.th,minWidth:"160px",position:"sticky",top:0,background:"white",zIndex:2},children:"Ingredient"}),Object.entries(f).map(([S,_])=>s.jsxs(s.Fragment,{children:[_.flags.map(b=>s.jsxs("th",{style:Oa.th,title:`${b.name} (${_.name})`,children:[Object.keys(f).length>1&&s.jsx("div",{style:{fontSize:"0.6rem",color:"#888"},children:_.name}),s.jsx("div",{children:b.code||b.name.substring(0,4)})]},b.id)),_.required&&s.jsx("th",{style:{...Oa.th,borderLeft:"2px solid #e0e0e0",fontSize:"0.6rem",minWidth:"28px"},title:`None apply for ${_.name}`,children:s.jsx("div",{children:"N"})},`none-${S}`)]}))]})}),s.jsxs("tbody",{children:[g.map((S,_)=>{if(S.type==="header"){const C=Object.values(f).filter(F=>F.required).length,T=d.flags.length+C+1;return s.jsx("tr",{children:s.jsx("td",{colSpan:T,style:Oa.subHeader,children:S.label})},`h-${_}`)}const b=S.ingredient;return s.jsxs("tr",{children:[s.jsx("td",{style:{...Oa.td,fontWeight:b.is_sub_recipe?400:500},children:S.label}),Object.entries(f).map(([C,T])=>s.jsxs(s.Fragment,{children:[T.flags.map(F=>x(b.ingredient_id,F.id,b.flags[F.id],T.propagation,F.name)),T.required&&s.jsx("td",{style:{...Oa.cell,borderLeft:"2px solid #e0e0e0",cursor:"pointer",color:y(b,Number(C))?"#3b82f6":"#ddd",background:y(b,Number(C))?"#eff6ff":void 0,fontWeight:y(b,Number(C))?600:400},title:y(b,Number(C))?"None apply — click to unset":`Click to mark "None apply" for ${T.name}`,onClick:()=>u.mutate({ingredientId:b.ingredient_id,catId:Number(C)}),children:"N"},`none-${C}-${b.ingredient_id}`)]}))]},b.ingredient_id+"-"+_)}),s.jsxs("tr",{style:{borderTop:"3px double #333"},children:[s.jsx("td",{style:{...Oa.td,fontWeight:700},children:"Recipe Total"}),Object.entries(f).map(([S,_])=>s.jsxs(s.Fragment,{children:[_.flags.map(b=>{const C=m[b.id];return C.unassessed?s.jsx("td",{style:{...Oa.cell,color:"#f59e0b"},children:"❓"},b.id):_.propagation==="contains"?s.jsx("td",{style:{...Oa.cell,color:C.has?"#dc3545":void 0,fontWeight:700},children:C.has?"✓":""},b.id):s.jsx("td",{style:{...Oa.cell,color:C.has?"#22c55e":"#dc3545",fontWeight:700},children:C.has?"✓":"✗"},b.id)}),_.required&&s.jsx("td",{style:{...Oa.cell,borderLeft:"2px solid #e0e0e0"}},`none-total-${S}`)]}))]})]})]})})]})}const Oa={container:{background:"white",padding:"1rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.8rem"},th:{padding:"0.4rem 0.35rem",textAlign:"center",borderBottom:"2px solid #ddd",fontSize:"0.7rem",fontWeight:600,minWidth:"40px",position:"sticky",top:0,background:"white",zIndex:1},td:{padding:"0.35rem 0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.8rem"},cell:{padding:"0.35rem",textAlign:"center",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},subHeader:{padding:"0.5rem",fontWeight:700,background:"#f8f9fa",fontSize:"0.8rem",color:"#555"}},Xfe={g:["g","kg"],kg:["g","kg"],ml:["ml","ltr"],ltr:["ml","ltr"],each:["each"],portion:["portion"]};function KN(n){return Xfe[n]||[n]}function Yfe(){var al;const{id:n}=G_(),e=parseInt(n||"0"),{token:t,user:r}=gn(),i=go(),o=pi(),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState("1"),[p,g]=k.useState("portions"),[m,y]=k.useState(""),[v,x]=k.useState("ml"),[w,S]=k.useState(""),[_,b]=k.useState(""),[C,T]=k.useState(""),[F,A]=k.useState(""),[D,P]=k.useState(!1),[L,W]=k.useState(!1),[O,U]=k.useState(""),[M,I]=k.useState([]),[H,z]=k.useState(null),[G,te]=k.useState(""),[re,me]=k.useState([]),[J,ne]=k.useState(""),[ye,ke]=k.useState(""),[Ye,De]=k.useState(!1),[qe,ue]=k.useState(null),[Ze,ee]=k.useState(null),[Z,ge]=k.useState(""),[Te,Be]=k.useState(""),[he,He]=k.useState("100"),[Ge,ae]=k.useState(""),[K,de]=k.useState(!1),[Y,Q]=k.useState(null),[X,pe]=k.useState(""),[we,Ne]=k.useState(""),[st,Ve]=k.useState(!1),[Re,Le]=k.useState(""),[rt,$e]=k.useState(""),[ce,Je]=k.useState(""),[jt,ct]=k.useState(null),[Se,ot]=k.useState(""),[ut,Ot]=k.useState(!1),[An,on]=k.useState(""),[Ke,Rt]=k.useState(null),[vt,Cr]=k.useState(!1),[Qt,Ci]=k.useState(null),[Lr,Gs]=k.useState(null),[Ai,Ks]=k.useState(null),[un,Fr]=k.useState(!1),[zi,aa]=k.useState(!1),[Oi,Vd]=k.useState(!1),[Gn,Dr]=k.useState(null),[xr,Ss]=k.useState(null),[rs,Xs]=k.useState(null),{data:Jt}=Oe({queryKey:["recipe",e],queryFn:async()=>{const ie=await fetch(`/api/recipes/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!ie.ok)throw new Error("Not found");return ie.json()},enabled:!!t&&!!e}),{data:Ys}=Oe({queryKey:["recipe-sections"],queryFn:async()=>(await fetch("/api/recipes/menu-sections?section_type=recipe",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:Ft}=Oe({queryKey:["recipe-cost",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:Ea}=Oe({queryKey:["recipe-cost-scaled",e,Se],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing?scale_to=${Se}`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&!!Se&&parseFloat(Se)>0}),{data:zn}=Oe({queryKey:["recipe-flags",e],queryFn:async()=>(await fetch(`/api/food-flags/recipes/${e}/flags`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:gi}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>(await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:je}=Oe({queryKey:["recipe-changelog",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/change-log`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&un}),{data:bt}=Oe({queryKey:["recipe-cost-trend",e],queryFn:async()=>{const ie=await fetch(`/api/recipes/${e}/cost-trend`,{headers:{Authorization:`Bearer ${t}`}});if(!ie.ok)throw new Error("Failed to fetch cost trend");return ie.json()},enabled:!!t&&!!e&&vt}),{data:yn}=Oe({queryKey:["ingredient-edit",qe],queryFn:async()=>{const ie=await fetch(`/api/ingredients/${qe}`,{headers:{Authorization:`Bearer ${t}`}});if(!ie.ok)throw new Error("Not found");const nt=await ie.json();return{id:nt.id,name:nt.name,category_id:nt.category_id,standard_unit:nt.standard_unit,yield_percent:Number(nt.yield_percent),manual_price:nt.manual_price!=null?Number(nt.manual_price):null,notes:nt.notes,is_prepackaged:nt.is_prepackaged||!1,is_free:nt.is_free||!1,product_ingredients:nt.product_ingredients,has_label_image:nt.has_label_image||!1}},enabled:!!t&&!!qe}),{data:tn}=Oe({queryKey:["recipes-list-for-sub"],queryFn:async()=>(await fetch("/api/recipes?recipe_type=component",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&K});k.useEffect(()=>{var ie,nt,$,ze;Jt&&(l(Jt.name),c(Jt.description||""),f(Jt.batch_portions.toString()),g(Jt.batch_output_type||"portions"),y(((ie=Jt.batch_yield_qty)==null?void 0:ie.toString())||""),x(Jt.batch_yield_unit||"ml"),S(((nt=Jt.prep_time_minutes)==null?void 0:nt.toString())||""),b((($=Jt.cook_time_minutes)==null?void 0:$.toString())||""),T(Jt.notes||""),A(((ze=Jt.menu_section_id)==null?void 0:ze.toString())||""),P(!1))},[Jt]),k.useEffect(()=>{if(!O||O.length<2||!t)return;const ie=setTimeout(async()=>{try{const nt=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(O)}`,{headers:{Authorization:`Bearer ${t}`}});if(nt.ok){const $=await nt.json();I(Array.isArray($)?$:$.suggestions||[])}else console.warn("Ingredient suggest failed:",nt.status,await nt.text().catch(()=>""))}catch(nt){console.warn("Ingredient suggest error:",nt)}},300);return()=>clearTimeout(ie)},[O,t]);const ci=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),P(!1)}}),hn=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/ingredients`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)})).ok)throw new Error("Failed to add")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]}),W(!1),U(""),z(null),te(""),me([]),ne(""),ke("")}}),Ti=Ue({mutationFn:async({riId:ie,quantity:nt,unit:$,yield_percent:ze,notes:Qe})=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${ie}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({quantity:nt,unit:$,yield_percent:ze,notes:Qe})})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),ee(null)}}),js=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to remove")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})}}),Ar=Ue({mutationFn:async ie=>{const nt=await fetch(`/api/recipes/${e}/sub-recipes`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)});if(!nt.ok){const $=await nt.json().catch(()=>({}));throw new Error($.detail||"Failed to add sub-recipe")}},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),de(!1)}}),fs=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/recipe-sub-recipes/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]})}}),Qs=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/steps`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Ve(!1),Le(""),$e(""),Je("")}}),Lo=Ue({mutationFn:async({stepId:ie,data:nt})=>{if(!(await fetch(`/api/recipes/recipe-steps/${ie}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(nt)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),ct(null),Ve(!1),Le(""),$e(""),Je("")}}),xn=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/recipe-steps/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>o.invalidateQueries({queryKey:["recipe",e]})}),Pa=Ue({mutationFn:async({file:ie,caption:nt,image_type:$})=>{const ze=new FormData;if(ze.append("file",ie),ze.append("caption",nt),ze.append("image_type",$),!(await fetch(`/api/recipes/${e}/images`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:ze})).ok)throw new Error("Failed to upload image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Ot(!1),on(""),Rt(null)}}),nn=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/images/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Zl=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/ingredients/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_ids:ie})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),qu=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/sub-recipes/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sub_recipe_ids:ie})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),$s=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/steps/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({step_ids:ie})})).ok)throw new Error("Failed to reorder steps")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Gd=(ie,nt)=>{Dr(ie),Xs(nt)},mo=(ie,nt)=>{ie.preventDefault(),Ss(nt)},Bc=()=>{if(Gn===null||xr===null||!Jt||rs!=="ing"){Dr(null),Ss(null),Xs(null);return}const nt=[...[...Jt.ingredients].sort((ze,Qe)=>ze.sort_order-Qe.sort_order)],[$]=nt.splice(Gn,1);nt.splice(xr,0,$),Zl.mutate(nt.map(ze=>ze.id)),Dr(null),Ss(null),Xs(null)},Kd=()=>{if(Gn===null||xr===null||!Jt||rs!=="sub"){Dr(null),Ss(null),Xs(null);return}const ie=[...Jt.sub_recipes],[nt]=ie.splice(Gn,1);ie.splice(xr,0,nt),qu.mutate(ie.map($=>$.id)),Dr(null),Ss(null),Xs(null)},Zs=(ie,nt)=>{if(!Jt)return;const $=[...Jt.steps],ze=nt==="up"?ie-1:ie+1;if(ze<0||ze>=$.length)return;const Qe=[...$],pt=Qe[ie];Qe[ie]=Qe[ze],Qe[ze]=pt,$s.mutate(Qe.map(kt=>kt.id))},Ra=()=>{ci.mutate({name:a,description:d||null,batch_portions:p==="portions"&&parseInt(u)||1,batch_output_type:p,batch_yield_qty:p==="bulk"&&parseFloat(m)||null,batch_yield_unit:p==="bulk"?v:null,prep_time_minutes:w?parseInt(w):null,cook_time_minutes:_?parseInt(_):null,notes:C||null,menu_section_id:F?parseInt(F):null})},Xd=ie=>{window.open(`/api/recipes/${e}/print?format=${ie}&token=${t}`,"_blank")};if(!Jt)return s.jsx("div",{style:Fe.loading,children:"Loading recipe..."});const No=Ft==null?void 0:Ft.total_cost_recent,Js=Ft==null?void 0:Ft.cost_per_portion,Ba=(Jt==null?void 0:Jt.output_unit)||"portion",Ic=Ba==="portion"?"Portion Cost":`Cost per ${Ba}`;return s.jsxs("div",{style:Fe.page,children:[s.jsxs("div",{style:Fe.topBar,children:[s.jsx("button",{onClick:()=>i("/recipes"),style:Fe.backBtn,children:"← Back"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>Xd("kitchen"),style:Fe.secondaryBtn,children:"Print Kitchen Card"}),s.jsx("button",{onClick:()=>Xd("full"),style:Fe.secondaryBtn,children:"Print Full"}),D&&s.jsx("button",{onClick:Ra,disabled:ci.isPending,style:Fe.primaryBtn,children:ci.isPending?"Saving...":"Save Changes"})]})]}),s.jsxs("div",{style:Fe.metaSection,children:[s.jsxs("div",{style:Fe.metaRow,children:[s.jsx("input",{value:a,onChange:ie=>{l(ie.target.value),P(!0)},style:{...Fe.nameInput,flex:1}}),s.jsx("span",{style:{background:"#8b5cf6",color:"white",padding:"4px 12px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},children:"RECIPE"})]}),s.jsxs("div",{style:Fe.metaGrid,children:[s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Section"}),s.jsxs("select",{value:F,onChange:ie=>{A(ie.target.value),P(!0)},style:Fe.input,children:[s.jsx("option",{value:"",children:"None"}),Ys==null?void 0:Ys.map(ie=>s.jsx("option",{value:ie.id,children:ie.name},ie.id))]})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Output Type"}),s.jsxs("select",{value:p,onChange:ie=>{g(ie.target.value),P(!0)},style:Fe.input,children:[s.jsx("option",{value:"portions",children:"Portioned"}),s.jsx("option",{value:"bulk",children:"Bulk (volume/weight)"})]})]}),p==="portions"?s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Batch Portions"}),s.jsx("input",{type:"number",value:u,onChange:ie=>{f(ie.target.value),P(!0)},style:Fe.input,min:"1"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Yield Qty"}),s.jsx("input",{type:"number",value:m,onChange:ie=>{y(ie.target.value),P(!0)},style:Fe.input,step:"0.1",min:"0.1"})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Yield Unit"}),s.jsxs("select",{value:v,onChange:ie=>{x(ie.target.value),P(!0)},style:Fe.input,children:[s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Prep (min)"}),s.jsx("input",{type:"number",value:w,onChange:ie=>{S(ie.target.value),P(!0)},style:Fe.input})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Cook (min)"}),s.jsx("input",{type:"number",value:_,onChange:ie=>{b(ie.target.value),P(!0)},style:Fe.input})]})]}),s.jsx("label",{style:Fe.label,children:"Description"}),s.jsx("textarea",{value:d,onChange:ie=>{c(ie.target.value),P(!0)},style:{...Fe.input,minHeight:"50px"}})]}),zn&&zn.unassessed_ingredients.length>0&&s.jsxs("div",{style:Fe.flagWarning,children:[s.jsxs("strong",{children:[zn.unassessed_ingredients.length," ingredient",zn.unassessed_ingredients.length>1?"s are":" is"," missing allergen details"]})," — ",zn.unassessed_ingredients.map(ie=>ie.name).join(", ")]}),zn&&zn.open_suggestion_ingredients&&zn.open_suggestion_ingredients.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsxs("strong",{children:[zn.open_suggestion_ingredients.length," ingredient",zn.open_suggestion_ingredients.length>1?"s have":" has"," unreviewed allergen suggestions"]})," — ",zn.open_suggestion_ingredients.map((ie,nt)=>s.jsxs("span",{children:[nt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline",fontWeight:600},onClick:()=>ue(ie.ingredient_id),children:ie.ingredient_name})," ","(",ie.suggestion_count,")"]},ie.ingredient_id))]}),zn&&zn.recipe_text_suggestions&&zn.recipe_text_suggestions.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsx("strong",{children:"Recipe text keyword matches"}),s.jsx("div",{style:{marginTop:"0.4rem"},children:zn.recipe_text_suggestions.map(ie=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.3rem"},children:[s.jsxs("span",{children:[s.jsx("strong",{children:ie.flag_name})," — ",ie.matched_keywords.join(", ")]}),s.jsx("button",{style:{marginLeft:"auto",background:"none",border:"1px solid #b4530955",borderRadius:"4px",color:"#b45309",cursor:"pointer",padding:"0.15rem 0.5rem",fontSize:"0.8rem",whiteSpace:"nowrap"},onClick:async()=>{try{(await fetch(`/api/food-flags/recipes/${e}/text-dismissals`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_id:ie.flag_id,dismissed_by_name:(r==null?void 0:r.name)||(r==null?void 0:r.email)||"Unknown",matched_keyword:ie.matched_keywords.join(", ")})})).ok&&o.invalidateQueries({queryKey:["recipe-flags",e]})}catch{}},children:"Dismiss"})]},ie.flag_id))})]}),Jt&&(()=>{const ie=Jt.ingredients.filter(Qe=>Qe.is_manual_price),nt=Jt.ingredients.filter(Qe=>Qe.has_no_price),$=Jt.sub_recipes.filter(Qe=>Qe.has_manual_price_ingredients),ze=Jt.sub_recipes.filter(Qe=>Qe.has_no_price_ingredients);return ie.length===0&&nt.length===0&&$.length===0&&ze.length===0?null:s.jsxs("div",{style:{background:"#fef3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #ffc10755"},children:[nt.length>0&&s.jsxs("div",{children:[s.jsxs("strong",{children:[nt.length," ingredient",nt.length>1?"s have":" has"," no price"]})," — ",nt.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ue(Qe.ingredient_id),children:Qe.ingredient_name})]},Qe.ingredient_id))]}),ie.length>0&&s.jsxs("div",{style:{marginTop:nt.length>0?"0.3rem":0},children:[s.jsxs("strong",{children:[ie.length," ingredient",ie.length>1?"s use":" uses"," manual price"]})," — ",ie.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ue(Qe.ingredient_id),children:Qe.ingredient_name})]},Qe.ingredient_id))]}),ze.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[ze.length," sub-recipe",ze.length>1?"s contain":" contains"," unpriced ingredients"]})," — ",ze.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${Qe.child_recipe_id}`),children:Qe.child_recipe_name})]},Qe.child_recipe_id))]}),$.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[$.length," sub-recipe",$.length>1?"s contain":" contains"," manual-priced ingredients"]})," — ",$.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${Qe.child_recipe_id}`),children:Qe.child_recipe_name})]},Qe.child_recipe_id))]})]})})(),zn&&s.jsxs("div",{style:{margin:"0.75rem 0"},children:[zn.flags.length>0&&s.jsx(T0,{flags:zn.flags,size:"medium"}),gi&&gi.length>0&&s.jsx("div",{style:{display:"flex",gap:"0.35rem",marginTop:"0.5rem",flexWrap:"wrap"},children:gi.map(ie=>s.jsx("button",{onClick:()=>Ks(Ai===ie.id?null:ie.id),style:{padding:"3px 10px",fontSize:"0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:Ai===ie.id?"#e94560":"#f5f5f5",color:Ai===ie.id?"white":"#555",cursor:"pointer"},children:ie.name},ie.id))})]}),Ai!=null&&s.jsx(WK,{recipeId:e,categoryId:Ai||void 0}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Ingredients"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Jt.ingredients.length>1&&s.jsx("button",{onClick:()=>aa(!zi),style:{...Fe.addBtn,background:zi?"#3b82f6":void 0,color:zi?"#fff":void 0},children:zi?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>W(!0),style:Fe.addBtn,children:"+ Add"})]})]}),s.jsxs("table",{style:Fe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[zi&&s.jsx("th",{style:{...Fe.th,width:"30px"}}),s.jsx("th",{style:Fe.th,children:"Ingredient"}),s.jsx("th",{style:Fe.th,children:"Quantity"}),s.jsx("th",{style:Fe.th,children:"Yield %"}),s.jsx("th",{style:Fe.th,children:"Cost"}),s.jsx("th",{style:Fe.th,children:"Notes"}),s.jsx("th",{style:Fe.th})]})}),s.jsx("tbody",{children:[...Jt.ingredients].sort((ie,nt)=>ie.sort_order-nt.sort_order).map((ie,nt)=>s.jsxs("tr",{style:{...Fe.tr,opacity:rs==="ing"&&Gn===nt?.4:1,background:rs==="ing"&&xr===nt?"#e0f2fe":void 0},draggable:zi,onDragStart:()=>Gd(nt,"ing"),onDragOver:$=>mo($,nt),onDrop:Bc,onDragEnd:()=>{Dr(null),Ss(null),Xs(null)},children:[zi&&s.jsx("td",{style:{...Fe.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6",textDecoration:"none"},onClick:()=>ue(ie.ingredient_id),title:"Edit ingredient",children:ie.ingredient_name})}),Ze===ie.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:Fe.td,children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"2px"},children:[s.jsx("input",{type:"number",value:Z,onChange:$=>ge($.target.value),style:{...Fe.input,width:"80px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.1",autoFocus:!0}),ie.compatible_units&&ie.compatible_units.length>1?s.jsx("select",{value:Te,onChange:$=>Be($.target.value),style:{...Fe.input,width:"55px",padding:"0.25rem 0.2rem",fontSize:"0.75rem"},children:ie.compatible_units.map($=>s.jsx("option",{value:$,children:$},$))}):s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ie.unit})]})}),s.jsx("td",{style:Fe.td,children:s.jsx("input",{type:"number",value:he,onChange:$=>He($.target.value),style:{...Fe.input,width:"60px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.5",min:"1",max:"100"})}),s.jsx("td",{style:Fe.td,children:ie.cost!=null?`£${ie.cost.toFixed(2)}`:"-"}),s.jsx("td",{style:Fe.td,children:s.jsx("input",{value:Ge,onChange:$=>ae($.target.value),style:{...Fe.input,width:"120px",padding:"0.25rem 0.4rem",fontSize:"0.8rem"},placeholder:"notes..."})}),s.jsx("td",{style:Fe.td,children:s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[s.jsx("button",{onClick:()=>Ti.mutate({riId:ie.id,quantity:parseFloat(Z),unit:Te,yield_percent:parseFloat(he),notes:Ge||void 0}),disabled:!Z||Ti.isPending,style:{...Fe.addBtn,fontSize:"0.7rem",padding:"2px 6px",color:"#16a34a"},children:"Save"}),s.jsx("button",{onClick:()=>ee(null),style:{...Fe.removeBtn,color:"#888"},children:"Cancel"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("td",{style:{...Fe.td,cursor:"pointer"},onClick:()=>{ee(ie.id),ge(ie.quantity.toString()),Be(ie.unit),He(ie.yield_percent.toString()),ae(ie.notes||"")},children:[ie.quantity,ie.unit]}),s.jsx("td",{style:{...Fe.td,cursor:"pointer"},onClick:()=>{ee(ie.id),ge(ie.quantity.toString()),Be(ie.unit),He(ie.yield_percent.toString()),ae(ie.notes||"")},children:ie.yield_percent<100?s.jsxs("span",{style:{color:"#e94560"},children:[ie.yield_percent,"%"]}):"100%"}),s.jsx("td",{style:Fe.td,children:ie.cost!=null?s.jsxs("span",{style:ie.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:ie.is_manual_price?"Manual price":void 0,children:["£",ie.cost.toFixed(2)]}):"-"}),s.jsx("td",{style:{...Fe.td,cursor:"pointer"},onClick:()=>{ee(ie.id),ge(ie.quantity.toString()),Be(ie.unit),He(ie.yield_percent.toString()),ae(ie.notes||"")},children:s.jsx("span",{style:{color:"#888",fontSize:"0.8rem"},children:ie.notes||"-"})}),s.jsx("td",{style:Fe.td,children:s.jsx("button",{onClick:()=>js.mutate(ie.id),style:Fe.removeBtn,children:"✕"})})]})]},ie.id))})]})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Sub-Recipes"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Jt.sub_recipes.length>1&&s.jsx("button",{onClick:()=>Vd(!Oi),style:{...Fe.addBtn,background:Oi?"#3b82f6":void 0,color:Oi?"#fff":void 0},children:Oi?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>de(!0),style:Fe.addBtn,children:"+ Add"})]})]}),Jt.sub_recipes.length>0?s.jsxs("table",{style:Fe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[Oi&&s.jsx("th",{style:{...Fe.th,width:"30px"}}),s.jsx("th",{style:Fe.th,children:"Recipe"}),s.jsx("th",{style:Fe.th,children:"Batch Output"}),s.jsx("th",{style:Fe.th,children:"Amount Used"}),s.jsx("th",{style:Fe.th,children:"Cost"}),s.jsx("th",{style:Fe.th})]})}),s.jsx("tbody",{children:Jt.sub_recipes.map((ie,nt)=>s.jsxs("tr",{style:{...Fe.tr,opacity:rs==="sub"&&Gn===nt?.4:1,background:rs==="sub"&&xr===nt?"#e0f2fe":void 0},draggable:Oi,onDragStart:()=>Gd(nt,"sub"),onDragOver:$=>mo($,nt),onDrop:Kd,onDragEnd:()=>{Dr(null),Ss(null),Xs(null)},children:[Oi&&s.jsx("td",{style:{...Fe.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${ie.child_recipe_id}`),children:ie.child_recipe_name})}),s.jsx("td",{style:Fe.td,children:ie.batch_output_type==="bulk"?`${ie.output_qty}${ie.output_unit}`:`${ie.batch_portions} portions`}),s.jsxs("td",{style:Fe.td,children:[ie.portions_needed,ie.batch_output_type==="bulk"?ie.portions_needed_unit:" portions",ie.batch_output_type==="bulk"&&ie.portions_needed_unit!==ie.output_unit&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#888",marginLeft:"4px"},children:["(",ie.output_unit,")"]})]}),s.jsx("td",{style:Fe.td,children:ie.cost_contribution!=null?s.jsxs("span",{style:ie.has_manual_price_ingredients||ie.has_no_price_ingredients?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:ie.has_manual_price_ingredients?"Includes manual-priced ingredients":ie.has_no_price_ingredients?"Includes unpriced ingredients":void 0,children:["£",ie.cost_contribution.toFixed(2)]}):"-"}),s.jsx("td",{style:Fe.td,children:s.jsx("button",{onClick:()=>fs.mutate(ie.id),style:Fe.removeBtn,children:"✕"})})]},ie.id))})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No sub-recipes added"})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Method"}),s.jsx("button",{onClick:()=>{ct(null),Le(""),$e(""),Je(""),Ve(!0)},style:Fe.addBtn,children:"+ Add Step"})]}),Jt.steps.length>0?s.jsx("div",{style:{margin:0},children:Jt.steps.map((ie,nt)=>s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px",padding:"8px 0",borderBottom:"1px solid #f0f0f0"},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",flexShrink:0,marginTop:"2px"},children:[s.jsx("button",{onClick:()=>Zs(nt,"up"),disabled:nt===0||$s.isPending,style:{...Fe.reorderBtn,opacity:nt===0?.3:1},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>Zs(nt,"down"),disabled:nt===Jt.steps.length-1||$s.isPending,style:{...Fe.reorderBtn,opacity:nt===Jt.steps.length-1?.3:1},title:"Move down",children:"▼"})]}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem",color:"#e94560",minWidth:"24px",marginTop:"1px"},children:nt+1}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:"6px"},children:[ie.title&&s.jsx("span",{style:{fontWeight:600,fontSize:"0.95rem"},children:ie.title}),ie.duration_minutes&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#888"},children:["(",ie.duration_minutes," min)"]})]}),s.jsx("div",{style:{fontSize:"0.85rem",color:"#555",marginTop:ie.title?"2px":0,whiteSpace:"pre-wrap"},children:ie.instruction})]}),s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{onClick:()=>{ct(ie.id),Le(ie.title||""),$e(ie.instruction),Je(ie.duration_minutes?String(ie.duration_minutes):""),Ve(!0)},style:{...Fe.reorderBtn,fontSize:"0.75rem"},title:"Edit step",children:"✎"}),s.jsx("button",{onClick:()=>xn.mutate(ie.id),style:{...Fe.removeBtn,flexShrink:0},children:"✕"})]})]},ie.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No steps added yet"})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Images"}),s.jsx("button",{onClick:()=>Ot(!ut),style:Fe.addBtn,children:ut?"Cancel":"+ Upload"})]}),ut&&s.jsxs("div",{style:{marginBottom:"1rem",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsx("label",{style:Fe.label,children:"Image File"}),s.jsx("input",{type:"file",accept:"image/*",onChange:ie=>{var nt;return Rt(((nt=ie.target.files)==null?void 0:nt[0])||null)},style:{...Fe.input,padding:"0.35rem"}}),s.jsx("label",{style:Fe.label,children:"Caption (optional)"}),s.jsx("input",{value:An,onChange:ie=>on(ie.target.value),style:Fe.input,placeholder:"Describe this image..."}),s.jsx("div",{style:{marginTop:"0.75rem",display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{onClick:()=>{Ke&&Pa.mutate({file:Ke,caption:An,image_type:"general"})},disabled:!Ke||Pa.isPending,style:Fe.primaryBtn,children:Pa.isPending?"Uploading...":"Upload Image"})}),Pa.error&&s.jsx("div",{style:Fe.errorMsg,children:Pa.error.message})]}),Jt.images.length>0?s.jsx("div",{style:Fe.imageGrid,children:Jt.images.map(ie=>s.jsxs("div",{style:Fe.imageCard,children:[s.jsx("img",{src:`/api/recipes/${e}/images/${ie.id}?token=${t}`,alt:ie.caption||"Recipe image",style:{...Fe.imageThumb,cursor:"pointer"},onClick:()=>Gs(`/api/recipes/${e}/images/${ie.id}?token=${t}`)}),s.jsxs("div",{style:{padding:"0.4rem"},children:[ie.caption&&s.jsx("div",{style:{fontSize:"0.8rem",color:"#333",marginTop:"2px"},children:ie.caption}),s.jsx("button",{onClick:()=>{confirm("Delete this image?")&&nn.mutate(ie.id)},style:{...Fe.removeBtn,marginTop:"4px",fontSize:"0.7rem"},children:"Delete"})]})]},ie.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No images uploaded"})]}),s.jsxs("div",{style:Fe.costPanel,children:[s.jsx("div",{style:Fe.costHeader,children:s.jsx("h3",{style:{margin:0},children:"Cost Summary"})}),s.jsxs("div",{style:Fe.costGrid,children:[s.jsxs("div",{style:Fe.costBox,children:[s.jsx("div",{style:Fe.costLabel,children:"Recipe Total"}),s.jsx("div",{style:Fe.costValue,children:No!=null?`£${No.toFixed(2)}`:"-"})]}),s.jsxs("div",{style:Fe.costBox,children:[s.jsx("div",{style:Fe.costLabel,children:Ic}),s.jsx("div",{style:Fe.costValue,children:Js!=null?`£${Js.toFixed(4)}`:"-"})]}),(Ft==null?void 0:Ft.total_cost_min)!=null&&s.jsxs("div",{style:Fe.costBox,children:[s.jsx("div",{style:Fe.costLabel,children:"Min / Max"}),s.jsxs("div",{style:{fontSize:"0.85rem"},children:["£",Ft.total_cost_min.toFixed(2)," – £",(al=Ft.total_cost_max)==null?void 0:al.toFixed(2)]})]})]}),s.jsx("div",{style:{marginTop:"0.5rem"},children:s.jsxs("button",{onClick:()=>Cr(!vt),style:Fe.linkBtn,children:[vt?"Hide":"Show"," cost trend"]})}),vt&&(bt==null?void 0:bt.snapshots)&&bt.snapshots.length>1&&(()=>{const ie=bt.snapshots,nt=ie.map(It=>It.cost_per_portion),$=Math.min(...nt),ze=Math.max(...nt),Qe=ze-$||1,pt=500,kt=120,Ht=40,Gt=20,Er=pt-Ht*2,ar=kt-Gt*2,Kn=ie.map((It,Tn)=>{const Dt=Ht+Tn/(ie.length-1)*Er,Ln=Gt+ar-(It.cost_per_portion-$)/Qe*ar;return{x:Dt,y:Ln,...It}}),is=Kn.map(It=>`${It.x},${It.y}`).join(" "),On=[$,$+Qe/2,ze],sn=[0,Math.floor(ie.length/2),ie.length-1],ps=ie.filter((It,Tn)=>Tn>0&&It.cost_per_portion!==ie[Tn-1].cost_per_portion);return s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"1rem",alignItems:"flex-start"},children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("svg",{width:pt,height:kt,style:{background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[On.map((It,Tn)=>{const Dt=Gt+ar-(It-$)/Qe*ar;return s.jsxs("g",{children:[s.jsx("line",{x1:Ht,y1:Dt,x2:pt-Ht,y2:Dt,stroke:"#f0f0f0",strokeWidth:"1"}),s.jsxs("text",{x:Ht-4,y:Dt+3,textAnchor:"end",fontSize:"9",fill:"#888",children:["£",It.toFixed(2)]})]},Tn)}),sn.filter((It,Tn,Dt)=>Dt.indexOf(It)===Tn).map(It=>{const Tn=Kn[It],Dt=new Date(Tn.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"});return s.jsx("text",{x:Tn.x,y:kt-2,textAnchor:"middle",fontSize:"9",fill:"#888",children:Dt},It)}),s.jsx("polyline",{points:is,fill:"none",stroke:"#e94560",strokeWidth:"2"}),Kn.map((It,Tn)=>s.jsx("circle",{cx:It.x,cy:It.y,r:4,fill:"#e94560",stroke:"white",strokeWidth:"2",style:{cursor:"pointer"},onMouseEnter:Dt=>{var Fi;const Ln=(Fi=Dt.target.closest("svg"))==null?void 0:Fi.getBoundingClientRect();Ci({x:Ln?It.x+Ln.left-((Ln==null?void 0:Ln.left)||0):It.x,y:It.y-10,date:new Date(It.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),cost:`£${It.cost_per_portion.toFixed(4)}`,trigger:It.trigger})},onMouseLeave:()=>Ci(null)},Tn))]}),Qt&&s.jsxs("div",{style:{position:"absolute",left:Qt.x,top:Qt.y-50,transform:"translateX(-50%)",background:"#333",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"0.75rem",whiteSpace:"nowrap",pointerEvents:"none",zIndex:20},children:[s.jsx("div",{children:Qt.date}),s.jsx("div",{children:Qt.cost}),s.jsx("div",{style:{color:"#ccc",fontSize:"0.7rem"},children:Qt.trigger})]})]}),ps.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"220px",maxHeight:"300px",overflow:"auto",fontSize:"0.75rem",background:"#fafafa",borderRadius:"6px",padding:"6px 8px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{fontWeight:600,fontSize:"0.7rem",color:"#888",marginBottom:"4px"},children:["Change Log (",ps.length," snapshots)"]}),ps.slice().reverse().map((It,Tn)=>{const Dt=ie[ie.indexOf(It)-1],Ln=It.cost_per_portion-Dt.cost_per_portion,Fi=Ln>0?"#dc2626":"#16a34a";return s.jsxs("div",{style:{padding:"3px 0",borderBottom:"1px solid #eee"},children:[s.jsxs("div",{style:{color:"#888"},children:[new Date(It.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),s.jsxs("span",{style:{color:Fi,fontWeight:600,marginLeft:"4px"},children:[Ln>0?"+":"","£",Ln.toFixed(4)]})]}),It.changes.length>0&&s.jsx("div",{style:{color:"#666",marginTop:"1px"},children:It.changes.map((Zr,ll)=>s.jsx("div",{style:{fontSize:"0.7rem",lineHeight:1.3},children:Zr},ll))})]},Tn)})]})]})})(),vt&&(bt==null?void 0:bt.snapshots)&&bt.snapshots.length<=1&&s.jsx("div",{style:{marginTop:"0.5rem",color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"Not enough data points to display a trend chart"})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Scale Recipe"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("input",{type:"number",value:Se,onChange:ie=>ot(ie.target.value),style:{...Fe.input,width:"80px"},placeholder:Jt.output_qty.toString(),min:"0.1",step:Jt.batch_output_type==="bulk"?"0.1":"1"}),s.jsxs("span",{style:{fontSize:"0.8rem",color:"#888"},children:[Ba,Ba==="portion"?"s":""]})]})]}),(()=>{var Qe;const ie=Ea||Ft;if(!(ie!=null&&ie.ingredients))return null;const nt=ie.ingredients.reduce((pt,kt)=>pt+(kt.cost_recent??0),0)+(((Qe=ie.sub_recipes)==null?void 0:Qe.reduce((pt,kt)=>pt+(kt.cost_contribution??0),0))??0),$=ie.ingredients.reduce((pt,kt)=>pt+(kt.cost_min??0),0),ze=ie.ingredients.reduce((pt,kt)=>pt+(kt.cost_max??0),0);return s.jsxs("table",{style:Fe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Fe.th,children:"Ingredient"}),s.jsx("th",{style:Fe.th,children:"Qty"}),s.jsx("th",{style:Fe.th,children:"Recent"}),s.jsx("th",{style:Fe.th,children:"Min"}),s.jsx("th",{style:Fe.th,children:"Max"})]})}),s.jsxs("tbody",{children:[ie.ingredients.map(pt=>{const kt=pt.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;return s.jsxs("tr",{children:[s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ue(pt.ingredient_id),title:"Edit ingredient",children:pt.ingredient_name})}),s.jsxs("td",{style:Fe.td,children:[pt.quantity,pt.unit]}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:kt,title:pt.is_manual_price?"Manual price":void 0,children:pt.cost_recent!=null?`£${pt.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:kt,title:pt.is_manual_price?"Manual price":void 0,children:pt.cost_min!=null?`£${pt.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:kt,title:pt.is_manual_price?"Manual price":void 0,children:pt.cost_max!=null?`£${pt.cost_max.toFixed(2)}`:"-"})})]},pt.ingredient_id)}),(()=>{const pt=(kt,Ht)=>{var Er,ar;const Gt=[];for(const Kn of kt){const is=Ht*1.5,On=Kn.child_ingredients&&Kn.child_ingredients.length>0||Kn.child_sub_recipes&&Kn.child_sub_recipes.length>0,sn=((Er=Kn.child_ingredients)==null?void 0:Er.some(It=>It.is_manual_price))||!1,ps=sn?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;if(Gt.push(s.jsx("tr",{children:s.jsxs("td",{colSpan:5,style:{...Fe.td,background:Ht===0?"#f0f0f0":"#f5f5f5",fontWeight:600,fontSize:"0.8rem",color:"#555",paddingLeft:`${.5+is}rem`},children:[Ht>0&&"→ ",s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${Kn.child_recipe_id}`),children:Kn.child_recipe_name})," (",Kn.portions_needed,Kn.output_unit==="portion"?" portions":Kn.output_unit,") — ",s.jsxs("span",{style:ps,title:sn?"Includes manual-priced ingredients":void 0,children:["£",((ar=Kn.cost_contribution)==null?void 0:ar.toFixed(2))??"-"]})]})},`sub-header-${Ht}-${Kn.child_recipe_id}`)),On){for(const It of Kn.child_ingredients||[]){const Tn=It.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;Gt.push(s.jsxs("tr",{style:{background:"#fafafa"},children:[s.jsx("td",{style:{...Fe.td,paddingLeft:`${1.5+is}rem`,color:"#666"},children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ue(It.ingredient_id),title:"Edit ingredient",children:It.ingredient_name})}),s.jsxs("td",{style:{...Fe.td,color:"#666"},children:[It.quantity,It.unit]}),s.jsx("td",{style:{...Fe.td,color:"#666"},children:s.jsx("span",{style:Tn,title:It.is_manual_price?"Manual price":void 0,children:It.cost_recent!=null?`£${It.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Fe.td,color:"#666"},children:s.jsx("span",{style:Tn,title:It.is_manual_price?"Manual price":void 0,children:It.cost_min!=null?`£${It.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Fe.td,color:"#666"},children:s.jsx("span",{style:Tn,title:It.is_manual_price?"Manual price":void 0,children:It.cost_max!=null?`£${It.cost_max.toFixed(2)}`:"-"})})]},`sub-${Ht}-${Kn.child_recipe_id}-ing-${It.ingredient_id}`))}Kn.child_sub_recipes&&Kn.child_sub_recipes.length>0&&Gt.push(...pt(Kn.child_sub_recipes,Ht+1))}}return Gt};return pt(ie.sub_recipes||[],0)})(),s.jsxs("tr",{style:{borderTop:"2px solid #333"},children:[s.jsx("td",{style:{...Fe.td,fontWeight:700},children:"Total"}),s.jsx("td",{style:Fe.td}),s.jsx("td",{style:{...Fe.td,fontWeight:700},children:nt>0?`£${nt.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Fe.td,fontWeight:700},children:$>0?`£${$.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Fe.td,fontWeight:700},children:ze>0?`£${ze.toFixed(2)}`:"-"})]})]})]})})()]}),s.jsxs("div",{style:Fe.section,children:[s.jsx("label",{style:Fe.label,children:"Notes"}),s.jsx("textarea",{value:C,onChange:ie=>{T(ie.target.value),P(!0)},style:{...Fe.input,minHeight:"60px"}})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("button",{onClick:()=>Fr(!un),style:Fe.linkBtn,children:[un?"Hide":"Show"," change history"]}),un&&je&&s.jsx("div",{style:{marginTop:"0.5rem"},children:je.map(ie=>s.jsxs("div",{style:Fe.logEntry,children:[s.jsx("span",{style:{color:"#888",fontSize:"0.75rem"},children:ie.created_at}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#555"},children:ie.username}),s.jsx("span",{style:{fontSize:"0.85rem"},children:ie.change_summary})]},ie.id))})]}),L&&s.jsx("div",{style:Fe.overlay,children:s.jsxs("div",{style:Fe.modal,children:[s.jsxs("div",{style:Fe.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Ingredient"}),s.jsx("button",{onClick:()=>W(!1),style:Fe.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Fe.modalBody,children:[s.jsx("label",{style:Fe.label,children:"Search Ingredient"}),s.jsx("input",{value:O,onChange:ie=>{U(ie.target.value),z(null)},style:Fe.input,placeholder:"Type to search..."}),O.length>=2&&!H&&s.jsxs("div",{style:Fe.suggestions,children:[M.map(ie=>s.jsxs("div",{style:Fe.suggestionItem,onClick:()=>{const nt=KN(ie.standard_unit);z(ie.id),te(ie.standard_unit),me(nt),U(ie.name)},children:[ie.name," ",s.jsxs("span",{style:{color:"#888",fontSize:"0.75rem"},children:["(",Math.round(ie.similarity*100),"%)"]})]},ie.id)),s.jsxs("div",{style:{...Fe.suggestionItem,color:"#16a34a",fontWeight:600,borderBottom:"none"},onClick:()=>De(!0),children:['+ Create "',O,'"']})]}),H&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Fe.label,children:"Quantity"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:J,onChange:ie=>ne(ie.target.value),style:{...Fe.input,flex:1},step:"0.1"}),re.length>1?s.jsx("select",{value:G,onChange:ie=>te(ie.target.value),style:{...Fe.input,width:"70px"},children:re.map(ie=>s.jsx("option",{value:ie,children:ie},ie))}):s.jsx("span",{style:{alignSelf:"center",fontSize:"0.85rem",color:"#666",minWidth:"30px"},children:G})]}),s.jsx("label",{style:Fe.label,children:"Notes (optional)"}),s.jsx("input",{value:ye,onChange:ie=>ke(ie.target.value),style:Fe.input,placeholder:"e.g. finely diced"})]})]}),s.jsxs("div",{style:Fe.modalFooter,children:[s.jsx("button",{onClick:()=>W(!1),style:Fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>hn.mutate({ingredient_id:H,quantity:parseFloat(J),unit:G||void 0,notes:ye||void 0}),disabled:!H||!J||hn.isPending,style:Fe.primaryBtn,children:hn.isPending?"Adding...":"Add"})]}),Ar.error&&s.jsx("div",{style:Fe.errorMsg,children:Ar.error.message})]})}),s.jsx(A0,{open:Ye,onClose:()=>De(!1),onSaved:ie=>{const nt=KN(ie.standard_unit);z(ie.id),te(ie.standard_unit),me(nt),U(ie.name)},prePopulateName:O}),s.jsx(A0,{open:!!qe&&!!yn,onClose:()=>ue(null),onSaved:()=>{ue(null),o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})},editingIngredient:yn||void 0}),K&&s.jsx("div",{style:Fe.overlay,children:s.jsxs("div",{style:Fe.modal,children:[s.jsxs("div",{style:Fe.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Sub-Recipe"}),s.jsx("button",{onClick:()=>de(!1),style:Fe.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Fe.modalBody,children:[s.jsx("label",{style:Fe.label,children:"Select Component Recipe"}),s.jsxs("select",{value:(Y==null?void 0:Y.toString())||"",onChange:ie=>{const nt=parseInt(ie.target.value);Q(nt);const $=tn==null?void 0:tn.find(ze=>ze.id===nt);Ne(($==null?void 0:$.batch_output_type)==="bulk"&&($==null?void 0:$.batch_yield_unit)||"")},style:Fe.input,children:[s.jsx("option",{value:"",children:"Select..."}),tn==null?void 0:tn.filter(ie=>ie.id!==e).map(ie=>s.jsxs("option",{value:ie.id,children:[ie.name," (",ie.batch_output_type==="bulk"?`yield: ${ie.batch_yield_qty}${ie.batch_yield_unit}`:`batch: ${ie.batch_portions}`,")"]},ie.id))]}),(()=>{const ie=tn==null?void 0:tn.find(Qe=>Qe.id===Y),nt=(ie==null?void 0:ie.batch_output_type)==="bulk",$=(ie==null?void 0:ie.batch_yield_unit)||"",ze=nt?$==="ml"||$==="ltr"?["ml","ltr"]:$==="g"||$==="kg"?["g","kg"]:[$]:[];return s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Fe.label,children:nt?"Amount":"Portions Needed"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:X,onChange:Qe=>pe(Qe.target.value),style:{...Fe.input,flex:1},step:nt?"0.1":"0.5",min:"0.1"}),nt&&ze.length>1?s.jsx("select",{value:we,onChange:Qe=>Ne(Qe.target.value),style:{...Fe.input,width:"80px",flex:"none"},children:ze.map(Qe=>s.jsx("option",{value:Qe,children:Qe},Qe))}):nt?s.jsx("span",{style:{padding:"0.5rem 0",fontSize:"0.85rem",color:"#555"},children:$}):null]})]})})()]}),s.jsxs("div",{style:Fe.modalFooter,children:[s.jsx("button",{onClick:()=>de(!1),style:Fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>Ar.mutate({child_recipe_id:Y,portions_needed:parseFloat(X),portions_needed_unit:we||void 0}),disabled:!Y||!X||Ar.isPending,style:Fe.primaryBtn,children:Ar.isPending?"Adding...":"Add"})]}),Ar.error&&s.jsx("div",{style:Fe.errorMsg,children:Ar.error.message})]})}),st&&s.jsx("div",{style:Fe.overlay,children:s.jsxs("div",{style:Fe.modal,children:[s.jsxs("div",{style:Fe.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:jt?"Edit Step":"Add Step"}),s.jsx("button",{onClick:()=>{Ve(!1),ct(null)},style:Fe.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Fe.modalBody,children:[s.jsx("label",{style:Fe.label,children:"Title (optional)"}),s.jsx("input",{value:Re,onChange:ie=>Le(ie.target.value),style:Fe.input,placeholder:"e.g. Prepare the base, Sear the protein"}),s.jsx("label",{style:Fe.label,children:"Instructions"}),s.jsx("textarea",{value:rt,onChange:ie=>$e(ie.target.value),style:{...Fe.input,minHeight:"80px"}}),s.jsx("label",{style:Fe.label,children:"Duration (minutes, optional)"}),s.jsx("input",{type:"number",value:ce,onChange:ie=>Je(ie.target.value),style:Fe.input})]}),s.jsxs("div",{style:Fe.modalFooter,children:[s.jsx("button",{onClick:()=>{Ve(!1),ct(null)},style:Fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>{jt?Lo.mutate({stepId:jt,data:{title:Re||"",instruction:rt,duration_minutes:ce?parseInt(ce):void 0}}):Qs.mutate({title:Re||void 0,instruction:rt,step_number:((Jt==null?void 0:Jt.steps.length)||0)+1,duration_minutes:ce?parseInt(ce):void 0})},disabled:!rt||Qs.isPending||Lo.isPending,style:Fe.primaryBtn,children:jt?Lo.isPending?"Saving...":"Save":Qs.isPending?"Adding...":"Add Step"})]})]})}),Lr&&s.jsxs("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.85)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,cursor:"pointer"},onClick:()=>Gs(null),children:[s.jsx("img",{src:Lr,alt:"Recipe image",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"},onClick:ie=>ie.stopPropagation()}),s.jsx("button",{onClick:()=>Gs(null),style:{position:"absolute",top:"20px",right:"20px",background:"rgba(255,255,255,0.2)",border:"none",color:"white",fontSize:"1.5rem",cursor:"pointer",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center"},children:"✕"})]})]})}const Fe={page:{padding:"1.5rem",maxWidth:"1000px",margin:"0 auto"},topBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},backBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},metaSection:{background:"white",padding:"1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},metaRow:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"0.75rem"},metaGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:"0.75rem",marginBottom:"0.75rem"},nameInput:{fontSize:"1.3rem",fontWeight:600,padding:"0.4rem",border:"1px solid #e0e0e0",borderRadius:"6px"},section:{background:"white",padding:"1rem 1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.5rem",fontSize:"0.85rem"},addBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},removeBtn:{padding:"2px 6px",background:"none",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.7rem",color:"#e94560"},costPanel:{background:"#f8f9fa",padding:"1.25rem",borderRadius:"8px",border:"2px solid #e0e0e0",marginBottom:"1rem"},costHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},costGrid:{display:"flex",gap:"1.5rem",flexWrap:"wrap"},costBox:{minWidth:"120px"},costLabel:{fontSize:"0.75rem",color:"#666",fontWeight:600},costValue:{fontSize:"1.3rem",fontWeight:700,color:"#333"},flagWarning:{background:"#fff3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem"},logEntry:{display:"flex",gap:"0.5rem",padding:"0.35rem 0",borderBottom:"1px solid #f0f0f0",alignItems:"center"},linkBtn:{background:"none",border:"none",color:"#3b82f6",cursor:"pointer",fontSize:"0.8rem",padding:0},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},secondaryBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.5rem",marginBottom:"0.2rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},suggestions:{background:"white",border:"1px solid #ddd",borderRadius:"6px",maxHeight:"150px",overflow:"auto",marginTop:"4px"},suggestionItem:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.85rem"},errorMsg:{padding:"0.75rem 1.25rem",color:"#dc3545",fontSize:"0.85rem"},reorderBtn:{padding:"0",width:"18px",height:"16px",background:"none",border:"1px solid #ddd",borderRadius:"3px",cursor:"pointer",fontSize:"0.55rem",color:"#666",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1},imageGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))",gap:"0.75rem"},imageCard:{background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0",overflow:"hidden"},imageThumb:{width:"100%",height:"120px",objectFit:"cover",display:"block"}};function Qfe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(!1),[o,a]=k.useState(""),[l,d]=k.useState(""),[c,u]=k.useState(""),{data:f,isLoading:p}=Oe({queryKey:["event-orders"],queryFn:async()=>{const v=await fetch("/api/event-orders",{headers:{Authorization:`Bearer ${n}`}});if(!v.ok)throw new Error("Failed");return v.json()},enabled:!!n}),g=Ue({mutationFn:async v=>{const x=await fetch("/api/event-orders",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(v)});if(!x.ok)throw new Error("Failed to create");return x.json()},onSuccess:v=>{t.invalidateQueries({queryKey:["event-orders"]}),i(!1),e(`/event-orders/${v.id}`)}}),m=Ue({mutationFn:async v=>{if(!(await fetch(`/api/event-orders/${v}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed")},onSuccess:()=>t.invalidateQueries({queryKey:["event-orders"]})}),y={DRAFT:"#f59e0b",FINALISED:"#3b82f6",ORDERED:"#22c55e"};return s.jsxs("div",{style:Pr.page,children:[s.jsxs("div",{style:Pr.header,children:[s.jsx("h2",{style:{margin:0},children:"Event Orders"}),s.jsx("button",{onClick:()=>{i(!0),a(""),d(""),u("")},style:Pr.primaryBtn,children:"+ New Event Order"})]}),p?s.jsx("div",{style:Pr.loading,children:"Loading..."}):f&&f.length>0?s.jsxs("table",{style:Pr.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Pr.th,children:"Name"}),s.jsx("th",{style:Pr.th,children:"Date"}),s.jsx("th",{style:Pr.th,children:"Status"}),s.jsx("th",{style:Pr.th,children:"Recipes"}),s.jsx("th",{style:Pr.th,children:"Actions"})]})}),s.jsx("tbody",{children:f.map(v=>s.jsxs("tr",{style:Pr.tr,onClick:()=>e(`/event-orders/${v.id}`),children:[s.jsx("td",{style:{...Pr.td,fontWeight:500,cursor:"pointer"},children:v.name}),s.jsx("td",{style:Pr.td,children:v.event_date||"-"}),s.jsx("td",{style:Pr.td,children:s.jsx("span",{style:{background:y[v.status]||"#ccc",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.75rem",fontWeight:600},children:v.status})}),s.jsx("td",{style:Pr.td,children:v.item_count}),s.jsx("td",{style:Pr.td,children:v.status==="DRAFT"&&s.jsx("button",{onClick:x=>{x.stopPropagation(),m.mutate(v.id)},style:{...Pr.smallBtn,color:"#e94560"},children:"Delete"})})]},v.id))})]}):s.jsx("div",{style:{textAlign:"center",padding:"3rem",color:"#888"},children:"No event orders yet. Create one to start planning."}),r&&s.jsx("div",{style:Pr.overlay,children:s.jsxs("div",{style:Pr.modal,children:[s.jsxs("div",{style:Pr.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"New Event Order"}),s.jsx("button",{onClick:()=>i(!1),style:Pr.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Pr.modalBody,children:[s.jsx("label",{style:Pr.label,children:"Event Name *"}),s.jsx("input",{value:o,onChange:v=>a(v.target.value),style:Pr.input,placeholder:"e.g. Wedding Reception 15th March"}),s.jsx("label",{style:Pr.label,children:"Event Date"}),s.jsx("input",{type:"date",value:l,onChange:v=>d(v.target.value),style:Pr.input}),s.jsx("label",{style:Pr.label,children:"Notes"}),s.jsx("textarea",{value:c,onChange:v=>u(v.target.value),style:{...Pr.input,minHeight:"60px"}})]}),s.jsxs("div",{style:Pr.modalFooter,children:[s.jsx("button",{onClick:()=>i(!1),style:Pr.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>g.mutate({name:o,event_date:l||void 0,notes:c||void 0}),disabled:!o||g.isPending,style:Pr.primaryBtn,children:"Create"})]})]})})]})}const Pr={page:{padding:"1.5rem",maxWidth:"1000px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},tr:{borderBottom:"1px solid #f0f0f0",cursor:"pointer"},td:{padding:"0.6rem 0.75rem",fontSize:"0.85rem"},smallBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"}};function $fe(){const{id:n}=G_(),e=parseInt(n||"0"),{token:t}=gn(),r=go(),i=pi(),[o,a]=k.useState(null),[l,d]=k.useState(""),[c,u]=k.useState(null),[f,p]=k.useState("1"),[g,m]=k.useState(null),[y,v]=k.useState([]),[x,w]=k.useState("1"),[S,_]=k.useState(!1),[b,C]=k.useState(!1),{data:T}=Oe({queryKey:["event-order",e],queryFn:async()=>{const ue=await fetch(`/api/event-orders/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Not found");return ue.json()},enabled:!!t&&!!e}),F=o==="recipe"?"component":o==="dish"?"dish":null,{data:A}=Oe({queryKey:["recipes-for-event",F],queryFn:async()=>{const ue=await fetch(`/api/recipes?recipe_type=${F}`,{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Failed");return ue.json()},enabled:!!t&&(o==="recipe"||o==="dish")}),{data:D}=Oe({queryKey:["menus-for-event"],queryFn:async()=>{const ue=await fetch("/api/menus",{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Failed");return ue.json()},enabled:!!t&&o==="menu"&&!g}),{data:P}=Oe({queryKey:["menu-detail-for-event",g],queryFn:async()=>{const ue=await fetch(`/api/menus/${g}`,{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Failed");return ue.json()},enabled:!!t&&!!g}),{data:L}=Oe({queryKey:["event-shopping-list",e,b],queryFn:async()=>(await fetch(`/api/event-orders/${e}/shopping-list${b?"?group_by_supplier=true":""}`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&S}),W=Ue({mutationFn:async ue=>{if(!(await fetch(`/api/event-orders/${e}/items`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ue)})).ok)throw new Error("Failed")},onSuccess:()=>{i.invalidateQueries({queryKey:["event-order",e]}),i.invalidateQueries({queryKey:["event-shopping-list",e]}),I()}}),O=Ue({mutationFn:async ue=>{const Ze=await fetch(`/api/event-orders/${e}/items/bulk`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({items:ue})});if(!Ze.ok)throw new Error("Failed");return Ze.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["event-order",e]}),i.invalidateQueries({queryKey:["event-shopping-list",e]}),I()}}),U=Ue({mutationFn:async ue=>{if(!(await fetch(`/api/event-orders/items/${ue}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>{i.invalidateQueries({queryKey:["event-order",e]}),i.invalidateQueries({queryKey:["event-shopping-list",e]})}}),M=Ue({mutationFn:async ue=>{if(!(await fetch(`/api/event-orders/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({status:ue})})).ok)throw new Error("Failed")},onSuccess:()=>i.invalidateQueries({queryKey:["event-order",e]})});function I(){a(null),d(""),u(null),p("1"),m(null),v([]),w("1")}function H(ue){m(ue),d("")}const z=ue=>{const Ze=new Set(((T==null?void 0:T.items)||[]).map(Z=>Z.recipe_id)),ee=[];for(const Z of ue.divisions)for(const ge of Z.items)ge.recipe_id&&!ge.is_archived&&ee.push({recipe_id:ge.recipe_id,display_name:ge.display_name,division_name:Z.name,checked:!Ze.has(ge.recipe_id),quantity:parseInt(x)||1});v(ee)};P&&y.length===0&&g&&z(P);function G(ue){w(ue);const Ze=parseInt(ue)||1;v(ee=>ee.map(Z=>({...Z,quantity:Ze})))}function te(ue,Ze){v(ee=>ee.map((Z,ge)=>ge===ue?{...Z,quantity:parseInt(Ze)||0}:Z))}function re(ue){v(Ze=>Ze.map((ee,Z)=>Z===ue?{...ee,checked:!ee.checked}:ee))}function me(){const ue=y.filter(Ze=>Ze.checked&&Ze.quantity>0).map(Ze=>({recipe_id:Ze.recipe_id,quantity:Ze.quantity,notes:`From menu: ${(P==null?void 0:P.name)||""}`}));ue.length>0&&O.mutate(ue)}if(!T)return s.jsx("div",{style:gt.loading,children:"Loading event order..."});const J=T.items.reduce((ue,Ze)=>ue+(Ze.subtotal||0),0),ne=T.items.reduce((ue,Ze)=>Ze.recipe_type==="dish"?ue+Ze.quantity:ue+Ze.quantity*Ze.batch_portions,0),ye=(A||[]).filter(ue=>!l||ue.name.toLowerCase().includes(l.toLowerCase())),Ye=(D||[]).filter(ue=>ue.is_active).filter(ue=>!l||ue.name.toLowerCase().includes(l.toLowerCase())),De=(L==null?void 0:L.by_supplier)||{},qe=Object.keys(De).sort();return s.jsxs("div",{style:gt.page,children:[s.jsxs("div",{style:gt.topBar,children:[s.jsx("button",{onClick:()=>r("/event-orders"),style:gt.backBtn,children:"← Back"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[T.status==="DRAFT"&&s.jsx("button",{onClick:()=>M.mutate("FINALISED"),style:gt.secondaryBtn,children:"Finalise"}),T.status==="FINALISED"&&s.jsx("button",{onClick:()=>M.mutate("ORDERED"),style:gt.primaryBtn,children:"Mark Ordered"})]})]}),s.jsxs("div",{style:gt.headerCard,children:[s.jsxs("div",{children:[s.jsx("h2",{style:{margin:0},children:T.name}),T.event_date&&s.jsx("div",{style:{color:"#888",marginTop:"4px"},children:T.event_date}),T.notes&&s.jsx("div",{style:{color:"#666",marginTop:"4px",fontSize:"0.85rem"},children:T.notes})]}),s.jsx("span",{style:{background:T.status==="DRAFT"?"#f59e0b":T.status==="FINALISED"?"#3b82f6":"#22c55e",color:"white",padding:"4px 12px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},children:T.status})]}),s.jsxs("div",{style:gt.section,children:[s.jsxs("div",{style:gt.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Items"}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem"},children:[s.jsx("button",{onClick:()=>a("recipe"),style:gt.addBtn,children:"+ Recipe"}),s.jsx("button",{onClick:()=>a("dish"),style:gt.addBtn,children:"+ Dish"}),s.jsx("button",{onClick:()=>a("menu"),style:{...gt.addBtn,background:"#eff6ff",borderColor:"#93c5fd"},children:"+ Menu"})]})]}),T.items.length>0?s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Recipe"}),s.jsx("th",{style:gt.th,children:"Type"}),s.jsx("th",{style:gt.th,children:"Quantity"}),s.jsx("th",{style:gt.th,children:"Cost/Portion"}),s.jsx("th",{style:gt.th,children:"Subtotal"}),s.jsx("th",{style:gt.th})]})}),s.jsx("tbody",{children:T.items.map(ue=>s.jsxs("tr",{children:[s.jsxs("td",{style:gt.td,children:[s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>r(`/recipes/${ue.recipe_id}`),children:ue.recipe_name}),ue.notes&&s.jsx("span",{style:{fontSize:"0.7rem",color:"#999",marginLeft:"0.5rem"},children:ue.notes})]}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.recipe_type==="component"?`Component (${ue.batch_portions} per batch)`:"Dish"})}),s.jsx("td",{style:gt.td,children:ue.quantity}),s.jsx("td",{style:gt.td,children:ue.cost_per_portion!=null?`£${ue.cost_per_portion.toFixed(2)}`:"-"}),s.jsx("td",{style:gt.td,children:ue.subtotal!=null?`£${ue.subtotal.toFixed(2)}`:"-"}),s.jsx("td",{style:gt.td,children:s.jsx("button",{onClick:()=>U.mutate(ue.id),style:gt.removeBtn,children:"✕"})})]},ue.id))}),s.jsx("tfoot",{children:s.jsxs("tr",{style:{borderTop:"2px solid #ddd"},children:[s.jsx("td",{colSpan:4,style:{...gt.td,fontWeight:600,textAlign:"right"},children:"Total:"}),s.jsxs("td",{style:{...gt.td,fontWeight:600},children:["£",J.toFixed(2)]}),s.jsx("td",{})]})})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",padding:"1rem 0"},children:"No items added yet"}),T.items.length>0&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666",marginTop:"0.5rem"},children:["~",ne," total servings | £",ne>0?(J/ne).toFixed(2):"0.00","/head"]})]}),T.items.length>0&&s.jsxs("div",{style:gt.section,children:[s.jsxs("div",{style:gt.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Shopping List"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsxs("label",{style:{fontSize:"0.8rem"},children:[s.jsx("input",{type:"checkbox",checked:b,onChange:ue=>C(ue.target.checked)})," ","Group by supplier"]}),s.jsxs("button",{onClick:()=>_(!S),style:gt.addBtn,children:[S?"Hide":"Show"," Shopping List"]})]})]}),S&&L&&!b&&s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Ingredient"}),s.jsx("th",{style:gt.th,children:"Category"}),s.jsx("th",{style:gt.th,children:"Quantity"}),s.jsx("th",{style:gt.th,children:"Source"}),s.jsx("th",{style:gt.th,children:"Packs"}),s.jsx("th",{style:gt.th,children:"Est. Cost"})]})}),s.jsx("tbody",{children:L.items.map(ue=>s.jsxs("tr",{children:[s.jsx("td",{style:gt.td,children:ue.ingredient_name}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.category})}),s.jsxs("td",{style:gt.td,children:[ue.adjusted_quantity,ue.unit]}),s.jsx("td",{style:gt.td,children:ue.sources.length>0?ue.sources[0].supplier_name:s.jsx("span",{style:{color:"#f59e0b",fontSize:"0.8rem"},children:"No source"})}),s.jsx("td",{style:gt.td,children:ue.sources.length>0&&ue.sources[0].suggested_packs?`${ue.sources[0].suggested_packs} × ${ue.sources[0].pack_description||"pack"}`:"-"}),s.jsx("td",{style:gt.td,children:ue.sources.length>0&&ue.sources[0].subtotal!=null?`£${ue.sources[0].subtotal.toFixed(2)}`:"-"})]},ue.ingredient_id))})]}),S&&L&&b&&s.jsxs("div",{children:[qe.length===0&&s.jsx("p",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No supplier data available"}),qe.map(ue=>{const Ze=De[ue],ee=Ze.reduce((Z,ge)=>Z+(ge.subtotal||0),0);return s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.4rem 0.5rem",background:"#f8f9fa",borderRadius:"4px",marginBottom:"0.25rem"},children:[s.jsx("strong",{style:{fontSize:"0.85rem"},children:ue}),ee>0&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#666"},children:["£",ee.toFixed(2)]})]}),s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Ingredient"}),s.jsx("th",{style:gt.th,children:"Quantity"}),s.jsx("th",{style:gt.th,children:"Packs"}),s.jsx("th",{style:gt.th,children:"Est. Cost"})]})}),s.jsx("tbody",{children:Ze.map((Z,ge)=>s.jsxs("tr",{children:[s.jsx("td",{style:gt.td,children:Z.ingredient_name}),s.jsxs("td",{style:gt.td,children:[Z.quantity_needed,Z.unit]}),s.jsx("td",{style:gt.td,children:Z.suggested_packs?`${Z.suggested_packs} × ${Z.pack_description||"pack"}`:"-"}),s.jsx("td",{style:gt.td,children:Z.subtotal!=null?`£${Z.subtotal.toFixed(2)}`:"-"})]},ge))})]})]},ue)}),L.items.filter(ue=>ue.sources.length===0).length>0&&s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("div",{style:{padding:"0.4rem 0.5rem",background:"#fef3c7",borderRadius:"4px",marginBottom:"0.25rem"},children:s.jsx("strong",{style:{fontSize:"0.85rem",color:"#92400e"},children:"No Supplier"})}),s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Ingredient"}),s.jsx("th",{style:gt.th,children:"Category"}),s.jsx("th",{style:gt.th,children:"Quantity"})]})}),s.jsx("tbody",{children:L.items.filter(ue=>ue.sources.length===0).map(ue=>s.jsxs("tr",{children:[s.jsx("td",{style:gt.td,children:ue.ingredient_name}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.category})}),s.jsxs("td",{style:gt.td,children:[ue.adjusted_quantity,ue.unit]})]},ue.ingredient_id))})]})]})]})]}),(o==="recipe"||o==="dish")&&s.jsx("div",{style:gt.overlay,onClick:I,children:s.jsxs("div",{style:gt.modal,onClick:ue=>ue.stopPropagation(),children:[s.jsxs("div",{style:gt.modalHeader,children:[s.jsxs("h3",{style:{margin:0},children:["Add ",o==="recipe"?"Recipe":"Dish"]}),s.jsx("button",{onClick:I,style:gt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:gt.modalBody,children:[s.jsx("input",{type:"text",value:l,onChange:ue=>d(ue.target.value),placeholder:`Search ${o==="recipe"?"recipes":"dishes"}...`,style:gt.input,autoFocus:!0}),s.jsxs("div",{style:{maxHeight:"250px",overflow:"auto",border:"1px solid #eee",borderRadius:"6px",marginTop:"0.5rem"},children:[ye.map(ue=>s.jsxs("div",{onClick:()=>u(ue.id),style:{padding:"0.5rem 0.75rem",cursor:"pointer",background:c===ue.id?"#eff6ff":"#fff",borderBottom:"1px solid #f3f4f6",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontWeight:c===ue.id?600:400,fontSize:"0.9rem"},children:ue.name}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:o==="recipe"?`batch: ${ue.batch_portions}`:ue.cost_per_portion!=null?`£${ue.cost_per_portion.toFixed(2)}/portion`:""})]},ue.id)),ye.length===0&&s.jsxs("p",{style:{padding:"0.75rem",color:"#999",textAlign:"center",margin:0,fontSize:"0.85rem"},children:["No ",o==="recipe"?"recipes":"dishes"," found"]})]}),c&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{style:gt.label,children:["Quantity (",o==="recipe"?"batches":"servings",")"]}),s.jsx("input",{type:"number",value:f,onChange:ue=>p(ue.target.value),style:gt.input,min:"1"})]})]}),s.jsxs("div",{style:gt.modalFooter,children:[s.jsx("button",{onClick:I,style:gt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>c&&W.mutate({recipe_id:c,quantity:parseInt(f)||1}),disabled:!c||!f||W.isPending,style:gt.primaryBtn,children:W.isPending?"Adding...":"Add"})]})]})}),o==="menu"&&s.jsx("div",{style:gt.overlay,onClick:I,children:s.jsxs("div",{style:{...gt.modal,width:"600px"},onClick:ue=>ue.stopPropagation(),children:[s.jsxs("div",{style:gt.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:g?`Add from: ${(P==null?void 0:P.name)||"Loading..."}`:"Add Menu"}),s.jsx("button",{onClick:I,style:gt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:gt.modalBody,children:[!g&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:l,onChange:ue=>d(ue.target.value),placeholder:"Search menus...",style:gt.input,autoFocus:!0}),s.jsxs("div",{style:{maxHeight:"300px",overflow:"auto",border:"1px solid #eee",borderRadius:"6px",marginTop:"0.5rem"},children:[Ye.map(ue=>s.jsxs("div",{onClick:()=>H(ue.id),style:{padding:"0.6rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f3f4f6",display:"flex",justifyContent:"space-between",alignItems:"center"},onMouseEnter:Ze=>Ze.currentTarget.style.background="#f9fafb",onMouseLeave:Ze=>Ze.currentTarget.style.background="#fff",children:[s.jsxs("div",{children:[s.jsx("span",{style:{fontWeight:500,fontSize:"0.9rem"},children:ue.name}),ue.description&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:ue.description})]}),s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:[ue.item_count," dish",ue.item_count!==1?"es":""]})]},ue.id)),Ye.length===0&&s.jsx("p",{style:{padding:"0.75rem",color:"#999",textAlign:"center",margin:0,fontSize:"0.85rem"},children:"No active menus found"})]})]}),g&&y.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"0.75rem"},children:[s.jsx("label",{style:{fontSize:"0.8rem",fontWeight:600,color:"#555",whiteSpace:"nowrap"},children:"Covers:"}),s.jsx("input",{type:"number",value:x,onChange:ue=>G(ue.target.value),style:{...gt.input,width:"80px"},min:"1"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:"Sets quantity for all dishes"})]}),s.jsx("div",{style:{maxHeight:"350px",overflow:"auto",border:"1px solid #eee",borderRadius:"6px"},children:s.jsxs("table",{style:{...gt.table,fontSize:"0.85rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...gt.th,width:"30px"}}),s.jsx("th",{style:gt.th,children:"Dish"}),s.jsx("th",{style:gt.th,children:"Section"}),s.jsx("th",{style:{...gt.th,width:"80px"},children:"Qty"})]})}),s.jsx("tbody",{children:y.map((ue,Ze)=>{const ee=((T==null?void 0:T.items)||[]).some(Z=>Z.recipe_id===ue.recipe_id);return s.jsxs("tr",{style:{opacity:ee?.5:1},children:[s.jsx("td",{style:gt.td,children:s.jsx("input",{type:"checkbox",checked:ue.checked,onChange:()=>re(Ze),disabled:ee})}),s.jsxs("td",{style:gt.td,children:[ue.display_name,ee&&s.jsx("span",{style:{fontSize:"0.7rem",color:"#f59e0b",marginLeft:"0.5rem"},children:"already added"})]}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.division_name})}),s.jsx("td",{style:gt.td,children:s.jsx("input",{type:"number",value:ue.quantity,onChange:Z=>te(Ze,Z.target.value),style:{width:"60px",padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.85rem",textAlign:"center"},min:"0",disabled:!ue.checked||ee})})]},Ze)})})]})})]}),g&&y.length===0&&P&&s.jsx("p",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No dishes on this menu"})]}),s.jsxs("div",{style:gt.modalFooter,children:[g&&s.jsx("button",{onClick:()=>{m(null),v([]),d("")},style:gt.cancelBtn,children:"← Back"}),s.jsx("button",{onClick:I,style:gt.cancelBtn,children:"Cancel"}),g&&s.jsx("button",{onClick:me,disabled:y.filter(ue=>ue.checked&&ue.quantity>0).length===0||O.isPending,style:gt.primaryBtn,children:O.isPending?"Adding...":`Add ${y.filter(ue=>ue.checked&&ue.quantity>0).length} Dishes`})]})]})})]})}const gt={page:{padding:"1.5rem",maxWidth:"1100px",margin:"0 auto"},topBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},backBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},headerCard:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",background:"white",padding:"1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},section:{background:"white",padding:"1rem 1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666"},td:{padding:"0.4rem 0.5rem",fontSize:"0.85rem",borderBottom:"1px solid #f0f0f0"},addBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},removeBtn:{padding:"2px 6px",background:"none",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.7rem",color:"#e94560"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},secondaryBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"}};function $P(n,e){return e==="g"&&n<1?`£${(n*1e3).toFixed(2)}/kg`:e==="ml"&&n<1?`£${(n*1e3).toFixed(2)}/ltr`:`£${n.toFixed(4)}/${e||"?"}`}function Zfe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(""),[o,a]=k.useState(""),[l,d]=k.useState(!1),[c,u]=k.useState(!1),[f,p]=k.useState("list"),[g,m]=k.useState(!1),[y,v]=k.useState(!1),[x,w]=k.useState(30),[S,_]=k.useState(null),[b,C]=k.useState(null),[T,F]=k.useState(""),[A,D]=k.useState(""),[P,L]=k.useState(""),[W,O]=k.useState({}),[U,M]=k.useState(null),[I,H]=k.useState(""),[z,G]=k.useState(""),[te,re]=k.useState(""),[me,J]=k.useState(""),[ne,ye]=k.useState(""),{data:ke}=Oe({queryKey:["dish-courses"],queryFn:async()=>{const Y=await fetch("/api/recipes/menu-sections?section_type=dish",{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch sections");return Y.json()},enabled:!!n}),{data:Ye,isLoading:De}=Oe({queryKey:["dishes",r,o,y],queryFn:async()=>{const Y=new URLSearchParams;r&&Y.set("search",r),Y.set("recipe_type","dish"),o&&Y.set("menu_section_id",o),y&&Y.set("archived","true");const Q=await fetch(`/api/recipes?${Y}`,{headers:{Authorization:`Bearer ${n}`}});if(!Q.ok)throw new Error("Failed to fetch dishes");return Q.json()},enabled:!!n}),{data:qe}=Oe({queryKey:["price-impact-dishes",x],queryFn:async()=>{const Y=await fetch(`/api/recipes/price-impact?days=${x}`,{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch price impact");return Y.json()},enabled:!!n}),ue=new Map;qe==null||qe.recipes.filter(Y=>Y.recipe_type==="dish").forEach(Y=>ue.set(Y.recipe_id,Y));const{data:Ze}=Oe({queryKey:["cost-trend",S],queryFn:async()=>{const Y=await fetch(`/api/recipes/${S}/cost-trend`,{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch cost trend");return Y.json()},enabled:!!n&&!!S}),ee=Ue({mutationFn:async Y=>{const Q=await fetch("/api/recipes",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!Q.ok)throw new Error("Failed to create dish");return Q.json()},onSuccess:Y=>{t.invalidateQueries({queryKey:["dishes"]}),d(!1),e(`/dishes/${Y.id}`)}}),Z=Ue({mutationFn:async Y=>{const Q=await fetch(`/api/recipes/${Y}/duplicate`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!Q.ok)throw new Error("Failed to duplicate");return Q.json()},onSuccess:Y=>{t.invalidateQueries({queryKey:["dishes"]}),e(`/dishes/${Y.id}`)}}),ge=Ue({mutationFn:async Y=>{if(!(await fetch(`/api/recipes/${Y}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to archive")},onSuccess:()=>t.invalidateQueries({queryKey:["dishes"]})}),Te=Ue({mutationFn:async Y=>{if(!(await fetch(`/api/recipes/${Y}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_archived:!1})})).ok)throw new Error("Failed to unarchive")},onSuccess:()=>t.invalidateQueries({queryKey:["dishes"]})}),Be=Ue({mutationFn:async Y=>{const Q=await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Y,section_type:"dish"})});if(!Q.ok)throw new Error("Failed to create course");return Q.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["dish-courses"]}),ye(""),u(!1)}}),he=Ue({mutationFn:async({id:Y,name:Q})=>{const X=await fetch(`/api/recipes/menu-sections/${Y}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Q})});if(!X.ok)throw new Error("Failed to update course");return X.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["dish-courses"]}),t.invalidateQueries({queryKey:["dishes"]}),M(null),H("")}}),He=Ue({mutationFn:async Y=>{const Q=await fetch(`/api/recipes/menu-sections/${Y}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!Q.ok)throw new Error("Failed to delete course");return Q.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["dish-courses"]}),t.invalidateQueries({queryKey:["dishes"]})}}),{data:Ge}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const Y=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch flag categories");return Y.json()},enabled:!!n&&g}),ae=(()=>{let Y=Ye||[];if(T.trim()){const pe=T.toLowerCase();Y=Y.filter(we=>we.name.toLowerCase().includes(pe)||we.flag_summary.some(Ne=>Ne.name.toLowerCase().includes(pe)))}if(A){const pe=parseFloat(A);isNaN(pe)||(Y=Y.filter(we=>we.cost_per_portion!=null&&we.cost_per_portion>=pe))}if(P){const pe=parseFloat(P);isNaN(pe)||(Y=Y.filter(we=>we.cost_per_portion!=null&&we.cost_per_portion<=pe))}const Q=Object.entries(W).filter(([,pe])=>pe==="include").map(([pe])=>pe),X=Object.entries(W).filter(([,pe])=>pe==="exclude").map(([pe])=>pe);return Q.length>0&&(Y=Y.filter(pe=>Q.every(we=>pe.flag_summary.some(Ne=>Ne.name===we&&Ne.active)))),X.length>0&&(Y=Y.filter(pe=>!X.some(we=>pe.flag_summary.some(Ne=>Ne.name===we&&Ne.active)))),Y})(),K=Y=>{const Q=ue.get(Y),X=S===Y?Ze==null?void 0:Ze.snapshots:void 0;return s.jsxs("div",{children:[X&&X.length>1&&(()=>{const pe=X.map(ot=>ot.cost_per_portion),we=Math.min(...pe),Ne=Math.max(...pe),st=Ne-we||1,Ve=460,Re=110,Le=40,rt=18,$e=Ve-Le*2,ce=Re-rt*2,Je=X.map((ot,ut)=>{const Ot=Le+ut/(X.length-1)*$e,An=rt+ce-(ot.cost_per_portion-we)/st*ce;return{x:Ot,y:An,...ot}}),jt=Je.map(ot=>`${ot.x},${ot.y}`).join(" "),ct=[we,we+st/2,Ne],Se=[0,Math.floor(X.length/2),X.length-1];return s.jsx("div",{children:s.jsxs("div",{style:{position:"relative"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"#888",marginBottom:"4px"},children:"Cost Trend"}),s.jsxs("svg",{width:Ve,height:Re,style:{background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[ct.map((ot,ut)=>{const Ot=rt+ce-(ot-we)/st*ce;return s.jsxs("g",{children:[s.jsx("line",{x1:Le,y1:Ot,x2:Ve-Le,y2:Ot,stroke:"#f0f0f0",strokeWidth:"1"}),s.jsxs("text",{x:Le-4,y:Ot+3,textAnchor:"end",fontSize:"9",fill:"#888",children:["£",ot.toFixed(2)]})]},ut)}),Se.filter((ot,ut,Ot)=>Ot.indexOf(ot)===ut).map(ot=>{const ut=Je[ot],Ot=new Date(ut.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"});return s.jsx("text",{x:ut.x,y:Re-2,textAnchor:"middle",fontSize:"9",fill:"#888",children:Ot},ot)}),s.jsx("polyline",{points:jt,fill:"none",stroke:"#e94560",strokeWidth:"2"}),Je.map((ot,ut)=>s.jsx("circle",{cx:ot.x,cy:ot.y,r:3.5,fill:"#e94560",stroke:"white",strokeWidth:"1.5",style:{cursor:"pointer"},onMouseEnter:()=>{C({x:ot.x,y:ot.y-10,date:new Date(ot.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),cost:`£${ot.cost_per_portion.toFixed(2)}`,trigger:ot.trigger})},onMouseLeave:()=>C(null)},ut))]}),b&&s.jsxs("div",{style:{position:"absolute",left:b.x,top:b.y-50,transform:"translateX(-50%)",background:"#333",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"0.75rem",whiteSpace:"nowrap",pointerEvents:"none",zIndex:20},children:[s.jsx("div",{children:b.date}),s.jsx("div",{children:b.cost}),b.trigger&&s.jsx("div",{style:{color:"#ccc",fontSize:"0.7rem"},children:b.trigger})]})]})})})(),X&&X.length<=1&&s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.8rem",marginBottom:"6px"},children:"Not enough data for trend chart"}),!X&&s.jsx("div",{style:{color:"#888",fontSize:"0.8rem"},children:"Loading cost trend..."}),Q&&Q.ingredient_changes.length>0&&s.jsxs("div",{style:{marginTop:"8px"},children:[s.jsxs("div",{style:{fontWeight:600,fontSize:"0.7rem",color:"#888",marginBottom:"4px"},children:["Ingredient Price Changes (",Q.ingredient_changes.length,") — last ",x," days"]}),s.jsx("div",{style:{fontSize:"0.8rem",color:"#555"},children:Q.ingredient_changes.map((pe,we)=>s.jsxs("div",{style:{padding:"3px 0",borderBottom:wee(`/invoice/${pe.source_invoice_id}`),children:pe.source_invoice_number||`#${pe.source_invoice_id}`}),pe.ingredient_name&&pe.old_price!=null&&pe.new_price!=null?s.jsxs(s.Fragment,{children:[pe.ingredient_name,": ",$P(pe.old_price,pe.unit)," ","→"," ",$P(pe.new_price,pe.unit)]}):pe.ingredient_name&&pe.new_price!=null&&pe.old_price==null?s.jsxs(s.Fragment,{children:[pe.ingredient_name," price set: ",$P(pe.new_price,pe.unit)]}):pe.summary]}),pe.cost_impact!=null&&s.jsxs("span",{style:{fontFamily:"monospace",fontWeight:600,fontSize:"0.75rem",color:pe.cost_impact>0?"#dc2626":pe.cost_impact<0?"#16a34a":"#888",marginLeft:"1rem",whiteSpace:"nowrap"},children:[pe.cost_impact>0?"+":"","£",pe.cost_impact.toFixed(4),"/",Q.output_unit]})]},we))})]})]})},de=()=>{ee.mutate({name:z,recipe_type:"dish",menu_section_id:te?parseInt(te):null,batch_portions:1,description:me||null})};return s.jsxs("div",{style:_t.page,children:[s.jsxs("div",{style:_t.header,children:[s.jsx("h2",{style:{margin:0},children:"Dishes"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>u(!0),style:_t.secondaryBtn,children:"+ Course"}),s.jsx("button",{onClick:()=>{d(!0),G(""),re(""),J("")},style:_t.primaryBtn,children:"+ New Dish"})]})]}),s.jsxs("div",{style:_t.statsBar,children:[s.jsxs("span",{children:[ae.length," ",y?"archived ":"","dishes"]}),ue.size>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{style:{color:"#dc2626",fontWeight:600},children:[ue.size," with cost changes"]})]})]}),s.jsxs("div",{style:_t.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search dishes...",value:r,onChange:Y=>i(Y.target.value),style:_t.searchInput}),s.jsxs("select",{value:o,onChange:Y=>a(Y.target.value),style:_t.select,children:[s.jsx("option",{value:"",children:"All Courses"}),ke==null?void 0:ke.map(Y=>s.jsxs("option",{value:Y.id,children:[Y.name," (",Y.recipe_count,")"]},Y.id))]}),s.jsxs("label",{style:_t.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:y,onChange:Y=>v(Y.target.checked)}),"Show Archived"]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.35rem"},children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",whiteSpace:"nowrap"},children:"Cost changes:"}),s.jsxs("select",{value:x,onChange:Y=>w(Number(Y.target.value)),style:{..._t.select,padding:"0.35rem 0.4rem",fontSize:"0.8rem"},children:[s.jsx("option",{value:7,children:"7d"}),s.jsx("option",{value:14,children:"14d"}),s.jsx("option",{value:30,children:"30d"}),s.jsx("option",{value:60,children:"60d"}),s.jsx("option",{value:90,children:"90d"})]})]}),s.jsx("button",{onClick:()=>m(!g),style:{..._t.secondaryBtn,padding:"0.5rem 0.75rem",fontSize:"0.85rem"},children:g?"Hide Filters":"Show Filters"}),s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"2px"},children:[s.jsx("button",{onClick:()=>p("card"),style:{..._t.viewToggleBtn,...f==="card"?_t.viewToggleBtnActive:{},borderRadius:"4px 0 0 4px"},children:"Cards"}),s.jsx("button",{onClick:()=>p("list"),style:{..._t.viewToggleBtn,...f==="list"?_t.viewToggleBtnActive:{},borderRadius:"0 4px 4px 0"},children:"List"})]})]}),g&&s.jsx("div",{style:_t.advancedFilterPanel,children:s.jsxs("div",{style:{display:"flex",gap:"1rem",flexWrap:"wrap",alignItems:"flex-start"},children:[s.jsxs("div",{style:{minWidth:"200px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Contains ingredient"}),s.jsx("input",{type:"text",placeholder:"Search by ingredient...",value:T,onChange:Y=>F(Y.target.value),style:{..._t.searchInput,width:"100%"}})]}),s.jsxs("div",{style:{minWidth:"150px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Cost/portion range"}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",placeholder:"Min",value:A,onChange:Y=>D(Y.target.value),style:{..._t.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"}),s.jsx("span",{style:{color:"#888"},children:"-"}),s.jsx("input",{type:"number",placeholder:"Max",value:P,onChange:Y=>L(Y.target.value),style:{..._t.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"})]})]}),Ge&&Ge.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"250px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Food flag filters"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Ge.flatMap(Y=>Y.flags||[]).map(Y=>{const Q=W[Y.name]||"neutral",X=Q==="neutral"?"include":Q==="include"?"exclude":"neutral";return s.jsxs("button",{onClick:()=>O(pe=>{const we={...pe};return X==="neutral"?delete we[Y.name]:we[Y.name]=X,we}),style:{padding:"2px 8px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:600,cursor:"pointer",border:"1px solid",borderColor:Q==="include"?"#22c55e":Q==="exclude"?"#ef4444":"#ddd",background:Q==="include"?"#dcfce7":Q==="exclude"?"#fef2f2":"white",color:Q==="include"?"#166534":Q==="exclude"?"#991b1b":"#666"},title:`${Y.name}: ${Q} (click to cycle)`,children:[Q==="include"?"+ ":Q==="exclude"?"- ":"",Y.code||Y.name]},Y.id)})})]})]})}),De?s.jsx("div",{style:_t.loading,children:"Loading dishes..."}):f==="card"?s.jsx("div",{style:_t.grid,children:ae.map(Y=>s.jsxs("div",{style:{..._t.card,...Y.is_archived?{opacity:.6}:{}},onClick:()=>e(`/dishes/${Y.id}`),children:[s.jsxs("div",{style:_t.cardHeader,children:[s.jsx("span",{style:{fontWeight:600,fontSize:"1rem",...Y.is_archived?{textDecoration:"line-through"}:{}},children:Y.name}),s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[Y.is_archived&&s.jsx("span",{style:{background:"#999",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"ARCHIVED"}),s.jsx("span",{style:{background:"#3b82f6",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600,textTransform:"uppercase"},children:"DISH"})]})]}),Y.menu_section_name&&s.jsx("div",{style:_t.sectionTag,children:Y.menu_section_name}),Y.kds_menu_item_name&&s.jsxs("div",{style:{fontSize:"0.7rem",color:"#999",marginTop:"0.15rem"},children:["SambaPOS: ",Y.kds_menu_item_name,Y.sambapos_portion_name&&Y.sambapos_portion_name!=="Normal"&&` (${Y.sambapos_portion_name})`]}),s.jsxs("div",{style:_t.cardMeta,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Y.cost_per_portion!=null?s.jsxs("span",{style:_t.costBadge,children:["£",Y.cost_per_portion.toFixed(2),"/portion"]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"No costing"}),ue.has(Y.id)&&(()=>{const Q=ue.get(Y.id),X=(Q.cost_change??0)>0;return s.jsxs("span",{onClick:pe=>{pe.stopPropagation(),_(S===Y.id?null:Y.id),C(null)},style:{background:X?"#fef2f2":"#f0fdf4",color:X?"#dc2626":"#16a34a",border:`1px solid ${X?"#fca5a5":"#86efac"}`,padding:"1px 6px",borderRadius:"10px",fontSize:"0.65rem",fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},title:`${Q.ingredient_changes.length} ingredient price change(s) in last ${x}d`,children:[X?"▲":"▼"," ",Q.cost_change_pct!=null?`${Q.cost_change_pct>0?"+":""}${Q.cost_change_pct}%`:""]})})()]}),Y.gross_sell_price!=null&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#555"},children:["Sell: ","£",Y.gross_sell_price.toFixed(2)]}),Y.gross_sell_price!=null&&Y.cost_per_portion!=null&&(()=>{const Q=Y.gross_sell_price/1.2,X=(Q-Y.cost_per_portion)/Q*100;return s.jsxs("span",{style:{fontSize:"0.8rem",fontWeight:600,color:X>=70?"#16a34a":X>=60?"#ca8a04":"#dc2626"},children:[X.toFixed(1),"% GP"]})})()]}),S===Y.id&&s.jsx("div",{onClick:Q=>Q.stopPropagation(),style:{marginTop:"8px",borderTop:"1px solid #eee",paddingTop:"8px"},children:K(Y.id)}),Y.flag_summary.length>0&&s.jsx("div",{style:{marginTop:"6px"},children:s.jsx(T0,{flags:Y.flag_summary})}),s.jsxs("div",{style:_t.cardActions,children:[s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Z.mutate(Y.id)},style:_t.actionBtn,children:"Duplicate"}),Y.is_archived?s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Te.mutate(Y.id)},style:{..._t.actionBtn,color:"#22c55e"},children:"Restore"}):s.jsx("button",{onClick:Q=>{Q.stopPropagation(),ge.mutate(Y.id)},style:{..._t.actionBtn,color:"#e94560"},children:"Archive"})]})]},Y.id))}):s.jsxs("table",{style:_t.listTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:_t.listTh,children:"Name"}),s.jsx("th",{style:_t.listTh,children:"Type"}),s.jsx("th",{style:_t.listTh,children:"Course"}),s.jsx("th",{style:_t.listTh,children:"Cost/Portion"}),s.jsx("th",{style:_t.listTh,children:"Sell Price"}),s.jsx("th",{style:_t.listTh,children:"GP%"}),s.jsx("th",{style:_t.listTh,children:"Flags"}),s.jsx("th",{style:_t.listTh,children:"Actions"})]})}),s.jsx("tbody",{children:ae.map(Y=>s.jsxs(s.Fragment,{children:[s.jsxs("tr",{style:{..._t.listTr,cursor:"pointer",...Y.is_archived?{opacity:.6}:{}},onClick:()=>e(`/dishes/${Y.id}`),children:[s.jsxs("td",{style:_t.listTd,children:[s.jsx("span",{style:{fontWeight:500,...Y.is_archived?{textDecoration:"line-through"}:{}},children:Y.name}),Y.is_archived&&s.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.7rem",color:"#999",fontStyle:"italic"},children:"archived"})]}),s.jsx("td",{style:_t.listTd,children:s.jsx("span",{style:{background:"#3b82f6",color:"white",padding:"1px 6px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600,textTransform:"uppercase"},children:"DISH"})}),s.jsx("td",{style:_t.listTd,children:Y.menu_section_name||"-"}),s.jsx("td",{style:_t.listTd,children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Y.cost_per_portion!=null?s.jsxs("span",{style:_t.costBadge,children:["£",Y.cost_per_portion.toFixed(2)]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"}),ue.has(Y.id)&&(()=>{const Q=ue.get(Y.id),X=(Q.cost_change??0)>0;return s.jsxs("span",{onClick:pe=>{pe.stopPropagation(),_(S===Y.id?null:Y.id),C(null)},style:{background:X?"#fef2f2":"#f0fdf4",color:X?"#dc2626":"#16a34a",border:`1px solid ${X?"#fca5a5":"#86efac"}`,padding:"1px 6px",borderRadius:"10px",fontSize:"0.65rem",fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},title:`${Q.ingredient_changes.length} ingredient price change(s) in last ${x}d — click to expand`,children:[X?"▲":"▼"," ",Q.cost_change_pct!=null?`${Q.cost_change_pct>0?"+":""}${Q.cost_change_pct}%`:""]})})()]})}),s.jsx("td",{style:_t.listTd,children:Y.gross_sell_price!=null?s.jsxs("span",{children:["£",Y.gross_sell_price.toFixed(2)]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"})}),s.jsx("td",{style:_t.listTd,children:Y.gross_sell_price!=null&&Y.cost_per_portion!=null?(()=>{const Q=Y.gross_sell_price/1.2,X=(Q-Y.cost_per_portion)/Q*100;return s.jsxs("span",{style:{fontWeight:600,color:X>=70?"#16a34a":X>=60?"#ca8a04":"#dc2626"},children:[X.toFixed(1),"%"]})})():s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"})}),s.jsx("td",{style:_t.listTd,children:Y.flag_summary.length>0&&s.jsx(T0,{flags:Y.flag_summary})}),s.jsxs("td",{style:_t.listTd,children:[s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Z.mutate(Y.id)},style:_t.actionBtn,children:"Duplicate"}),Y.is_archived?s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Te.mutate(Y.id)},style:{..._t.actionBtn,color:"#22c55e",marginLeft:"4px"},children:"Restore"}):s.jsx("button",{onClick:Q=>{Q.stopPropagation(),ge.mutate(Y.id)},style:{..._t.actionBtn,color:"#e94560",marginLeft:"4px"},children:"Archive"})]})]},Y.id),S===Y.id&&s.jsx("tr",{children:s.jsx("td",{colSpan:8,style:{padding:"0.5rem 0.75rem 0.75rem 2rem",background:"#fafafa",borderBottom:"1px solid #e0e0e0"},children:K(Y.id)})},`${Y.id}-cost-detail`)]}))})]}),l&&s.jsx("div",{style:_t.overlay,children:s.jsxs("div",{style:_t.modal,children:[s.jsxs("div",{style:_t.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"New Dish"}),s.jsx("button",{onClick:()=>d(!1),style:_t.closeBtn,children:"✕"})]}),s.jsxs("div",{style:_t.modalBody,children:[s.jsx("label",{style:_t.label,children:"Name *"}),s.jsx("input",{value:z,onChange:Y=>G(Y.target.value),style:_t.input,placeholder:"e.g. Beef Burger, Caesar Salad"}),s.jsx("label",{style:_t.label,children:"Course"}),s.jsxs("select",{value:te,onChange:Y=>re(Y.target.value),style:_t.input,children:[s.jsx("option",{value:"",children:"None"}),ke==null?void 0:ke.map(Y=>s.jsx("option",{value:Y.id,children:Y.name},Y.id))]}),s.jsx("label",{style:_t.label,children:"Description"}),s.jsx("textarea",{value:me,onChange:Y=>J(Y.target.value),style:{..._t.input,minHeight:"60px"},placeholder:"Brief description..."})]}),s.jsxs("div",{style:_t.modalFooter,children:[s.jsx("button",{onClick:()=>d(!1),style:_t.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:de,disabled:!z||ee.isPending,style:_t.primaryBtn,children:ee.isPending?"Creating...":"Create Dish"})]})]})}),c&&s.jsx("div",{style:_t.overlay,children:s.jsxs("div",{style:{..._t.modal,width:"450px"},children:[s.jsxs("div",{style:_t.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Manage Courses"}),s.jsx("button",{onClick:()=>{u(!1),M(null)},style:_t.closeBtn,children:"✕"})]}),s.jsxs("div",{style:_t.modalBody,children:[ke&&ke.length>0&&s.jsx("div",{style:{marginBottom:"1rem"},children:ke.map(Y=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.4rem 0",borderBottom:"1px solid #f0f0f0"},children:U===Y.id?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:I,onChange:Q=>H(Q.target.value),style:{..._t.input,flex:1},autoFocus:!0}),s.jsx("button",{onClick:()=>he.mutate({id:Y.id,name:I}),disabled:!I.trim(),style:{..._t.actionBtn,color:"#22c55e"},children:"Save"}),s.jsx("button",{onClick:()=>{M(null),H("")},style:_t.actionBtn,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:"0.9rem"},children:Y.name}),s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:["(",Y.recipe_count,")"]}),s.jsx("button",{onClick:()=>{M(Y.id),H(Y.name)},style:_t.actionBtn,children:"Edit"}),s.jsx("button",{onClick:()=>{confirm(`Delete course "${Y.name}"? Dishes in this course will be unassigned.`)&&He.mutate(Y.id)},style:{..._t.actionBtn,color:"#e94560"},children:"Delete"})]})},Y.id))}),s.jsx("label",{style:_t.label,children:"Add New Course"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{value:ne,onChange:Y=>ye(Y.target.value),style:{..._t.input,flex:1},placeholder:"e.g. Starters, Mains, Desserts, Sides"}),s.jsx("button",{onClick:()=>Be.mutate(ne),disabled:!ne,style:_t.primaryBtn,children:"Add"})]})]}),s.jsx("div",{style:_t.modalFooter,children:s.jsx("button",{onClick:()=>{u(!1),M(null)},style:_t.cancelBtn,children:"Close"})})]})})]})}const _t={page:{padding:"1.5rem",maxWidth:"1400px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},statsBar:{display:"flex",gap:"0.75rem",fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},checkLabel:{display:"flex",alignItems:"center",gap:"0.35rem",fontSize:"0.85rem",color:"#555",cursor:"pointer",whiteSpace:"nowrap"},grid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:"1rem"},card:{background:"white",borderRadius:"8px",padding:"1rem",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",cursor:"pointer",transition:"box-shadow 0.2s",border:"1px solid #eee"},cardHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"0.5rem"},sectionTag:{fontSize:"0.75rem",color:"#888",marginTop:"2px"},cardMeta:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"8px"},costBadge:{background:"#f0fdf4",color:"#166534",padding:"2px 8px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},cardActions:{display:"flex",gap:"0.5rem",marginTop:"10px",borderTop:"1px solid #f0f0f0",paddingTop:"8px"},actionBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},secondaryBtn:{padding:"0.6rem 1.25rem",background:"white",color:"#333",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},viewToggleBtn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",background:"white",cursor:"pointer",fontSize:"0.8rem",color:"#666"},viewToggleBtnActive:{background:"#e94560",color:"white",borderColor:"#e94560"},advancedFilterPanel:{background:"#fafafa",border:"1px solid #eee",borderRadius:"8px",padding:"1rem",marginBottom:"1rem"},listTable:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},listTh:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},listTr:{borderBottom:"1px solid #f0f0f0"},listTd:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"}};function UK({menuId:n,divisions:e,preSelectedDivisionId:t,recipeId:r,recipeName:i,recipeDesc:o,recipePrice:a,onClose:l,onPublished:d}){const{token:c,user:u}=gn(),[f,p]=k.useState("select"),[g,m]=k.useState(r||null),[y,v]=k.useState(n||null),[x,w]=k.useState(t||null),[S,_]=k.useState(i||""),[b,C]=k.useState(o||""),[T,F]=k.useState(a?String(a):""),[A,D]=k.useState((u==null?void 0:u.name)||""),[P,L]=k.useState(""),[W,O]=k.useState(!1),{data:U}=Oe({queryKey:["settings"],queryFn:async()=>{const De=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${c}`}});return De.ok?De.json():{llm_enabled:!1,anthropic_api_key_set:!1}},staleTime:6e4}),M=async()=>{const De=g||r;if(De){O(!0);try{const qe=await fetch("/api/menus/generate-description",{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({recipe_id:De,recipe_name:S||i||"",ingredients:[],allergen_flags:[]})});if(qe.ok){const ue=await qe.json();ue.description&&C(ue.description)}}catch{}O(!1)}},{data:I}=Oe({queryKey:["dishes-for-menu"],queryFn:async()=>{const De=await fetch("/api/recipes?recipe_type=dish",{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed to fetch dishes");return De.json()},enabled:!!c&&!r}),{data:H}=Oe({queryKey:["menus-for-publish"],queryFn:async()=>{const De=await fetch("/api/menus",{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed to fetch menus");return De.json()},enabled:!!c&&!n}),{data:z}=Oe({queryKey:["menu-divisions",y],queryFn:async()=>{const De=await fetch(`/api/menus/${y}`,{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed");return De.json()},enabled:!!c&&!!y&&!n}),{data:G,isLoading:te}=Oe({queryKey:["recipe-flags-for-publish",g],queryFn:async()=>{const De=await fetch(`/api/food-flags/recipes/${g}/flags`,{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed");return De.json()},enabled:!!c&&!!g}),re=e||(z==null?void 0:z.divisions)||[],me=(H||[]).filter(De=>De.is_active),J=(G==null?void 0:G.unassessed_ingredients)||[],ne=((G==null?void 0:G.flags)||[]).filter(De=>De.is_active),ye=J.length>0;k.useEffect(()=>{if(g&&I){const De=I.find(qe=>qe.id===g);De&&(_(De.name),C(De.description||""),F(De.gross_sell_price?String(De.gross_sell_price):""))}},[g,I]);const ke=Ue({mutationFn:async()=>{var qe;const De=await fetch(`/api/menus/${y}/items`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({recipe_id:g,division_id:x,display_name:S.trim(),description:b.trim()||null,price:T?parseFloat(T):null,confirmed_by_name:A.trim()})});if(!De.ok){const ue=await De.json().catch(()=>({}));throw new Error(typeof ue.detail=="string"?ue.detail:((qe=ue.detail)==null?void 0:qe.message)||"Failed to publish")}return De.json()},onSuccess:()=>d()}),Ye=(I||[]).filter(De=>!P||De.name.toLowerCase().includes(P.toLowerCase()));return s.jsx("div",{style:Ei.overlay,onClick:l,children:s.jsxs("div",{style:{...Ei.modal,maxWidth:"550px"},onClick:De=>De.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:f==="select"?"Publish Dish to Menu":"Confirm Allergens & Publish"}),f==="select"&&s.jsxs(s.Fragment,{children:[!r&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ei.label,children:"Select Dish *"}),s.jsx("input",{type:"text",value:P,onChange:De=>L(De.target.value),style:Ei.input,placeholder:"Search dishes..."}),s.jsxs("div",{style:{maxHeight:"200px",overflow:"auto",border:"1px solid #eee",borderRadius:"4px",marginTop:"0.25rem"},children:[Ye.map(De=>s.jsx("div",{onClick:()=>m(De.id),style:{padding:"0.5rem",cursor:"pointer",background:g===De.id?"#eff6ff":"#fff",borderBottom:"1px solid #f3f4f6"},children:s.jsx("span",{style:{fontWeight:g===De.id?600:400},children:De.name})},De.id)),Ye.length===0&&s.jsx("p",{style:{padding:"0.5rem",color:"#999"},children:"No dishes found"})]})]}),!n&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ei.label,children:"Menu *"}),s.jsxs("select",{value:y||"",onChange:De=>{v(parseInt(De.target.value)),w(null)},style:Ei.input,children:[s.jsx("option",{value:"",children:"Select a menu..."}),me.map(De=>s.jsx("option",{value:De.id,children:De.name},De.id))]})]}),re.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ei.label,children:"Section *"}),s.jsxs("select",{value:x||"",onChange:De=>w(parseInt(De.target.value)),style:Ei.input,children:[s.jsx("option",{value:"",children:"Select section..."}),re.map(De=>s.jsx("option",{value:De.id,children:De.name},De.id))]})]}),s.jsxs("div",{style:Ei.modalActions,children:[s.jsx("button",{onClick:l,style:Ei.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>p("confirm"),style:Ei.btnPrimary,disabled:!g||!y||!x,children:"Next: Review Allergens"})]})]}),f==="confirm"&&s.jsxs(s.Fragment,{children:[te&&s.jsx("p",{children:"Loading allergen data..."}),!te&&ye&&s.jsxs("div",{style:{background:"#fee2e2",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem"},children:[s.jsx("strong",{style:{color:"#dc2626"},children:"Cannot publish: unassessed ingredients"}),s.jsx("ul",{style:{margin:"0.5rem 0 0",paddingLeft:"1.25rem"},children:J.map((De,qe)=>s.jsxs("li",{style:{fontSize:"0.875rem"},children:[De.name," — ",De.category]},qe))})]}),!te&&!ye&&s.jsxs(s.Fragment,{children:[ne.length>0&&s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("label",{style:Ei.label,children:"Confirmed Allergens"}),s.jsx("div",{style:{display:"flex",gap:"0.25rem",flexWrap:"wrap"},children:ne.map(De=>s.jsxs("span",{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"0.8rem",background:De.propagation_type==="contains"?"#fee2e2":"#dcfce7",color:De.propagation_type==="contains"?"#991b1b":"#166534"},children:[De.flag_code||De.flag_name,De.excludable_on_request&&" *"]},De.food_flag_id))})]}),s.jsx("label",{style:Ei.label,children:"Display Name *"}),s.jsx("input",{value:S,onChange:De=>_(De.target.value),style:Ei.input}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("label",{style:Ei.label,children:"Description"}),(U==null?void 0:U.llm_enabled)&&(U==null?void 0:U.anthropic_api_key_set)&&s.jsx("button",{onClick:M,disabled:W,style:{padding:"0.2rem 0.6rem",background:"#7952b3",color:"white",border:"none",borderRadius:"4px",cursor:W?"wait":"pointer",fontSize:"0.75rem",opacity:W?.7:1},children:W?"Generating...":"✨ Generate"})]}),s.jsx("textarea",{value:b,onChange:De=>C(De.target.value),style:{...Ei.input,minHeight:"60px",resize:"vertical"}}),s.jsx("label",{style:Ei.label,children:"Price"}),s.jsx("input",{type:"number",step:"0.01",value:T,onChange:De=>F(De.target.value),style:{...Ei.input,width:"120px"}}),s.jsx("label",{style:Ei.label,children:"Confirmed by *"}),s.jsx("input",{value:A,onChange:De=>D(De.target.value),style:Ei.input})]}),s.jsxs("div",{style:Ei.modalActions,children:[s.jsx("button",{onClick:()=>p("select"),style:Ei.btn,children:"Back"}),s.jsx("button",{onClick:l,style:Ei.btn,children:"Cancel"}),!ye&&s.jsx("button",{onClick:()=>ke.mutate(),style:Ei.btnPrimary,disabled:!S.trim()||!A.trim()||ke.isPending,children:ke.isPending?"Publishing...":"Publish to Menu"})]}),ke.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:ke.error.message})]})]})})}const Ei={overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"90%",maxHeight:"90vh",overflow:"auto"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.75rem"},input:{width:"100%",padding:"0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",boxSizing:"border-box"},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"}},Jfe={g:["g","kg"],kg:["g","kg"],ml:["ml","ltr"],ltr:["ml","ltr"],each:["each"],portion:["portion"]};function XN(n){return Jfe[n]||[n]}function epe(){var nt;const{id:n}=G_(),e=parseInt(n||"0"),{token:t,user:r}=gn(),i=go(),o=pi(),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState(""),[p,g]=k.useState(""),[m,y]=k.useState(""),[v,x]=k.useState(""),[w,S]=k.useState(""),[_,b]=k.useState(!1),[C,T]=k.useState(!1),[F,A]=k.useState(""),[D,P]=k.useState([]),[L,W]=k.useState(null),[O,U]=k.useState(""),[M,I]=k.useState([]),[H,z]=k.useState(""),[G,te]=k.useState(""),[re,me]=k.useState(!1),[J,ne]=k.useState(null),[ye,ke]=k.useState(null),[Ye,De]=k.useState(""),[qe,ue]=k.useState(""),[Ze,ee]=k.useState("100"),[Z,ge]=k.useState(""),[Te,Be]=k.useState(!1),[he,He]=k.useState(!1),[Ge,ae]=k.useState(null),[K,de]=k.useState(null),[Y,Q]=k.useState(null),[X,pe]=k.useState(!1),[we,Ne]=k.useState(null),[st,Ve]=k.useState(""),[Re,Le]=k.useState(""),[rt,$e]=k.useState(!1),[ce,Je]=k.useState(""),[jt,ct]=k.useState(""),[Se,ot]=k.useState(""),[ut,Ot]=k.useState(null),[An,on]=k.useState(""),[Ke,Rt]=k.useState(!1),[vt,Cr]=k.useState(""),[Qt,Ci]=k.useState(null),[Lr,Gs]=k.useState(""),[Ai,Ks]=k.useState(!1),[un,Fr]=k.useState(""),[zi,aa]=k.useState(!1),[Oi,Vd]=k.useState(!1),[Gn,Dr]=k.useState(null),[xr,Ss]=k.useState(null),[rs,Xs]=k.useState(null),[Jt,Ys]=k.useState(!1),{data:Ft}=Oe({queryKey:["recipe",e],queryFn:async()=>{const $=await fetch(`/api/recipes/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!$.ok)throw new Error("Not found");return $.json()},enabled:!!t&&!!e}),{data:Ea}=Oe({queryKey:["dish-courses"],queryFn:async()=>(await fetch("/api/recipes/menu-sections?section_type=dish",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:zn}=Oe({queryKey:["recipe-cost",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:gi}=Oe({queryKey:["recipe-cost-scaled",e,An],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing?scale_to=${An}`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&!!An&&parseInt(An)>0}),{data:je}=Oe({queryKey:["recipe-flags",e],queryFn:async()=>(await fetch(`/api/food-flags/recipes/${e}/flags`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:bt}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>(await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:yn}=Oe({queryKey:["recipe-changelog",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/change-log`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&Jt}),{data:tn}=Oe({queryKey:["recipe-cost-trend",e],queryFn:async()=>{const $=await fetch(`/api/recipes/${e}/cost-trend`,{headers:{Authorization:`Bearer ${t}`}});if(!$.ok)throw new Error("Failed to fetch cost trend");return $.json()},enabled:!!t&&!!e&&Oi}),{data:ci}=Oe({queryKey:["dish-menus",e],queryFn:async()=>{const $=await fetch(`/api/menus/dish/${e}/menus`,{headers:{Authorization:`Bearer ${t}`}});return $.ok?$.json():[]},enabled:!!t&&!!e}),{data:hn}=Oe({queryKey:["ingredient-edit",J],queryFn:async()=>{const $=await fetch(`/api/ingredients/${J}`,{headers:{Authorization:`Bearer ${t}`}});if(!$.ok)throw new Error("Not found");const ze=await $.json();return{id:ze.id,name:ze.name,category_id:ze.category_id,standard_unit:ze.standard_unit,yield_percent:Number(ze.yield_percent),manual_price:ze.manual_price!=null?Number(ze.manual_price):null,notes:ze.notes,is_prepackaged:ze.is_prepackaged||!1,is_free:ze.is_free||!1,product_ingredients:ze.product_ingredients,has_label_image:ze.has_label_image||!1}},enabled:!!t&&!!J}),{data:Ti}=Oe({queryKey:["recipes-list-for-sub"],queryFn:async()=>(await fetch("/api/recipes?recipe_type=component",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&X}),{data:js}=Oe({queryKey:["sambapos-menu-items-portions"],queryFn:async()=>{const $=await fetch("/api/sambapos/menu-items-with-portions",{headers:{Authorization:`Bearer ${t}`}});return $.ok?$.json():[]},enabled:!!t&&Ai});k.useEffect(()=>{var $,ze,Qe,pt;Ft&&(l(Ft.name),c(Ft.description||""),f((($=Ft.prep_time_minutes)==null?void 0:$.toString())||""),g(((ze=Ft.cook_time_minutes)==null?void 0:ze.toString())||""),y(Ft.notes||""),x(((Qe=Ft.menu_section_id)==null?void 0:Qe.toString())||""),S(Ft.kds_menu_item_name||""),Gs(((pt=Ft.gross_sell_price)==null?void 0:pt.toString())||""),b(!1))},[Ft]),k.useEffect(()=>{if(!F||F.length<2||!t)return;const $=setTimeout(async()=>{try{const ze=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(F)}`,{headers:{Authorization:`Bearer ${t}`}});if(ze.ok){const Qe=await ze.json();P(Array.isArray(Qe)?Qe:Qe.suggestions||[])}else console.warn("Ingredient suggest failed:",ze.status,await ze.text().catch(()=>""))}catch(ze){console.warn("Ingredient suggest error:",ze)}},300);return()=>clearTimeout($)},[F,t]);const Ar=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),b(!1)}}),fs=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/ingredients`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)})).ok)throw new Error("Failed to add")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]}),T(!1),A(""),W(null),U(""),I([]),z(""),te("")}}),Qs=Ue({mutationFn:async({riId:$,quantity:ze,unit:Qe,yield_percent:pt,notes:kt})=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${$}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({quantity:ze,unit:Qe,yield_percent:pt,notes:kt})})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),ke(null)}}),Lo=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to remove")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})}}),xn=Ue({mutationFn:async $=>{const ze=await fetch(`/api/recipes/${e}/sub-recipes`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)});if(!ze.ok){const Qe=await ze.json().catch(()=>({}));throw new Error(Qe.detail||"Failed to add sub-recipe")}},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),pe(!1)}}),Pa=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/recipe-sub-recipes/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]})}}),nn=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/steps`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),$e(!1),Je(""),ct(""),ot("")}}),Zl=Ue({mutationFn:async({stepId:$,data:ze})=>{if(!(await fetch(`/api/recipes/recipe-steps/${$}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ze)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Ot(null),$e(!1),Je(""),ct(""),ot("")}}),qu=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/recipe-steps/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>o.invalidateQueries({queryKey:["recipe",e]})}),$s=Ue({mutationFn:async({file:$,caption:ze,image_type:Qe})=>{const pt=new FormData;if(pt.append("file",$),pt.append("caption",ze),pt.append("image_type",Qe),!(await fetch(`/api/recipes/${e}/images`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:pt})).ok)throw new Error("Failed to upload image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Rt(!1),Cr(""),Ci(null)}}),Gd=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/images/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),mo=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/ingredients/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_ids:$})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Bc=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/sub-recipes/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sub_recipe_ids:$})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Kd=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/steps/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({step_ids:$})})).ok)throw new Error("Failed to reorder steps")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Zs=($,ze)=>{ae($),Q(ze)},Ra=($,ze)=>{$.preventDefault(),de(ze)},Xd=()=>{if(Ge===null||K===null||!Ft||Y!=="ing"){ae(null),de(null),Q(null);return}const ze=[...[...Ft.ingredients].sort((pt,kt)=>pt.sort_order-kt.sort_order)],[Qe]=ze.splice(Ge,1);ze.splice(K,0,Qe),mo.mutate(ze.map(pt=>pt.id)),ae(null),de(null),Q(null)},No=()=>{if(Ge===null||K===null||!Ft||Y!=="sub"){ae(null),de(null),Q(null);return}const $=[...Ft.sub_recipes],[ze]=$.splice(Ge,1);$.splice(K,0,ze),Bc.mutate($.map(Qe=>Qe.id)),ae(null),de(null),Q(null)},Js=($,ze)=>{if(!Ft)return;const Qe=[...Ft.steps],pt=ze==="up"?$-1:$+1;if(pt<0||pt>=Qe.length)return;const kt=[...Qe],Ht=kt[$];kt[$]=kt[pt],kt[pt]=Ht,Kd.mutate(kt.map(Gt=>Gt.id))},Ba=()=>{Ar.mutate({name:a,description:d||null,batch_portions:1,prep_time_minutes:u?parseInt(u):null,cook_time_minutes:p?parseInt(p):null,notes:m||null,menu_section_id:v?parseInt(v):null,kds_menu_item_name:w||null,sambapos_portion_name:(Ft==null?void 0:Ft.sambapos_portion_name)||null,gross_sell_price:Lr&&parseFloat(Lr)>0?parseFloat(Lr):null})},Ic=$=>{window.open(`/api/recipes/${e}/print?format=${$}&token=${t}`,"_blank")};if(!Ft)return s.jsx("div",{style:Ce.loading,children:"Loading dish..."});const al=zn==null?void 0:zn.total_cost_recent,ie=zn==null?void 0:zn.cost_per_portion;return s.jsxs("div",{style:Ce.page,children:[s.jsxs("div",{style:Ce.topBar,children:[s.jsx("button",{onClick:()=>i("/dishes"),style:Ce.backBtn,children:"← Back"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>aa(!0),style:{...Ce.secondaryBtn,background:"#eff6ff",color:"#2563eb"},children:"Publish to Menu"}),s.jsx("button",{onClick:()=>Ic("kitchen"),style:Ce.secondaryBtn,children:"Print Kitchen Card"}),s.jsx("button",{onClick:()=>Ic("full"),style:Ce.secondaryBtn,children:"Print Full"}),_&&s.jsx("button",{onClick:Ba,disabled:Ar.isPending,style:Ce.primaryBtn,children:Ar.isPending?"Saving...":"Save Changes"})]})]}),s.jsxs("div",{style:Ce.metaSection,children:[s.jsxs("div",{style:Ce.metaRow,children:[s.jsx("input",{value:a,onChange:$=>{l($.target.value),b(!0)},style:{...Ce.nameInput,flex:1}}),s.jsx("span",{style:{background:"#3b82f6",color:"white",padding:"4px 12px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},children:"DISH"})]}),ci&&ci.length>0&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666",marginTop:"0.25rem"},children:["Published on: ",ci.map(($,ze)=>s.jsxs("span",{children:[ze>0&&", ",s.jsx("span",{style:{color:$.is_active?"#2563eb":"#999"},children:$.menu_name})]},$.menu_id))]}),s.jsxs("div",{style:Ce.metaGrid,children:[s.jsxs("div",{children:[s.jsx("label",{style:Ce.label,children:"Course"}),s.jsxs("select",{value:v,onChange:$=>{x($.target.value),b(!0)},style:Ce.input,children:[s.jsx("option",{value:"",children:"None"}),Ea==null?void 0:Ea.map($=>s.jsx("option",{value:$.id,children:$.name},$.id))]})]}),s.jsxs("div",{children:[s.jsx("label",{style:Ce.label,children:"Prep (min)"}),s.jsx("input",{type:"number",value:u,onChange:$=>{f($.target.value),b(!0)},style:Ce.input})]}),s.jsxs("div",{children:[s.jsx("label",{style:Ce.label,children:"Cook (min)"}),s.jsx("input",{type:"number",value:p,onChange:$=>{g($.target.value),b(!0)},style:Ce.input})]})]}),s.jsx("label",{style:Ce.label,children:"Description"}),s.jsx("textarea",{value:d,onChange:$=>{c($.target.value),b(!0)},style:{...Ce.input,minHeight:"50px"}}),s.jsx("label",{style:Ce.label,children:"SambaPOS Menu Item"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsxs("div",{onClick:()=>Ks(!0),style:{...Ce.input,cursor:"pointer",flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",minHeight:"36px",background:"#fafafa"},children:[w?s.jsxs("span",{children:[s.jsx("strong",{children:w}),(Ft==null?void 0:Ft.sambapos_portion_name)&&Ft.sambapos_portion_name!=="Normal"&&s.jsxs("span",{style:{color:"#666",marginLeft:"0.5rem"},children:["(",Ft.sambapos_portion_name,")"]})]}):s.jsx("span",{style:{color:"#999"},children:"Click to select SambaPOS item..."}),s.jsx("span",{style:{color:"#999",fontSize:"0.8rem"},children:"▼"})]}),w&&s.jsx("button",{onClick:()=>{S(""),Ar.mutate({kds_menu_item_name:"",sambapos_portion_name:""})},style:{background:"none",border:"1px solid #ddd",borderRadius:"4px",padding:"6px 10px",cursor:"pointer",color:"#999",fontSize:"0.85rem"},title:"Clear SambaPOS link",children:"✕"})]})]}),je&&je.unassessed_ingredients.length>0&&s.jsxs("div",{style:Ce.flagWarning,children:[s.jsxs("strong",{children:[je.unassessed_ingredients.length," ingredient",je.unassessed_ingredients.length>1?"s are":" is"," missing allergen details"]})," — ",je.unassessed_ingredients.map($=>$.name).join(", ")]}),je&&je.open_suggestion_ingredients&&je.open_suggestion_ingredients.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsxs("strong",{children:[je.open_suggestion_ingredients.length," ingredient",je.open_suggestion_ingredients.length>1?"s have":" has"," unreviewed allergen suggestions"]})," — ",je.open_suggestion_ingredients.map(($,ze)=>s.jsxs("span",{children:[ze>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline",fontWeight:600},onClick:()=>ne($.ingredient_id),children:$.ingredient_name})," ","(",$.suggestion_count,")"]},$.ingredient_id))]}),je&&je.recipe_text_suggestions&&je.recipe_text_suggestions.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsx("strong",{children:"Recipe text keyword matches"}),s.jsx("div",{style:{marginTop:"0.4rem"},children:je.recipe_text_suggestions.map($=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.3rem"},children:[s.jsxs("span",{children:[s.jsx("strong",{children:$.flag_name})," — ",$.matched_keywords.join(", ")]}),s.jsx("button",{style:{marginLeft:"auto",background:"none",border:"1px solid #b4530955",borderRadius:"4px",color:"#b45309",cursor:"pointer",padding:"0.15rem 0.5rem",fontSize:"0.8rem",whiteSpace:"nowrap"},onClick:async()=>{try{(await fetch(`/api/food-flags/recipes/${e}/text-dismissals`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_id:$.flag_id,dismissed_by_name:(r==null?void 0:r.name)||(r==null?void 0:r.email)||"Unknown",matched_keyword:$.matched_keywords.join(", ")})})).ok&&o.invalidateQueries({queryKey:["recipe-flags",e]})}catch{}},children:"Dismiss"})]},$.flag_id))})]}),Ft&&(()=>{const $=Ft.ingredients.filter(kt=>kt.is_manual_price),ze=Ft.ingredients.filter(kt=>kt.has_no_price),Qe=Ft.sub_recipes.filter(kt=>kt.has_manual_price_ingredients),pt=Ft.sub_recipes.filter(kt=>kt.has_no_price_ingredients);return $.length===0&&ze.length===0&&Qe.length===0&&pt.length===0?null:s.jsxs("div",{style:{background:"#fef3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #ffc10755"},children:[ze.length>0&&s.jsxs("div",{children:[s.jsxs("strong",{children:[ze.length," ingredient",ze.length>1?"s have":" has"," no price"]})," — ",ze.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ne(kt.ingredient_id),children:kt.ingredient_name})]},kt.ingredient_id))]}),$.length>0&&s.jsxs("div",{style:{marginTop:ze.length>0?"0.3rem":0},children:[s.jsxs("strong",{children:[$.length," ingredient",$.length>1?"s use":" uses"," manual price"]})," — ",$.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ne(kt.ingredient_id),children:kt.ingredient_name})]},kt.ingredient_id))]}),pt.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[pt.length," sub-recipe",pt.length>1?"s contain":" contains"," unpriced ingredients"]})," — ",pt.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${kt.child_recipe_id}`),children:kt.child_recipe_name})]},kt.child_recipe_id))]}),Qe.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[Qe.length," sub-recipe",Qe.length>1?"s contain":" contains"," manual-priced ingredients"]})," — ",Qe.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${kt.child_recipe_id}`),children:kt.child_recipe_name})]},kt.child_recipe_id))]})]})})(),je&&s.jsxs("div",{style:{margin:"0.75rem 0"},children:[je.flags.length>0&&s.jsx(T0,{flags:je.flags,size:"medium"}),bt&&bt.length>0&&s.jsx("div",{style:{display:"flex",gap:"0.35rem",marginTop:"0.5rem",flexWrap:"wrap"},children:bt.map($=>s.jsx("button",{onClick:()=>Xs(rs===$.id?null:$.id),style:{padding:"3px 10px",fontSize:"0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:rs===$.id?"#e94560":"#f5f5f5",color:rs===$.id?"white":"#555",cursor:"pointer"},children:$.name},$.id))})]}),rs!=null&&s.jsx(WK,{recipeId:e,categoryId:rs||void 0}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Ingredients"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Ft.ingredients.length>1&&s.jsx("button",{onClick:()=>Be(!Te),style:{...Ce.addBtn,background:Te?"#3b82f6":void 0,color:Te?"#fff":void 0},children:Te?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>T(!0),style:Ce.addBtn,children:"+ Add"})]})]}),s.jsxs("table",{style:Ce.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[Te&&s.jsx("th",{style:{...Ce.th,width:"30px"}}),s.jsx("th",{style:Ce.th,children:"Ingredient"}),s.jsx("th",{style:Ce.th,children:"Quantity"}),s.jsx("th",{style:Ce.th,children:"Yield %"}),s.jsx("th",{style:Ce.th,children:"Cost"}),s.jsx("th",{style:Ce.th,children:"Notes"}),s.jsx("th",{style:Ce.th})]})}),s.jsx("tbody",{children:[...Ft.ingredients].sort(($,ze)=>$.sort_order-ze.sort_order).map(($,ze)=>s.jsxs("tr",{style:{...Ce.tr,opacity:Y==="ing"&&Ge===ze?.4:1,background:Y==="ing"&&K===ze?"#e0f2fe":void 0},draggable:Te,onDragStart:()=>Zs(ze,"ing"),onDragOver:Qe=>Ra(Qe,ze),onDrop:Xd,onDragEnd:()=>{ae(null),de(null),Q(null)},children:[Te&&s.jsx("td",{style:{...Ce.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6",textDecoration:"none"},onClick:()=>ne($.ingredient_id),title:"Edit ingredient",children:$.ingredient_name})}),ye===$.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:Ce.td,children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"2px"},children:[s.jsx("input",{type:"number",value:Ye,onChange:Qe=>De(Qe.target.value),style:{...Ce.input,width:"80px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.1",autoFocus:!0}),$.compatible_units&&$.compatible_units.length>1?s.jsx("select",{value:qe,onChange:Qe=>ue(Qe.target.value),style:{...Ce.input,width:"55px",padding:"0.25rem 0.2rem",fontSize:"0.75rem"},children:$.compatible_units.map(Qe=>s.jsx("option",{value:Qe,children:Qe},Qe))}):s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:$.unit})]})}),s.jsx("td",{style:Ce.td,children:s.jsx("input",{type:"number",value:Ze,onChange:Qe=>ee(Qe.target.value),style:{...Ce.input,width:"60px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.5",min:"1",max:"100"})}),s.jsx("td",{style:Ce.td,children:$.cost!=null?`£${$.cost.toFixed(2)}`:"-"}),s.jsx("td",{style:Ce.td,children:s.jsx("input",{value:Z,onChange:Qe=>ge(Qe.target.value),style:{...Ce.input,width:"120px",padding:"0.25rem 0.4rem",fontSize:"0.8rem"},placeholder:"notes..."})}),s.jsx("td",{style:Ce.td,children:s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[s.jsx("button",{onClick:()=>Qs.mutate({riId:$.id,quantity:parseFloat(Ye),unit:qe,yield_percent:parseFloat(Ze),notes:Z||void 0}),disabled:!Ye||Qs.isPending,style:{...Ce.addBtn,fontSize:"0.7rem",padding:"2px 6px",color:"#16a34a"},children:"Save"}),s.jsx("button",{onClick:()=>ke(null),style:{...Ce.removeBtn,color:"#888"},children:"Cancel"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("td",{style:{...Ce.td,cursor:"pointer"},onClick:()=>{ke($.id),De($.quantity.toString()),ue($.unit),ee($.yield_percent.toString()),ge($.notes||"")},children:[$.quantity,$.unit]}),s.jsx("td",{style:{...Ce.td,cursor:"pointer"},onClick:()=>{ke($.id),De($.quantity.toString()),ue($.unit),ee($.yield_percent.toString()),ge($.notes||"")},children:$.yield_percent<100?s.jsxs("span",{style:{color:"#e94560"},children:[$.yield_percent,"%"]}):"100%"}),s.jsx("td",{style:Ce.td,children:$.cost!=null?s.jsxs("span",{style:$.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:$.is_manual_price?"Manual price":void 0,children:["£",$.cost.toFixed(2)]}):"-"}),s.jsx("td",{style:{...Ce.td,cursor:"pointer"},onClick:()=>{ke($.id),De($.quantity.toString()),ue($.unit),ee($.yield_percent.toString()),ge($.notes||"")},children:s.jsx("span",{style:{color:"#888",fontSize:"0.8rem"},children:$.notes||"-"})}),s.jsx("td",{style:Ce.td,children:s.jsx("button",{onClick:()=>Lo.mutate($.id),style:Ce.removeBtn,children:"✕"})})]})]},$.id))})]})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Sub-Recipes"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Ft.sub_recipes.length>1&&s.jsx("button",{onClick:()=>He(!he),style:{...Ce.addBtn,background:he?"#3b82f6":void 0,color:he?"#fff":void 0},children:he?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>pe(!0),style:Ce.addBtn,children:"+ Add"})]})]}),Ft.sub_recipes.length>0?s.jsxs("table",{style:Ce.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[he&&s.jsx("th",{style:{...Ce.th,width:"30px"}}),s.jsx("th",{style:Ce.th,children:"Recipe"}),s.jsx("th",{style:Ce.th,children:"Batch Output"}),s.jsx("th",{style:Ce.th,children:"Amount Used"}),s.jsx("th",{style:Ce.th,children:"Cost"}),s.jsx("th",{style:Ce.th})]})}),s.jsx("tbody",{children:Ft.sub_recipes.map(($,ze)=>s.jsxs("tr",{style:{...Ce.tr,opacity:Y==="sub"&&Ge===ze?.4:1,background:Y==="sub"&&K===ze?"#e0f2fe":void 0},draggable:he,onDragStart:()=>Zs(ze,"sub"),onDragOver:Qe=>Ra(Qe,ze),onDrop:No,onDragEnd:()=>{ae(null),de(null),Q(null)},children:[he&&s.jsx("td",{style:{...Ce.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${$.child_recipe_id}`),children:$.child_recipe_name})}),s.jsx("td",{style:Ce.td,children:$.batch_output_type==="bulk"?`${$.output_qty}${$.output_unit}`:`${$.batch_portions} portions`}),s.jsxs("td",{style:Ce.td,children:[$.portions_needed,$.batch_output_type==="bulk"?$.portions_needed_unit:" portions",$.batch_output_type==="bulk"&&$.portions_needed_unit!==$.output_unit&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#888",marginLeft:"4px"},children:["(",$.output_unit,")"]})]}),s.jsx("td",{style:Ce.td,children:$.cost_contribution!=null?s.jsxs("span",{style:$.has_manual_price_ingredients||$.has_no_price_ingredients?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:$.has_manual_price_ingredients?"Includes manual-priced ingredients":$.has_no_price_ingredients?"Includes unpriced ingredients":void 0,children:["£",$.cost_contribution.toFixed(2)]}):"-"}),s.jsx("td",{style:Ce.td,children:s.jsx("button",{onClick:()=>Pa.mutate($.id),style:Ce.removeBtn,children:"✕"})})]},$.id))})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No sub-recipes added"})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Method"}),s.jsx("button",{onClick:()=>{Ot(null),Je(""),ct(""),ot(""),$e(!0)},style:Ce.addBtn,children:"+ Add Step"})]}),Ft.steps.length>0?s.jsx("div",{style:{margin:0},children:Ft.steps.map(($,ze)=>s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px",padding:"8px 0",borderBottom:"1px solid #f0f0f0"},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",flexShrink:0,marginTop:"2px"},children:[s.jsx("button",{onClick:()=>Js(ze,"up"),disabled:ze===0||Kd.isPending,style:{...Ce.reorderBtn,opacity:ze===0?.3:1},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>Js(ze,"down"),disabled:ze===Ft.steps.length-1||Kd.isPending,style:{...Ce.reorderBtn,opacity:ze===Ft.steps.length-1?.3:1},title:"Move down",children:"▼"})]}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem",color:"#e94560",minWidth:"24px",marginTop:"1px"},children:ze+1}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:"6px"},children:[$.title&&s.jsx("span",{style:{fontWeight:600,fontSize:"0.95rem"},children:$.title}),$.duration_minutes&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#888"},children:["(",$.duration_minutes," min)"]})]}),s.jsx("div",{style:{fontSize:"0.85rem",color:"#555",marginTop:$.title?"2px":0,whiteSpace:"pre-wrap"},children:$.instruction})]}),s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{onClick:()=>{Ot($.id),Je($.title||""),ct($.instruction),ot($.duration_minutes?String($.duration_minutes):""),$e(!0)},style:{...Ce.reorderBtn,fontSize:"0.75rem"},title:"Edit step",children:"✎"}),s.jsx("button",{onClick:()=>qu.mutate($.id),style:{...Ce.removeBtn,flexShrink:0},children:"✕"})]})]},$.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No steps added yet"})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Images"}),s.jsx("button",{onClick:()=>Rt(!Ke),style:Ce.addBtn,children:Ke?"Cancel":"+ Upload"})]}),Ke&&s.jsxs("div",{style:{marginBottom:"1rem",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsx("label",{style:Ce.label,children:"Image File"}),s.jsx("input",{type:"file",accept:"image/*",onChange:$=>{var ze;return Ci(((ze=$.target.files)==null?void 0:ze[0])||null)},style:{...Ce.input,padding:"0.35rem"}}),s.jsx("label",{style:Ce.label,children:"Caption (optional)"}),s.jsx("input",{value:vt,onChange:$=>Cr($.target.value),style:Ce.input,placeholder:"Describe this image..."}),s.jsx("div",{style:{marginTop:"0.75rem",display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{onClick:()=>{Qt&&$s.mutate({file:Qt,caption:vt,image_type:"general"})},disabled:!Qt||$s.isPending,style:Ce.primaryBtn,children:$s.isPending?"Uploading...":"Upload Image"})}),$s.error&&s.jsx("div",{style:Ce.errorMsg,children:$s.error.message})]}),Ft.images.length>0?s.jsx("div",{style:Ce.imageGrid,children:Ft.images.map($=>s.jsxs("div",{style:Ce.imageCard,children:[s.jsx("img",{src:`/api/recipes/${e}/images/${$.id}?token=${t}`,alt:$.caption||"Dish image",style:{...Ce.imageThumb,cursor:"pointer"},onClick:()=>Ss(`/api/recipes/${e}/images/${$.id}?token=${t}`)}),s.jsxs("div",{style:{padding:"0.4rem"},children:[$.caption&&s.jsx("div",{style:{fontSize:"0.8rem",color:"#333",marginTop:"2px"},children:$.caption}),s.jsx("button",{onClick:()=>{confirm("Delete this image?")&&Gd.mutate($.id)},style:{...Ce.removeBtn,marginTop:"4px",fontSize:"0.7rem"},children:"Delete"})]})]},$.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No images uploaded"})]}),s.jsxs("div",{style:Ce.costPanel,children:[s.jsx("div",{style:Ce.costHeader,children:s.jsx("h3",{style:{margin:0},children:"Cost Summary"})}),s.jsxs("div",{style:Ce.costGrid,children:[s.jsxs("div",{style:Ce.costBox,children:[s.jsx("div",{style:Ce.costLabel,children:"Dish Total"}),s.jsx("div",{style:Ce.costValue,children:al!=null?`£${al.toFixed(2)}`:"-"})]}),s.jsxs("div",{style:Ce.costBox,children:[s.jsx("div",{style:Ce.costLabel,children:"Portion Cost"}),s.jsx("div",{style:Ce.costValue,children:ie!=null?`£${ie.toFixed(2)}`:"-"})]}),(zn==null?void 0:zn.total_cost_min)!=null&&s.jsxs("div",{style:Ce.costBox,children:[s.jsx("div",{style:Ce.costLabel,children:"Min / Max"}),s.jsxs("div",{style:{fontSize:"0.85rem"},children:["£",zn.total_cost_min.toFixed(2)," – £",(nt=zn.total_cost_max)==null?void 0:nt.toFixed(2)]})]})]}),(zn==null?void 0:zn.gp_comparison)&&s.jsxs("div",{style:{marginTop:"0.75rem"},children:[s.jsx("strong",{style:{fontSize:"0.85rem"},children:"Suggested Sell Price (incl. VAT):"}),s.jsx("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.35rem",flexWrap:"wrap"},children:zn.gp_comparison.map($=>s.jsxs("div",{style:Ce.gpBadge,children:[$.gp_target,"% GP → ",s.jsxs("strong",{children:["£",$.suggested_price.toFixed(2)]})]},$.gp_target))})]}),ie!=null&&s.jsxs("div",{style:{marginTop:"0.75rem",display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"2px"},children:"Gross Sell Price"}),s.jsx("input",{type:"number",value:Lr,onChange:$=>{Gs($.target.value),b(!0)},style:{...Ce.input,width:"100px"},step:"0.5",min:"0",placeholder:"£"})]}),Lr&&parseFloat(Lr)>0&&(()=>{const ze=parseFloat(Lr)/1.2,Qe=(ze-ie)/ze*100,pt=Qe>=70?"#16a34a":Qe>=60?"#ca8a04":"#dc2626";return s.jsxs("div",{style:{...Ce.gpBadge,borderColor:pt,background:`${pt}10`},children:[s.jsxs("span",{style:{color:pt,fontWeight:700,fontSize:"1rem"},children:[Qe.toFixed(1),"% GP"]}),s.jsxs("span",{style:{color:"#888",fontSize:"0.75rem",marginLeft:"0.5rem"},children:["(net £",ze.toFixed(2),")"]})]})})()]}),s.jsx("div",{style:{marginTop:"0.5rem"},children:s.jsxs("button",{onClick:()=>Vd(!Oi),style:Ce.linkBtn,children:[Oi?"Hide":"Show"," cost trend"]})}),Oi&&(tn==null?void 0:tn.snapshots)&&tn.snapshots.length>1&&(()=>{const $=tn.snapshots,ze=$.map(Dt=>Dt.cost_per_portion),Qe=Math.min(...ze),pt=Math.max(...ze),kt=pt-Qe||1,Ht=500,Gt=120,Er=40,ar=20,Kn=Ht-Er*2,is=Gt-ar*2,On=$.map((Dt,Ln)=>{const Fi=Er+Ln/($.length-1)*Kn,Zr=ar+is-(Dt.cost_per_portion-Qe)/kt*is;return{x:Fi,y:Zr,...Dt}}),sn=On.map(Dt=>`${Dt.x},${Dt.y}`).join(" "),ps=[Qe,Qe+kt/2,pt],It=[0,Math.floor($.length/2),$.length-1],Tn=$.filter((Dt,Ln)=>Ln>0&&Dt.cost_per_portion!==$[Ln-1].cost_per_portion);return s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"1rem",alignItems:"flex-start"},children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("svg",{width:Ht,height:Gt,style:{background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[ps.map((Dt,Ln)=>{const Fi=ar+is-(Dt-Qe)/kt*is;return s.jsxs("g",{children:[s.jsx("line",{x1:Er,y1:Fi,x2:Ht-Er,y2:Fi,stroke:"#f0f0f0",strokeWidth:"1"}),s.jsxs("text",{x:Er-4,y:Fi+3,textAnchor:"end",fontSize:"9",fill:"#888",children:["£",Dt.toFixed(2)]})]},Ln)}),It.filter((Dt,Ln,Fi)=>Fi.indexOf(Dt)===Ln).map(Dt=>{const Ln=On[Dt],Fi=new Date(Ln.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"});return s.jsx("text",{x:Ln.x,y:Gt-2,textAnchor:"middle",fontSize:"9",fill:"#888",children:Fi},Dt)}),s.jsx("polyline",{points:sn,fill:"none",stroke:"#e94560",strokeWidth:"2"}),On.map((Dt,Ln)=>s.jsx("circle",{cx:Dt.x,cy:Dt.y,r:4,fill:"#e94560",stroke:"white",strokeWidth:"2",style:{cursor:"pointer"},onMouseEnter:Fi=>{var ll;const Zr=(ll=Fi.target.closest("svg"))==null?void 0:ll.getBoundingClientRect();Dr({x:Zr?Dt.x+Zr.left-((Zr==null?void 0:Zr.left)||0):Dt.x,y:Dt.y-10,date:new Date(Dt.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),cost:`£${Dt.cost_per_portion.toFixed(2)}`,trigger:Dt.trigger})},onMouseLeave:()=>Dr(null)},Ln))]}),Gn&&s.jsxs("div",{style:{position:"absolute",left:Gn.x,top:Gn.y-50,transform:"translateX(-50%)",background:"#333",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"0.75rem",whiteSpace:"nowrap",pointerEvents:"none",zIndex:20},children:[s.jsx("div",{children:Gn.date}),s.jsx("div",{children:Gn.cost}),s.jsx("div",{style:{color:"#ccc",fontSize:"0.7rem"},children:Gn.trigger})]})]}),Tn.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"220px",maxHeight:"300px",overflow:"auto",fontSize:"0.75rem",background:"#fafafa",borderRadius:"6px",padding:"6px 8px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{fontWeight:600,fontSize:"0.7rem",color:"#888",marginBottom:"4px"},children:["Change Log (",Tn.length," snapshots)"]}),Tn.slice().reverse().map((Dt,Ln)=>{const Fi=$[$.indexOf(Dt)-1],Zr=Dt.cost_per_portion-Fi.cost_per_portion,ll=Zr>0?"#dc2626":"#16a34a";return s.jsxs("div",{style:{padding:"3px 0",borderBottom:"1px solid #eee"},children:[s.jsxs("div",{style:{color:"#888"},children:[new Date(Dt.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),s.jsxs("span",{style:{color:ll,fontWeight:600,marginLeft:"4px"},children:[Zr>0?"+":"","£",Zr.toFixed(4)]})]}),Dt.changes.length>0&&s.jsx("div",{style:{color:"#666",marginTop:"1px"},children:Dt.changes.map((Wo,Mc)=>s.jsx("div",{style:{fontSize:"0.7rem",lineHeight:1.3},children:Wo},Mc))})]},Ln)})]})]})})(),Oi&&(tn==null?void 0:tn.snapshots)&&tn.snapshots.length<=1&&s.jsx("div",{style:{marginTop:"0.5rem",color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"Not enough data points to display a trend chart"})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Scale Dish"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("input",{type:"number",value:An,onChange:$=>on($.target.value),style:{...Ce.input,width:"80px"},placeholder:Ft.batch_portions.toString(),min:"1"}),s.jsx("span",{style:{fontSize:"0.8rem",color:"#888"},children:"portions"})]})]}),(()=>{var kt;const $=gi||zn;if(!($!=null&&$.ingredients))return null;const ze=$.ingredients.reduce((Ht,Gt)=>Ht+(Gt.cost_recent??0),0)+(((kt=$.sub_recipes)==null?void 0:kt.reduce((Ht,Gt)=>Ht+(Gt.cost_contribution??0),0))??0),Qe=$.ingredients.reduce((Ht,Gt)=>Ht+(Gt.cost_min??0),0),pt=$.ingredients.reduce((Ht,Gt)=>Ht+(Gt.cost_max??0),0);return s.jsxs("table",{style:Ce.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ce.th,children:"Ingredient"}),s.jsx("th",{style:Ce.th,children:"Qty"}),s.jsx("th",{style:Ce.th,children:"Recent"}),s.jsx("th",{style:Ce.th,children:"Min"}),s.jsx("th",{style:Ce.th,children:"Max"})]})}),s.jsxs("tbody",{children:[$.ingredients.map(Ht=>{const Gt=Ht.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;return s.jsxs("tr",{children:[s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ne(Ht.ingredient_id),title:"Edit ingredient",children:Ht.ingredient_name})}),s.jsxs("td",{style:Ce.td,children:[Ht.quantity,Ht.unit]}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:Gt,title:Ht.is_manual_price?"Manual price":void 0,children:Ht.cost_recent!=null?`£${Ht.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:Gt,title:Ht.is_manual_price?"Manual price":void 0,children:Ht.cost_min!=null?`£${Ht.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:Gt,title:Ht.is_manual_price?"Manual price":void 0,children:Ht.cost_max!=null?`£${Ht.cost_max.toFixed(2)}`:"-"})})]},Ht.ingredient_id)}),(()=>{const Ht=(Gt,Er)=>{var Kn,is;const ar=[];for(const On of Gt){const sn=Er*1.5,ps=On.child_ingredients&&On.child_ingredients.length>0||On.child_sub_recipes&&On.child_sub_recipes.length>0,It=((Kn=On.child_ingredients)==null?void 0:Kn.some(Dt=>Dt.is_manual_price))||!1,Tn=It?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;if(ar.push(s.jsx("tr",{children:s.jsxs("td",{colSpan:5,style:{...Ce.td,background:Er===0?"#f0f0f0":"#f5f5f5",fontWeight:600,fontSize:"0.8rem",color:"#555",paddingLeft:`${.5+sn}rem`},children:[Er>0&&"→ ",s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${On.child_recipe_id}`),children:On.child_recipe_name})," (",On.portions_needed,On.output_unit==="portion"?" portions":On.output_unit,") — ",s.jsxs("span",{style:Tn,title:It?"Includes manual-priced ingredients":void 0,children:["£",((is=On.cost_contribution)==null?void 0:is.toFixed(2))??"-"]})]})},`sub-header-${Er}-${On.child_recipe_id}`)),ps){for(const Dt of On.child_ingredients||[]){const Ln=Dt.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;ar.push(s.jsxs("tr",{style:{background:"#fafafa"},children:[s.jsx("td",{style:{...Ce.td,paddingLeft:`${1.5+sn}rem`,color:"#666"},children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ne(Dt.ingredient_id),title:"Edit ingredient",children:Dt.ingredient_name})}),s.jsxs("td",{style:{...Ce.td,color:"#666"},children:[Dt.quantity,Dt.unit]}),s.jsx("td",{style:{...Ce.td,color:"#666"},children:s.jsx("span",{style:Ln,title:Dt.is_manual_price?"Manual price":void 0,children:Dt.cost_recent!=null?`£${Dt.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Ce.td,color:"#666"},children:s.jsx("span",{style:Ln,title:Dt.is_manual_price?"Manual price":void 0,children:Dt.cost_min!=null?`£${Dt.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Ce.td,color:"#666"},children:s.jsx("span",{style:Ln,title:Dt.is_manual_price?"Manual price":void 0,children:Dt.cost_max!=null?`£${Dt.cost_max.toFixed(2)}`:"-"})})]},`sub-${Er}-${On.child_recipe_id}-ing-${Dt.ingredient_id}`))}On.child_sub_recipes&&On.child_sub_recipes.length>0&&ar.push(...Ht(On.child_sub_recipes,Er+1))}}return ar};return Ht($.sub_recipes||[],0)})(),s.jsxs("tr",{style:{borderTop:"2px solid #333"},children:[s.jsx("td",{style:{...Ce.td,fontWeight:700},children:"Total"}),s.jsx("td",{style:Ce.td}),s.jsx("td",{style:{...Ce.td,fontWeight:700},children:ze>0?`£${ze.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Ce.td,fontWeight:700},children:Qe>0?`£${Qe.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Ce.td,fontWeight:700},children:pt>0?`£${pt.toFixed(2)}`:"-"})]})]})]})})()]}),s.jsxs("div",{style:Ce.section,children:[s.jsx("label",{style:Ce.label,children:"Notes"}),s.jsx("textarea",{value:m,onChange:$=>{y($.target.value),b(!0)},style:{...Ce.input,minHeight:"60px"}})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("button",{onClick:()=>Ys(!Jt),style:Ce.linkBtn,children:[Jt?"Hide":"Show"," change history"]}),Jt&&yn&&s.jsx("div",{style:{marginTop:"0.5rem"},children:yn.map($=>s.jsxs("div",{style:Ce.logEntry,children:[s.jsx("span",{style:{color:"#888",fontSize:"0.75rem"},children:$.created_at}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#555"},children:$.username}),s.jsx("span",{style:{fontSize:"0.85rem"},children:$.change_summary})]},$.id))})]}),C&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:Ce.modal,children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Ingredient"}),s.jsx("button",{onClick:()=>T(!1),style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("label",{style:Ce.label,children:"Search Ingredient"}),s.jsx("input",{value:F,onChange:$=>{A($.target.value),W(null)},style:Ce.input,placeholder:"Type to search..."}),F.length>=2&&!L&&s.jsxs("div",{style:Ce.suggestions,children:[D.map($=>s.jsxs("div",{style:Ce.suggestionItem,onClick:()=>{const ze=XN($.standard_unit);W($.id),U($.standard_unit),I(ze),A($.name)},children:[$.name," ",s.jsxs("span",{style:{color:"#888",fontSize:"0.75rem"},children:["(",Math.round($.similarity*100),"%)"]})]},$.id)),s.jsxs("div",{style:{...Ce.suggestionItem,color:"#16a34a",fontWeight:600,borderBottom:"none"},onClick:()=>me(!0),children:['+ Create "',F,'"']})]}),L&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ce.label,children:"Quantity"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:H,onChange:$=>z($.target.value),style:{...Ce.input,flex:1},step:"0.1"}),M.length>1?s.jsx("select",{value:O,onChange:$=>U($.target.value),style:{...Ce.input,width:"70px"},children:M.map($=>s.jsx("option",{value:$,children:$},$))}):s.jsx("span",{style:{alignSelf:"center",fontSize:"0.85rem",color:"#666",minWidth:"30px"},children:O})]}),s.jsx("label",{style:Ce.label,children:"Notes (optional)"}),s.jsx("input",{value:G,onChange:$=>te($.target.value),style:Ce.input,placeholder:"e.g. finely diced"})]})]}),s.jsxs("div",{style:Ce.modalFooter,children:[s.jsx("button",{onClick:()=>T(!1),style:Ce.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>fs.mutate({ingredient_id:L,quantity:parseFloat(H),unit:O||void 0,notes:G||void 0}),disabled:!L||!H||fs.isPending,style:Ce.primaryBtn,children:fs.isPending?"Adding...":"Add"})]}),xn.error&&s.jsx("div",{style:Ce.errorMsg,children:xn.error.message})]})}),s.jsx(A0,{open:re,onClose:()=>me(!1),onSaved:$=>{const ze=XN($.standard_unit);W($.id),U($.standard_unit),I(ze),A($.name)},prePopulateName:F}),s.jsx(A0,{open:!!J&&!!hn,onClose:()=>ne(null),onSaved:()=>{ne(null),o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})},editingIngredient:hn||void 0}),X&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:Ce.modal,children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Sub-Recipe"}),s.jsx("button",{onClick:()=>pe(!1),style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("label",{style:Ce.label,children:"Select Component Recipe"}),s.jsxs("select",{value:(we==null?void 0:we.toString())||"",onChange:$=>{const ze=parseInt($.target.value);Ne(ze);const Qe=Ti==null?void 0:Ti.find(pt=>pt.id===ze);Le((Qe==null?void 0:Qe.batch_output_type)==="bulk"&&(Qe==null?void 0:Qe.batch_yield_unit)||"")},style:Ce.input,children:[s.jsx("option",{value:"",children:"Select..."}),Ti==null?void 0:Ti.filter($=>$.id!==e).map($=>s.jsxs("option",{value:$.id,children:[$.name," (",$.batch_output_type==="bulk"?`yield: ${$.batch_yield_qty}${$.batch_yield_unit}`:`batch: ${$.batch_portions}`,")"]},$.id))]}),(()=>{const $=Ti==null?void 0:Ti.find(kt=>kt.id===we),ze=($==null?void 0:$.batch_output_type)==="bulk",Qe=($==null?void 0:$.batch_yield_unit)||"",pt=ze?Qe==="ml"||Qe==="ltr"?["ml","ltr"]:Qe==="g"||Qe==="kg"?["g","kg"]:[Qe]:[];return s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ce.label,children:ze?"Amount":"Portions Needed"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:st,onChange:kt=>Ve(kt.target.value),style:{...Ce.input,flex:1},step:ze?"0.1":"0.5",min:"0.1"}),ze&&pt.length>1?s.jsx("select",{value:Re,onChange:kt=>Le(kt.target.value),style:{...Ce.input,width:"80px",flex:"none"},children:pt.map(kt=>s.jsx("option",{value:kt,children:kt},kt))}):ze?s.jsx("span",{style:{padding:"0.5rem 0",fontSize:"0.85rem",color:"#555"},children:Qe}):null]})]})})()]}),s.jsxs("div",{style:Ce.modalFooter,children:[s.jsx("button",{onClick:()=>pe(!1),style:Ce.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>xn.mutate({child_recipe_id:we,portions_needed:parseFloat(st),portions_needed_unit:Re||void 0}),disabled:!we||!st||xn.isPending,style:Ce.primaryBtn,children:xn.isPending?"Adding...":"Add"})]}),xn.error&&s.jsx("div",{style:Ce.errorMsg,children:xn.error.message})]})}),rt&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:Ce.modal,children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:ut?"Edit Step":"Add Step"}),s.jsx("button",{onClick:()=>{$e(!1),Ot(null)},style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("label",{style:Ce.label,children:"Title (optional)"}),s.jsx("input",{value:ce,onChange:$=>Je($.target.value),style:Ce.input,placeholder:"e.g. Prepare the base, Sear the protein"}),s.jsx("label",{style:Ce.label,children:"Instructions"}),s.jsx("textarea",{value:jt,onChange:$=>ct($.target.value),style:{...Ce.input,minHeight:"80px"}}),s.jsx("label",{style:Ce.label,children:"Duration (minutes, optional)"}),s.jsx("input",{type:"number",value:Se,onChange:$=>ot($.target.value),style:Ce.input})]}),s.jsxs("div",{style:Ce.modalFooter,children:[s.jsx("button",{onClick:()=>{$e(!1),Ot(null)},style:Ce.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>{ut?Zl.mutate({stepId:ut,data:{title:ce||"",instruction:jt,duration_minutes:Se?parseInt(Se):void 0}}):nn.mutate({title:ce||void 0,instruction:jt,step_number:((Ft==null?void 0:Ft.steps.length)||0)+1,duration_minutes:Se?parseInt(Se):void 0})},disabled:!jt||nn.isPending||Zl.isPending,style:Ce.primaryBtn,children:ut?Zl.isPending?"Saving...":"Save":nn.isPending?"Adding...":"Add Step"})]})]})}),xr&&s.jsxs("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.85)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,cursor:"pointer"},onClick:()=>Ss(null),children:[s.jsx("img",{src:xr,alt:"Dish image",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"},onClick:$=>$.stopPropagation()}),s.jsx("button",{onClick:()=>Ss(null),style:{position:"absolute",top:"20px",right:"20px",background:"rgba(255,255,255,0.2)",border:"none",color:"white",fontSize:"1.5rem",cursor:"pointer",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center"},children:"✕"})]}),zi&&Ft&&s.jsx(UK,{recipeId:Ft.id,recipeName:Ft.name,recipeDesc:Ft.description||"",recipePrice:Ft.gross_sell_price,onClose:()=>aa(!1),onPublished:()=>{aa(!1),o.invalidateQueries({queryKey:["dish-menus",e]})}}),Ai&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:{...Ce.modal,width:"550px"},children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Select SambaPOS Menu Item"}),s.jsx("button",{onClick:()=>{Ks(!1),Fr("")},style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("input",{value:un,onChange:$=>Fr($.target.value),style:{...Ce.input,marginBottom:"0.75rem"},placeholder:"Search menu items...",autoFocus:!0}),js?js.length===0?s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"No items found. Check SambaPOS connection and tracked categories."}):(()=>{const $=js.filter(Gt=>!un||Gt.menu_item_name.toLowerCase().includes(un.toLowerCase())||Gt.portion_name.toLowerCase().includes(un.toLowerCase())),ze={},Qe={};for(const Gt of $)ze[Gt.category]||(ze[Gt.category]={}),ze[Gt.category][Gt.menu_item_name]||(ze[Gt.category][Gt.menu_item_name]=[]),ze[Gt.category][Gt.menu_item_name].push(Gt.portion_name),Qe[Gt.menu_item_name]=Gt.on_pos_menu;const pt=o.getQueryData(["recipes-list-dish"]),kt={};if(pt){for(const Gt of pt)if(Gt.kds_menu_item_name){const Er=`${Gt.kds_menu_item_name}|${Gt.sambapos_portion_name||""}`;kt[Er]=Gt.name}}const Ht=(Gt,Er)=>{S(Gt),b(!0),Ar.mutate({kds_menu_item_name:Gt,sambapos_portion_name:Er==="Normal"?null:Er}),Ks(!1),Fr("")};return s.jsxs("div",{style:{maxHeight:"400px",overflow:"auto"},children:[Object.entries(ze).map(([Gt,Er])=>s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"#e94560",textTransform:"uppercase",padding:"0.3rem 0",borderBottom:"1px solid #eee",marginBottom:"0.25rem"},children:Gt}),Object.entries(Er).map(([ar,Kn])=>{const is=Kn.length===1&&Kn[0]==="Normal";return s.jsx("div",{children:is?s.jsxs("div",{onClick:()=>Ht(ar,"Normal"),style:{padding:"0.4rem 0.5rem",cursor:"pointer",borderBottom:"1px solid #f5f5f5",fontSize:"0.85rem",display:"flex",justifyContent:"space-between",alignItems:"center"},onMouseEnter:On=>On.currentTarget.style.background="#f0f7ff",onMouseLeave:On=>On.currentTarget.style.background="transparent",children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[ar,s.jsxs("span",{style:{fontSize:"0.65rem",color:Qe[ar]?"#16a34a":"#ccc",fontWeight:600},children:["POS ",Qe[ar]?"✓":"✗"]})]}),kt[`${ar}|`]&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#999"},children:["→ ",kt[`${ar}|`]]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{padding:"0.4rem 0.5rem",fontSize:"0.85rem",fontWeight:600,color:"#333",borderBottom:"1px solid #f5f5f5",display:"flex",alignItems:"center",gap:"0.5rem"},children:[ar,s.jsxs("span",{style:{fontSize:"0.65rem",color:Qe[ar]?"#16a34a":"#ccc",fontWeight:600},children:["POS ",Qe[ar]?"✓":"✗"]})]}),Kn.map(On=>{const sn=`${ar}|${On==="Normal"?"":On}`;return s.jsxs("div",{onClick:()=>Ht(ar,On),style:{padding:"0.35rem 0.5rem 0.35rem 1.5rem",cursor:"pointer",borderBottom:"1px solid #f5f5f5",fontSize:"0.85rem",display:"flex",justifyContent:"space-between",alignItems:"center"},onMouseEnter:ps=>ps.currentTarget.style.background="#f0f7ff",onMouseLeave:ps=>ps.currentTarget.style.background="transparent",children:[s.jsxs("span",{style:{color:"#555"},children:["↳ ",On]}),kt[sn]&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#999"},children:["→ ",kt[sn]]})]},On)})]})},ar)})]},Gt)),Object.keys(ze).length===0&&s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"No items match your search."})]})})():s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"Loading SambaPOS items..."})]})]})})]})}const Ce={page:{padding:"1.5rem",maxWidth:"1000px",margin:"0 auto"},topBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},backBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},metaSection:{background:"white",padding:"1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},metaRow:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"0.75rem"},metaGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:"0.75rem",marginBottom:"0.75rem"},nameInput:{fontSize:"1.3rem",fontWeight:600,padding:"0.4rem",border:"1px solid #e0e0e0",borderRadius:"6px"},section:{background:"white",padding:"1rem 1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.5rem",fontSize:"0.85rem"},addBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},removeBtn:{padding:"2px 6px",background:"none",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.7rem",color:"#e94560"},costPanel:{background:"#f8f9fa",padding:"1.25rem",borderRadius:"8px",border:"2px solid #e0e0e0",marginBottom:"1rem"},costHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},costGrid:{display:"flex",gap:"1.5rem",flexWrap:"wrap"},costBox:{minWidth:"120px"},costLabel:{fontSize:"0.75rem",color:"#666",fontWeight:600},costValue:{fontSize:"1.3rem",fontWeight:700,color:"#333"},gpBadge:{background:"white",padding:"0.35rem 0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.8rem"},flagWarning:{background:"#fff3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem"},logEntry:{display:"flex",gap:"0.5rem",padding:"0.35rem 0",borderBottom:"1px solid #f0f0f0",alignItems:"center"},linkBtn:{background:"none",border:"none",color:"#3b82f6",cursor:"pointer",fontSize:"0.8rem",padding:0},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},secondaryBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.5rem",marginBottom:"0.2rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},suggestions:{background:"white",border:"1px solid #ddd",borderRadius:"6px",maxHeight:"150px",overflow:"auto",marginTop:"4px"},suggestionItem:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.85rem"},errorMsg:{padding:"0.75rem 1.25rem",color:"#dc3545",fontSize:"0.85rem"},reorderBtn:{padding:"0",width:"18px",height:"16px",background:"none",border:"1px solid #ddd",borderRadius:"3px",cursor:"pointer",fontSize:"0.55rem",color:"#666",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1},imageGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))",gap:"0.75rem"},imageCard:{background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0",overflow:"hidden"},imageThumb:{width:"100%",height:"120px",objectFit:"cover",display:"block"}};function tpe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(""),[o,a]=k.useState(!1),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState(""),[g,m]=k.useState(!0),[y,v]=k.useState(!1),[x,w]=k.useState(null),[S,_]=k.useState(null),[b,C]=k.useState(null),[T,F]=k.useState(""),{data:A,isLoading:D}=Oe({queryKey:["menus"],queryFn:async()=>{const H=await fetch("/api/menus",{headers:{Authorization:`Bearer ${n}`}});if(!H.ok)throw new Error("Failed to fetch menus");return H.json()},enabled:!!n,staleTime:0}),P=Ue({mutationFn:async H=>{const z=await fetch("/api/menus",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(H)});if(!z.ok){const G=await z.json().catch(()=>({}));throw new Error(G.detail||"Failed to create menu")}return z.json()},onSuccess:H=>{t.invalidateQueries({queryKey:["menus"]}),a(!1),d(""),u(""),p(""),e(`/menus/${H.id}`)}}),L=Ue({mutationFn:async({id:H,is_active:z})=>{if(!(await fetch(`/api/menus/${H}`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_active:z})})).ok)throw new Error("Failed to update")},onSuccess:()=>t.invalidateQueries({queryKey:["menus"]})}),W=Ue({mutationFn:async H=>{if(!(await fetch(`/api/menus/${H}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to delete")},onSuccess:()=>t.invalidateQueries({queryKey:["menus"]})}),O=Ue({mutationFn:async({id:H,name:z})=>{const G=await fetch(`/api/menus/${H}/duplicate`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:z})});if(!G.ok){const te=await G.json().catch(()=>({}));throw new Error(te.detail||"Failed to duplicate")}return G.json()},onSuccess:H=>{t.invalidateQueries({queryKey:["menus"]}),C(null),F(""),e(`/menus/${H.id}`)}}),U=Ue({mutationFn:async H=>{if(!(await fetch("/api/menus/reorder",{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({ids:H})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>t.invalidateQueries({queryKey:["menus"]})}),M=()=>{if(x===null||S===null||!A)return;const H=[...A],[z]=H.splice(x,1);H.splice(S,0,z),U.mutate(H.map(G=>G.id)),w(null),_(null)},I=(A==null?void 0:A.filter(H=>!r||H.name.toLowerCase().includes(r.toLowerCase())))||[];return s.jsxs("div",{style:Xn.container,children:[s.jsxs("div",{style:Xn.header,children:[s.jsx("h2",{style:Xn.title,children:"Menus"}),s.jsxs("div",{style:Xn.headerActions,children:[s.jsx("input",{type:"text",placeholder:"Search menus...",value:r,onChange:H=>i(H.target.value),style:Xn.searchInput}),I.length>1&&s.jsx("button",{onClick:()=>v(!y),style:{...Xn.btn,background:y?"#3b82f6":void 0,color:y?"#fff":void 0},children:y?"Done":"Sort"}),s.jsx("button",{onClick:()=>a(!0),style:Xn.btnPrimary,children:"+ New Menu"})]})]}),D&&s.jsx("p",{style:{padding:"1rem"},children:"Loading..."}),!D&&I.length===0&&s.jsx("p",{style:{padding:"1rem",color:"#666"},children:"No menus found. Create your first menu to get started."}),s.jsx("div",{style:Xn.list,children:I.map((H,z)=>s.jsxs("div",{style:{...Xn.card,opacity:x===z?.4:1,background:S===z?"#e0f2fe":"#fff"},draggable:y,onDragStart:()=>{w(z)},onDragOver:G=>{G.preventDefault(),_(z)},onDrop:M,onDragEnd:()=>{w(null),_(null)},children:[y&&s.jsx("span",{style:Xn.dragHandle,children:"☰"}),s.jsxs("div",{style:Xn.cardContent,onClick:()=>e(`/menus/${H.id}`),children:[s.jsxs("div",{style:Xn.cardHeader,children:[s.jsx("span",{style:Xn.menuName,children:H.name}),s.jsx("span",{style:{...Xn.badge,background:H.is_active?"#dcfce7":"#f3f4f6",color:H.is_active?"#166534":"#6b7280"},children:H.is_active?"Active":"Inactive"})]}),H.description&&s.jsx("p",{style:Xn.desc,children:H.description}),s.jsxs("div",{style:Xn.meta,children:[s.jsxs("span",{children:[H.division_count," section",H.division_count!==1?"s":""]}),s.jsx("span",{style:{margin:"0 0.5rem"},children:"·"}),s.jsxs("span",{children:[H.item_count," dish",H.item_count!==1?"es":""]}),H.stale_count>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{margin:"0 0.5rem"},children:"·"}),s.jsxs("span",{style:{background:"#fef3c7",color:"#92400e",padding:"1px 6px",borderRadius:"3px",fontSize:"0.75rem",fontWeight:600},children:[H.stale_count," need",H.stale_count===1?"s":""," republishing"]})]})]})]}),s.jsxs("div",{style:Xn.cardActions,children:[s.jsx("button",{onClick:G=>{G.stopPropagation(),L.mutate({id:H.id,is_active:!H.is_active})},style:Xn.btnSmall,title:H.is_active?"Deactivate":"Activate",children:H.is_active?"Deactivate":"Activate"}),s.jsx("button",{onClick:G=>{G.stopPropagation(),C(H.id),F(`${H.name} (Copy)`)},style:Xn.btnSmall,children:"Duplicate"}),s.jsx("button",{onClick:G=>{G.stopPropagation(),confirm(`Delete "${H.name}"? This will remove all divisions and items.`)&&W.mutate(H.id)},style:{...Xn.btnSmall,color:"#dc2626"},children:"Delete"})]})]},H.id))}),o&&s.jsx("div",{style:Xn.overlay,onClick:()=>a(!1),children:s.jsxs("div",{style:Xn.modal,onClick:H=>H.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:"New Menu"}),s.jsx("label",{style:Xn.label,children:"Name *"}),s.jsx("input",{type:"text",value:l,onChange:H=>d(H.target.value),style:Xn.input,placeholder:"e.g. Evening Menu",autoFocus:!0}),s.jsx("label",{style:Xn.label,children:"Description (customer-facing)"}),s.jsx("input",{type:"text",value:c,onChange:H=>u(H.target.value),style:Xn.input,placeholder:"e.g. Seasonal tasting menu"}),s.jsx("label",{style:Xn.label,children:"Internal Notes"}),s.jsx("textarea",{value:f,onChange:H=>p(H.target.value),style:{...Xn.input,minHeight:"60px",resize:"vertical"},placeholder:"e.g. Available Fri-Sun 6pm-9pm"}),s.jsxs("label",{style:Xn.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:g,onChange:H=>m(H.target.checked)}),s.jsx("span",{style:{marginLeft:"0.5rem"},children:"Pre-load default sections (Starters, Mains, Sides, Desserts)"})]}),s.jsxs("div",{style:Xn.modalActions,children:[s.jsx("button",{onClick:()=>a(!1),style:Xn.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>P.mutate({name:l.trim(),description:c.trim()||null,notes:f.trim()||null,preset_divisions:g}),style:Xn.btnPrimary,disabled:!l.trim()||P.isPending,children:P.isPending?"Creating...":"Create Menu"})]}),P.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:P.error.message})]})}),b!==null&&s.jsx("div",{style:Xn.overlay,onClick:()=>C(null),children:s.jsxs("div",{style:Xn.modal,onClick:H=>H.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:"Duplicate Menu"}),s.jsx("label",{style:Xn.label,children:"New menu name *"}),s.jsx("input",{type:"text",value:T,onChange:H=>F(H.target.value),style:Xn.input,autoFocus:!0}),s.jsxs("div",{style:Xn.modalActions,children:[s.jsx("button",{onClick:()=>C(null),style:Xn.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>O.mutate({id:b,name:T.trim()}),style:Xn.btnPrimary,disabled:!T.trim()||O.isPending,children:O.isPending?"Duplicating...":"Duplicate"})]}),O.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:O.error.message})]})})]})}const Xn={container:{maxWidth:"900px",margin:"0 auto",padding:"1rem"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},title:{margin:0,fontSize:"1.5rem"},headerActions:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},searchInput:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",width:"200px"},list:{display:"flex",flexDirection:"column",gap:"0.5rem"},card:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.75rem 1rem",border:"1px solid #e5e7eb",borderRadius:"8px",background:"#fff",cursor:"pointer",transition:"box-shadow 0.2s"},dragHandle:{cursor:"grab",fontSize:"1rem",color:"#999"},cardContent:{flex:1,minWidth:0},cardHeader:{display:"flex",alignItems:"center",gap:"0.5rem"},menuName:{fontWeight:600,fontSize:"1rem"},badge:{padding:"2px 8px",borderRadius:"12px",fontSize:"0.75rem",fontWeight:500},desc:{margin:"0.25rem 0 0",fontSize:"0.875rem",color:"#666"},meta:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},cardActions:{display:"flex",gap:"0.25rem",flexShrink:0},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnSmall:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.75rem"},overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",minWidth:"360px",maxWidth:"500px",width:"90%"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.75rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",boxSizing:"border-box"},checkboxLabel:{display:"flex",alignItems:"center",marginTop:"1rem",fontSize:"0.875rem",cursor:"pointer"}};function npe({menuId:n,divisionId:e,divisionName:t,onClose:r,onPublished:i}){const{token:o,user:a}=gn(),[l,d]=k.useState("select"),[c,u]=k.useState(new Set),[f,p]=k.useState(""),[g,m]=k.useState((a==null?void 0:a.name)||""),[y,v]=k.useState({}),[x,w]=k.useState({}),{data:S}=Oe({queryKey:["dishes-for-bulk"],queryFn:async()=>{const D=await fetch("/api/recipes?recipe_type=dish",{headers:{Authorization:`Bearer ${o}`}});if(!D.ok)throw new Error("Failed");return D.json()},enabled:!!o}),{data:_}=Oe({queryKey:["bulk-flag-check",Array.from(c)],queryFn:async()=>{const D={};for(const P of c){const L=await fetch(`/api/food-flags/recipes/${P}/flags`,{headers:{Authorization:`Bearer ${o}`}});if(L.ok){const W=await L.json();D[P]={ok:!W.unassessed_ingredients||W.unassessed_ingredients.length===0,unassessed:W.unassessed_ingredients}}else D[P]={ok:!1}}return D},enabled:!!o&&l==="confirm"&&c.size>0}),b=Ue({mutationFn:async()=>{var W;const P=Array.from(c).filter(O=>{var U;return(U=_==null?void 0:_[O])==null?void 0:U.ok}).map(O=>{const U=S==null?void 0:S.find(M=>M.id===O);return{recipe_id:O,display_name:y[O]||(U==null?void 0:U.name)||"",description:(U==null?void 0:U.description)||null,price:x[O]?parseFloat(x[O]):(U==null?void 0:U.gross_sell_price)||null}}),L=await fetch(`/api/menus/${n}/items/bulk`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({division_id:e,confirmed_by_name:g.trim(),items:P})});if(!L.ok){const O=await L.json().catch(()=>({}));throw new Error(((W=O.detail)==null?void 0:W.message)||"Failed to bulk publish")}return L.json()},onSuccess:()=>i()}),C=(S||[]).filter(D=>!f||D.name.toLowerCase().includes(f.toLowerCase())),T=D=>{const P=new Set(c);P.has(D)?P.delete(D):P.add(D),u(P)},F=_?Array.from(c).filter(D=>{var P;return(P=_[D])==null?void 0:P.ok}).length:0,A=_?Array.from(c).filter(D=>_[D]&&!_[D].ok).length:0;return s.jsx("div",{style:ca.overlay,onClick:r,children:s.jsxs("div",{style:{...ca.modal,maxWidth:"600px"},onClick:D=>D.stopPropagation(),children:[s.jsxs("h3",{style:{margin:"0 0 0.5rem"},children:['Bulk Add Dishes to "',t,'"']}),l==="select"&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:f,onChange:D=>p(D.target.value),style:ca.input,placeholder:"Search dishes..."}),s.jsxs("div",{style:{maxHeight:"350px",overflow:"auto",border:"1px solid #eee",borderRadius:"4px",marginTop:"0.5rem"},children:[C.map(D=>{var P;return s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",cursor:"pointer",background:c.has(D.id)?"#eff6ff":"#fff",borderBottom:"1px solid #f3f4f6"},children:[s.jsx("input",{type:"checkbox",checked:c.has(D.id),onChange:()=>T(D.id)}),s.jsx("span",{style:{flex:1},children:D.name}),(P=D.flag_summary)==null?void 0:P.filter(L=>L.active).map((L,W)=>s.jsx("span",{style:ca.flagBadge,children:L.code||L.name},W))]},D.id)}),C.length===0&&s.jsx("p",{style:{padding:"0.5rem",color:"#999"},children:"No dishes found"})]}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#666",marginTop:"0.5rem"},children:[c.size," selected"]}),s.jsxs("div",{style:ca.modalActions,children:[s.jsx("button",{onClick:r,style:ca.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>d("confirm"),style:ca.btnPrimary,disabled:c.size===0,children:"Next: Review"})]})]}),l==="confirm"&&s.jsxs(s.Fragment,{children:[!_&&s.jsx("p",{children:"Checking allergens..."}),_&&s.jsxs(s.Fragment,{children:[A>0&&s.jsxs("div",{style:{background:"#fee2e2",padding:"0.5rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.875rem"},children:[s.jsxs("strong",{style:{color:"#dc2626"},children:[A," dish",A!==1?"es":""," blocked"]})," — unassessed ingredients"]}),s.jsx("div",{style:{maxHeight:"300px",overflow:"auto"},children:Array.from(c).map(D=>{const P=S==null?void 0:S.find(W=>W.id===D),L=_[D];return P?s.jsxs("div",{style:{padding:"0.5rem",borderBottom:"1px solid #eee",opacity:L!=null&&L.ok?1:.5},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{fontWeight:500},children:P.name}),!(L!=null&&L.ok)&&s.jsx("span",{style:{color:"#dc2626",fontSize:"0.75rem"},children:"BLOCKED"})]}),(L==null?void 0:L.ok)&&s.jsxs("div",{style:{display:"flex",gap:"0.25rem",marginTop:"0.25rem"},children:[s.jsx("input",{value:y[D]??P.name,onChange:W=>v(O=>({...O,[D]:W.target.value})),style:{...ca.inputSm,flex:1},placeholder:"Display name"}),s.jsx("input",{value:x[D]??(P.gross_sell_price?String(P.gross_sell_price):""),onChange:W=>w(O=>({...O,[D]:W.target.value})),style:{...ca.inputSm,width:"80px"},placeholder:"Price"})]})]},D):null})}),s.jsx("label",{style:ca.label,children:"Confirmed by *"}),s.jsx("input",{value:g,onChange:D=>m(D.target.value),style:ca.input}),s.jsxs("div",{style:ca.modalActions,children:[s.jsx("button",{onClick:()=>d("select"),style:ca.btn,children:"Back"}),s.jsx("button",{onClick:r,style:ca.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>b.mutate(),style:ca.btnPrimary,disabled:F===0||!g.trim()||b.isPending,children:b.isPending?"Publishing...":`Publish ${F} Dishes`})]}),b.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:b.error.message})]})]})]})})}const ca={overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"90%",maxHeight:"90vh",overflow:"auto"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.75rem"},input:{width:"100%",padding:"0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",boxSizing:"border-box"},inputSm:{padding:"0.25rem 0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.8rem"},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"},flagBadge:{padding:"1px 6px",background:"#f3f4f6",borderRadius:"4px",fontSize:"0.7rem",color:"#374151"}};function rpe({menuId:n,menuName:e,onClose:t}){const{token:r}=gn(),{data:i,isLoading:o}=Oe({queryKey:["menu-flag-matrix",n],queryFn:async()=>{const l=await fetch(`/api/menus/${n}/flags`,{headers:{Authorization:`Bearer ${r}`}});if(!l.ok)throw new Error("Failed");return l.json()},enabled:!!r});if(o)return s.jsx("div",{style:hl.overlay,onClick:t,children:s.jsx("div",{style:hl.modal,onClick:l=>l.stopPropagation(),children:"Loading..."})});if(!i)return null;const a=new Map;for(const l of i.all_flags)a.has(l.category_name)||a.set(l.category_name,[]),a.get(l.category_name).push(l);for(const[l,d]of a);return s.jsx("div",{style:hl.overlay,onClick:t,children:s.jsxs("div",{style:hl.modal,onClick:l=>l.stopPropagation(),children:[s.jsxs("div",{style:hl.printHeader,children:[s.jsxs("h3",{style:{margin:0},children:[e," — Allergen Matrix"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},className:"no-print",children:[s.jsx("button",{onClick:()=>window.print(),style:hl.btnPrimary,children:"Print"}),s.jsx("button",{onClick:t,style:hl.btn,children:"Close"})]})]}),i.divisions.length===0&&s.jsx("p",{style:{color:"#666"},children:"No items on this menu."}),i.divisions.length>0&&s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:hl.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...hl.th,minWidth:"180px"},children:"Dish"}),i.all_flags.map(l=>s.jsx("th",{style:{...hl.th,writingMode:"vertical-lr",textAlign:"center",fontSize:"0.7rem",padding:"4px 2px",maxWidth:"30px"},children:l.code||l.name},l.id))]})}),s.jsx("tbody",{children:i.divisions.map(l=>s.jsxs(s.Fragment,{children:[s.jsx("tr",{children:s.jsx("td",{colSpan:i.all_flags.length+1,style:hl.sectionRow,children:l.name})},`div-${l.name}`),l.items.map(d=>s.jsxs("tr",{children:[s.jsx("td",{style:hl.td,children:d.display_name}),i.all_flags.map(c=>s.jsx("td",{style:{...hl.td,textAlign:"center",background:d.flags[String(c.id)]?"#fee2e2":"transparent",color:d.flags[String(c.id)]?"#dc2626":"#ccc",fontWeight:d.flags[String(c.id)]?700:400},children:d.flags[String(c.id)]?"Y":"-"},c.id))]},d.id))]}))})]})}),s.jsx("style",{children:` @media print { .no-print { display: none !important; } body > * { display: none !important; } body > div:last-child { display: block !important; } } `})]})})}const hl={overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"95%",maxWidth:"1000px",maxHeight:"90vh",overflow:"auto"},printHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{padding:"0.4rem",borderBottom:"2px solid #e5e7eb",fontWeight:600,textAlign:"left",fontSize:"0.8rem"},td:{padding:"0.35rem 0.4rem",borderBottom:"1px solid #f3f4f6",fontSize:"0.8rem"},sectionRow:{padding:"0.5rem",fontWeight:700,background:"#f9fafb",fontSize:"0.85rem",borderBottom:"1px solid #e5e7eb"},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"}};function ipe(){var on;const{id:n}=G_(),e=parseInt(n||"0"),{token:t,user:r}=gn(),i=go(),o=pi(),[a,l]=k.useState(!1),[d,c]=k.useState(""),[u,f]=k.useState(!1),[p,g]=k.useState(""),[m,y]=k.useState(!1),[v,x]=k.useState(""),[w,S]=k.useState(!1),[_,b]=k.useState(""),[C,T]=k.useState(null),[F,A]=k.useState(""),[D,P]=k.useState(!1),[L,W]=k.useState(null),[O,U]=k.useState(null),[M,I]=k.useState(null),[H,z]=k.useState(null),[G,te]=k.useState(null),[re,me]=k.useState(null),[J,ne]=k.useState(""),[ye,ke]=k.useState(""),[Ye,De]=k.useState(""),[qe,ue]=k.useState(null),[Ze,ee]=k.useState(null),[Z,ge]=k.useState(null),[Te,Be]=k.useState(!1),[he,He]=k.useState(!1),[Ge,ae]=k.useState(""),[K,de]=k.useState(new Set),{data:Y,isLoading:Q}=Oe({queryKey:["menu",e],queryFn:async()=>{const Ke=await fetch(`/api/menus/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!Ke.ok)throw new Error("Failed to fetch menu");return Ke.json()},enabled:!!t&&e>0,staleTime:0}),X=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Ke)})).ok)throw new Error("Failed to update")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),pe=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/divisions`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:Ke})})).ok)throw new Error("Failed to add division")},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),S(!1),b("")}}),we=Ue({mutationFn:async({divId:Ke,name:Rt})=>{if(!(await fetch(`/api/menus/${e}/divisions/${Ke}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:Rt})})).ok)throw new Error("Failed to rename")},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),T(null)}}),Ne=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/divisions/${Ke}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),st=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/divisions/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ids:Ke})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),Ve=Ue({mutationFn:async({itemId:Ke,data:Rt})=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Rt)})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),me(null)}}),Re=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to remove")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),Le=Ue({mutationFn:async({itemId:Ke,confirmed_by_name:Rt})=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}/republish`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({confirmed_by_name:Rt})})).ok)throw new Error("Failed to republish")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),rt=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/items/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ids:Ke})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),$e=Ue({mutationFn:async Ke=>{const Rt=await fetch(`/api/menus/${e}/republish-stale`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Ke)});if(!Rt.ok)throw new Error("Failed to batch republish");return Rt.json()},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),He(!1)}}),ce=Ue({mutationFn:async({itemId:Ke,file:Rt})=>{const vt=new FormData;if(vt.append("file",Rt),!(await fetch(`/api/menus/${e}/items/${Ke}/image`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:vt})).ok)throw new Error("Failed to upload image")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),Je=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}/image`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete image")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})});if(Q)return s.jsx("div",{style:{padding:"2rem"},children:"Loading..."});if(!Y)return s.jsx("div",{style:{padding:"2rem"},children:"Menu not found"});const jt=Y.divisions.flatMap(Ke=>Ke.items),ct=jt.filter(Ke=>Ke.is_stale).length,Se=jt.filter(Ke=>Ke.is_archived).length,ot=()=>{if(L===null||O===null)return;const Ke=[...Y.divisions],[Rt]=Ke.splice(L,1);Ke.splice(O,0,Rt),st.mutate(Ke.map(vt=>vt.id)),W(null),U(null)},ut=Ke=>{if(H===null||G===null)return;const Rt=[...Ke],[vt]=Rt.splice(H,1);Rt.splice(G,0,vt),rt.mutate(Rt.map(Cr=>Cr.id)),z(null),te(null)},Ot=Ke=>{const Rt=new Set(K);Rt.has(Ke)?Rt.delete(Ke):Rt.add(Ke),de(Rt)},An=jt.filter(Ke=>Ke.is_stale&&!Ke.is_archived);return s.jsxs("div",{style:qt.container,children:[s.jsx("button",{onClick:()=>i("/menus"),style:qt.backBtn,children:"← Menus"}),s.jsxs("div",{style:qt.menuHeader,children:[s.jsxs("div",{style:{flex:1},children:[a?s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{value:d,onChange:Ke=>c(Ke.target.value),style:qt.input,autoFocus:!0}),s.jsx("button",{onClick:()=>{X.mutate({name:d}),l(!1)},style:qt.btnPrimary,children:"Save"}),s.jsx("button",{onClick:()=>l(!1),style:qt.btn,children:"Cancel"})]}):s.jsx("h2",{style:{margin:0,cursor:"pointer"},onClick:()=>{c(Y.name),l(!0)},children:Y.name}),u?s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("input",{value:p,onChange:Ke=>g(Ke.target.value),style:qt.input,placeholder:"Customer-facing description"}),s.jsx("button",{onClick:()=>{X.mutate({description:p}),f(!1)},style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>f(!1),style:qt.btnSmall,children:"Cancel"})]}):s.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.875rem",color:"#666",cursor:"pointer"},onClick:()=>{g(Y.description||""),f(!0)},children:Y.description||"Click to add description..."}),m?s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("input",{value:v,onChange:Ke=>x(Ke.target.value),style:qt.input,placeholder:"Internal notes"}),s.jsx("button",{onClick:()=>{X.mutate({notes:v}),y(!1)},style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>y(!1),style:qt.btnSmall,children:"Cancel"})]}):s.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8rem",color:"#999",cursor:"pointer",fontStyle:"italic"},onClick:()=>{x(Y.notes||""),y(!0)},children:Y.notes?`Notes: ${Y.notes}`:"Click to add internal notes..."})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"flex-start",flexWrap:"wrap"},children:[s.jsx("button",{onClick:()=>X.mutate({is_active:!Y.is_active}),style:{...qt.btn,background:Y.is_active?"#dcfce7":"#f3f4f6",color:Y.is_active?"#166534":"#6b7280",border:"none"},children:Y.is_active?"Active":"Inactive"}),ct>0&&s.jsxs("button",{onClick:()=>{ae((r==null?void 0:r.name)||""),He(!0)},style:{...qt.btn,background:"#fef3c7",color:"#92400e",border:"none"},children:["Republish All Stale (",ct,")"]}),s.jsx("button",{onClick:()=>Be(!0),style:qt.btn,children:"Print Flag Matrix"})]})]}),ct>0&&s.jsxs("div",{style:{...qt.notifBar,background:"#fef3c7",borderColor:"#f59e0b"},children:[ct," item",ct!==1?"s":""," need",ct===1?"s":""," republishing"]}),Se>0&&s.jsxs("div",{style:{...qt.notifBar,background:"#fee2e2",borderColor:"#ef4444"},children:[Se," dish",Se!==1?"es have":" has"," been archived and should be removed"]}),s.jsxs("div",{style:qt.divHeader,children:[s.jsx("h3",{style:{margin:0},children:"Sections"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[Y.divisions.length>1&&s.jsx("button",{onClick:()=>P(!D),style:{...qt.btn,background:D?"#3b82f6":void 0,color:D?"#fff":void 0},children:D?"Done":"Sort"}),s.jsx("button",{onClick:()=>S(!0),style:qt.btnPrimary,children:"+ Add Section"})]})]}),w&&s.jsxs("div",{style:qt.inlineForm,children:[s.jsx("input",{value:_,onChange:Ke=>b(Ke.target.value),style:qt.input,placeholder:"Section name",autoFocus:!0}),s.jsx("button",{onClick:()=>{_.trim()&&pe.mutate(_.trim())},style:qt.btnPrimary,disabled:!_.trim(),children:"Add"}),s.jsx("button",{onClick:()=>{S(!1),b("")},style:qt.btn,children:"Cancel"})]}),Y.divisions.length===0&&s.jsx("p",{style:{color:"#666",padding:"1rem"},children:"No sections yet. Add a section to start publishing dishes."}),Y.divisions.map((Ke,Rt)=>s.jsxs("div",{style:{...qt.divisionCard,opacity:D&&L===Rt?.4:1,background:D&&O===Rt?"#e0f2fe":"#fff"},draggable:D,onDragStart:()=>W(Rt),onDragOver:vt=>{D&&(vt.preventDefault(),U(Rt))},onDrop:()=>{D&&ot()},onDragEnd:()=>{W(null),U(null)},children:[s.jsxs("div",{style:qt.divisionHeader,onClick:()=>Ot(Ke.id),children:[D&&s.jsx("span",{style:qt.dragHandle,children:"☰"}),s.jsx("span",{style:{cursor:"pointer",userSelect:"none"},children:K.has(Ke.id)?"▶":"▼"}),C===Ke.id?s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flex:1},onClick:vt=>vt.stopPropagation(),children:[s.jsx("input",{value:F,onChange:vt=>A(vt.target.value),style:qt.input,autoFocus:!0}),s.jsx("button",{onClick:()=>we.mutate({divId:Ke.id,name:F}),style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>T(null),style:qt.btnSmall,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontWeight:600,flex:1},children:Ke.name}),s.jsxs("span",{style:{fontSize:"0.8rem",color:"#999"},children:[Ke.items.length," item",Ke.items.length!==1?"s":""]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:vt=>vt.stopPropagation(),children:[s.jsx("button",{onClick:()=>{T(Ke.id),A(Ke.name)},style:qt.btnTiny,children:"Rename"}),s.jsx("button",{onClick:()=>ee(Ke.id),style:{...qt.btnTiny,background:"#eff6ff",color:"#2563eb"},children:"+ Dish"}),s.jsx("button",{onClick:()=>ge(Ke.id),style:{...qt.btnTiny,background:"#f0fdf4",color:"#166534"},children:"+ Bulk"}),s.jsx("button",{onClick:()=>{const vt=Ke.items.length>0?`Delete "${Ke.name}" and its ${Ke.items.length} item(s)?`:`Delete "${Ke.name}"?`;confirm(vt)&&Ne.mutate(Ke.id)},style:{...qt.btnTiny,color:"#dc2626"},children:"Delete"})]})]}),!K.has(Ke.id)&&s.jsxs("div",{style:qt.itemsList,children:[Ke.items.length>1&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",padding:"0.25rem 0"},children:s.jsx("button",{onClick:()=>I(M===Ke.id?null:Ke.id),style:{...qt.btnTiny,background:M===Ke.id?"#3b82f6":void 0,color:M===Ke.id?"#fff":void 0},children:M===Ke.id?"Done":"Sort"})}),Ke.items.map((vt,Cr)=>s.jsxs("div",{style:{...qt.itemRow,opacity:vt.is_archived?.5:M===Ke.id&&H===Cr?.4:1,background:M===Ke.id&&G===Cr?"#e0f2fe":vt.is_archived?"#f9fafb":"transparent"},draggable:M===Ke.id,onDragStart:()=>z(Cr),onDragOver:Qt=>{M===Ke.id&&(Qt.preventDefault(),te(Cr))},onDrop:()=>{M===Ke.id&&ut(Ke.items)},onDragEnd:()=>{z(null),te(null)},children:[M===Ke.id&&s.jsx("span",{style:qt.dragHandle,children:"☰"}),vt.has_image?s.jsx("img",{src:`/api/menus/${e}/items/${vt.id}/image?token=${t}`,alt:"",style:qt.thumbnail}):s.jsx("div",{style:qt.thumbnailPlaceholder,children:s.jsxs("label",{style:{cursor:"pointer",fontSize:"0.7rem",color:"#999"},children:["+ img",s.jsx("input",{type:"file",accept:"image/*",style:{display:"none"},onChange:Qt=>{var Lr;const Ci=(Lr=Qt.target.files)==null?void 0:Lr[0];Ci&&ce.mutate({itemId:vt.id,file:Ci})}})]})}),s.jsx("div",{style:{flex:1,minWidth:0},children:re===vt.id?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},onClick:Qt=>Qt.stopPropagation(),children:[s.jsx("input",{value:J,onChange:Qt=>ne(Qt.target.value),style:qt.inputSm,placeholder:"Display name"}),s.jsx("input",{value:ye,onChange:Qt=>ke(Qt.target.value),style:qt.inputSm,placeholder:"Description"}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem",alignItems:"center"},children:[s.jsx("input",{value:Ye,onChange:Qt=>De(Qt.target.value),style:{...qt.inputSm,width:"80px"},placeholder:"Price"}),s.jsx("select",{value:qe||"",onChange:Qt=>ue(parseInt(Qt.target.value)),style:qt.inputSm,children:Y.divisions.map(Qt=>s.jsx("option",{value:Qt.id,children:Qt.name},Qt.id))}),s.jsx("button",{onClick:()=>{const Qt={};J&&(Qt.display_name=J),ye!==void 0&&(Qt.description=ye),Ye&&(Qt.price=parseFloat(Ye)),qe&&qe!==Ke.id&&(Qt.division_id=qe),Ve.mutate({itemId:vt.id,data:Qt})},style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>me(null),style:qt.btnSmall,children:"Cancel"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{fontWeight:500},children:vt.display_name}),vt.price&&s.jsxs("span",{style:{color:"#666",fontSize:"0.875rem"},children:["£",vt.price]}),vt.is_archived&&s.jsx("span",{style:{...qt.badgeSm,background:"#fee2e2",color:"#dc2626"},children:"Archived"}),vt.is_stale&&s.jsx("span",{style:{...qt.badgeSm,background:"#fef3c7",color:"#92400e"},title:vt.stale_reason||"",children:"Needs Republishing"})]}),vt.description&&s.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:"0.8rem",color:"#666"},children:vt.description}),vt.snapshot_json&&vt.snapshot_json.confirmed_flags&&s.jsx("div",{style:{display:"flex",gap:"0.25rem",marginTop:"0.25rem",flexWrap:"wrap"},children:vt.snapshot_json.confirmed_flags.map((Qt,Ci)=>s.jsx("span",{style:{...qt.flagBadge},children:Qt.code||Qt.name},Ci))})]})}),re!==vt.id&&s.jsxs("div",{style:{display:"flex",gap:"0.25rem",flexShrink:0},children:[s.jsx("button",{onClick:()=>{me(vt.id),ne(vt.display_name),ke(vt.description||""),De(vt.price||""),ue(Ke.id)},style:qt.btnTiny,children:"Edit"}),vt.is_stale&&!vt.is_archived&&s.jsx("button",{onClick:()=>{const Qt=prompt("Confirmed by:",(r==null?void 0:r.name)||"");Qt&&Le.mutate({itemId:vt.id,confirmed_by_name:Qt})},style:{...qt.btnTiny,background:"#fef3c7",color:"#92400e"},children:"Republish"}),vt.has_image&&s.jsx("button",{onClick:()=>{confirm("Remove image?")&&Je.mutate(vt.id)},style:{...qt.btnTiny,color:"#dc2626"},children:"- img"}),!vt.has_image&&s.jsxs("label",{style:{...qt.btnTiny,background:"#f0fdf4",color:"#166534",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:["+ img",s.jsx("input",{type:"file",accept:"image/*",style:{display:"none"},onChange:Qt=>{var Lr;const Ci=(Lr=Qt.target.files)==null?void 0:Lr[0];Ci&&ce.mutate({itemId:vt.id,file:Ci})}})]}),s.jsx("button",{onClick:()=>{confirm(`Remove "${vt.display_name}" from menu?`)&&Re.mutate(vt.id)},style:{...qt.btnTiny,color:"#dc2626"},children:"Remove"})]})]},vt.id)),Ke.items.length===0&&s.jsxs("p",{style:{color:"#999",fontSize:"0.875rem",padding:"0.5rem 0"},children:["No dishes in this section."," ",s.jsx("button",{onClick:()=>ee(Ke.id),style:{...qt.btnTiny,background:"#eff6ff",color:"#2563eb"},children:"+ Add Dish"})]})]})]},Ke.id)),Ze!==null&&s.jsx(UK,{menuId:e,menuName:Y.name,divisions:Y.divisions,preSelectedDivisionId:Ze,onClose:()=>ee(null),onPublished:()=>{o.invalidateQueries({queryKey:["menu",e]}),ee(null)}}),Z!==null&&s.jsx(npe,{menuId:e,divisionId:Z,divisionName:((on=Y.divisions.find(Ke=>Ke.id===Z))==null?void 0:on.name)||"",onClose:()=>ge(null),onPublished:()=>{o.invalidateQueries({queryKey:["menu",e]}),ge(null)}}),Te&&s.jsx(rpe,{menuId:e,menuName:Y.name,onClose:()=>Be(!1)}),he&&s.jsx("div",{style:qt.overlay,onClick:()=>He(!1),children:s.jsxs("div",{style:{...qt.modal,maxWidth:"600px"},onClick:Ke=>Ke.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:"Batch Republish Stale Items"}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#666",marginBottom:"1rem"},children:[An.length," item",An.length!==1?"s":""," will be republished with updated allergen information."]}),s.jsx("div",{style:{maxHeight:"300px",overflow:"auto",marginBottom:"1rem"},children:An.map(Ke=>{const Rt=Ke.snapshot_json?Ke.snapshot_json.confirmed_flags||[]:[];return s.jsxs("div",{style:{padding:"0.5rem",borderBottom:"1px solid #eee"},children:[s.jsx("span",{style:{fontWeight:500},children:Ke.display_name}),Ke.stale_reason&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#92400e",marginLeft:"0.5rem"},children:["(",Ke.stale_reason,")"]}),s.jsx("div",{style:{display:"flex",gap:"0.25rem",marginTop:"0.25rem",flexWrap:"wrap"},children:Rt.map((vt,Cr)=>s.jsx("span",{style:qt.flagBadge,children:vt.code||vt.name},Cr))})]},Ke.id)})}),s.jsx("label",{style:qt.label,children:"Confirmed by *"}),s.jsx("input",{value:Ge,onChange:Ke=>ae(Ke.target.value),style:qt.input}),s.jsxs("div",{style:qt.modalActions,children:[s.jsx("button",{onClick:()=>He(!1),style:qt.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>$e.mutate({confirmed_by_name:Ge,items:An.map(Ke=>({id:Ke.id,confirmed:!0}))}),style:qt.btnPrimary,disabled:!Ge.trim()||$e.isPending,children:$e.isPending?"Republishing...":`Republish ${An.length} Items`})]})]})})]})}const qt={container:{maxWidth:"1000px",margin:"0 auto",padding:"1rem"},backBtn:{background:"none",border:"none",color:"#2563eb",cursor:"pointer",fontSize:"0.875rem",padding:"0.25rem 0",marginBottom:"0.5rem"},menuHeader:{display:"flex",justifyContent:"space-between",gap:"1rem",marginBottom:"1rem",flexWrap:"wrap"},notifBar:{padding:"0.5rem 1rem",borderRadius:"6px",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.5rem",borderLeft:"4px solid"},divHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem",marginTop:"1rem"},divisionCard:{border:"1px solid #e5e7eb",borderRadius:"8px",marginBottom:"0.5rem",overflow:"hidden"},divisionHeader:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.75rem 1rem",background:"#f9fafb",cursor:"pointer",borderBottom:"1px solid #e5e7eb"},dragHandle:{cursor:"grab",fontSize:"1rem",color:"#999"},itemsList:{padding:"0.5rem 1rem"},itemRow:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0",borderBottom:"1px solid #f3f4f6"},thumbnail:{width:"48px",height:"48px",objectFit:"cover",borderRadius:"4px",flexShrink:0},thumbnailPlaceholder:{width:"48px",height:"48px",border:"1px dashed #ddd",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},flagBadge:{padding:"1px 6px",background:"#f3f4f6",borderRadius:"4px",fontSize:"0.7rem",color:"#374151"},badgeSm:{padding:"1px 6px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:500},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnSmall:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.75rem"},btnTiny:{padding:"2px 6px",border:"1px solid #e5e7eb",borderRadius:"3px",background:"#fff",cursor:"pointer",fontSize:"0.7rem"},inlineForm:{display:"flex",gap:"0.5rem",marginBottom:"0.75rem",alignItems:"center"},input:{padding:"0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",flex:1},inputSm:{padding:"0.25rem 0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.8rem"},overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"90%",maxWidth:"500px"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.5rem"}};function spe(){const{token:n}=gn(),e=pi(),[t,r]=k.useState(""),[i,o]=k.useState(""),[a,l]=k.useState(!1),[d,c]=k.useState(null),{data:u}=Oe({queryKey:["ingredients-bulk"],queryFn:async()=>{const b=await fetch("/api/ingredients?limit=9999",{headers:{Authorization:`Bearer ${n}`}});if(!b.ok)throw new Error("Failed to fetch ingredients");return b.json()},enabled:!!n}),{data:f}=Oe({queryKey:["ingredient-categories"],queryFn:async()=>{const b=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():[]},enabled:!!n}),{data:p}=Oe({queryKey:["food-flag-categories-full"],queryFn:async()=>{const b=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${n}`}});if(!b.ok)throw new Error("Failed to fetch flag categories");return b.json()},enabled:!!n}),{data:g}=Oe({queryKey:["bulk-nones"],queryFn:async()=>{const b=await fetch("/api/ingredients/bulk-nones",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():{}},enabled:!!n}),{data:m}=Oe({queryKey:["bulk-suggestions"],queryFn:async()=>{const b=await fetch("/api/food-flags/suggest/bulk",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():{}},enabled:!!n}),y=Ue({mutationFn:async({ingredientId:b,flagId:C,action:T})=>{const F=u==null?void 0:u.find(L=>L.id===b),A=(F==null?void 0:F.flags.map(L=>L.food_flag_id))||[];let D;if(T==="add"?D=[...A,C]:D=A.filter(L=>L!==C),!(await fetch(`/api/ingredients/${b}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:D})})).ok)throw new Error("Failed to update flags")},onSuccess:()=>{e.invalidateQueries({queryKey:["ingredients-bulk"]}),e.invalidateQueries({queryKey:["bulk-nones"]})}}),v=Ue({mutationFn:async({ingredientId:b,categoryId:C})=>{if(!(await fetch(`/api/ingredients/${b}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:C})})).ok)throw new Error("Failed to toggle none")},onSuccess:()=>{e.invalidateQueries({queryKey:["ingredients-bulk"]}),e.invalidateQueries({queryKey:["bulk-nones"]})}}),x=b=>{c(d===b.id?null:b.id)},w=(p==null?void 0:p.filter(b=>b.required))||[],S=[];for(const b of w)for(const C of b.flags)S.push({flagId:C.id,flagName:C.name,flagCode:C.code,categoryId:b.id,categoryName:b.name,propagation:b.propagation_type});const _=(u||[]).filter(b=>{if(t&&!b.name.toLowerCase().includes(t.toLowerCase())||i&&b.category_id!==parseInt(i))return!1;if(a){const C=(g==null?void 0:g[b.id])||[];for(const T of w){if(C.includes(T.id))continue;if(!b.flags.some(A=>T.flags.some(D=>D.id===A.food_flag_id)))return!0}return!1}return!0});return s.jsxs("div",{style:fl.page,children:[s.jsx("h2",{style:{margin:"0 0 0.75rem 0"},children:"Bulk Allergen Assessment"}),s.jsxs("div",{style:fl.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search ingredients...",value:t,onChange:b=>r(b.target.value),style:fl.searchInput}),s.jsxs("select",{value:i,onChange:b=>o(b.target.value),style:fl.select,children:[s.jsx("option",{value:"",children:"All Categories"}),f==null?void 0:f.map(b=>s.jsx("option",{value:b.id,children:b.name},b.id))]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"0.85rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:a,onChange:b=>l(b.target.checked)}),"Unassessed only"]}),s.jsxs("span",{style:{fontSize:"0.85rem",color:"#666",marginLeft:"auto"},children:[_.length," ingredients"]})]}),S.length===0?s.jsx("div",{style:fl.emptyState,children:'No required flag categories found. Go to Settings > Food Flags and mark allergen categories as "Required".'}):s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:fl.table,children:[s.jsx("thead",{style:{position:"sticky",top:0,zIndex:3},children:s.jsxs("tr",{children:[s.jsx("th",{style:{...fl.th,position:"sticky",left:0,background:"#fafafa",zIndex:4,minWidth:"200px"},children:"Ingredient"}),w.map(b=>s.jsx("th",{style:{...fl.th,textAlign:"center",fontSize:"0.7rem",background:"#f0fdf4",minWidth:"50px"},title:`None apply for ${b.name}`,children:"None"},`cat-none-${b.id}`)),S.map(b=>s.jsx("th",{style:{...fl.th,textAlign:"center",minWidth:"45px",writingMode:"vertical-lr",fontSize:"0.7rem"},title:`${b.flagName} (${b.categoryName})`,children:b.flagCode||b.flagName},b.flagId))]})}),_.map(b=>{const C=new Set(b.flags.map(W=>W.food_flag_id)),T=(g==null?void 0:g[b.id])||[],F=d===b.id,A=m==null?void 0:m[b.id],D=A==null?void 0:A.filter(W=>!C.has(W.flag_id)),P=!!(D!=null&&D.length),L=1+w.length+S.length;return s.jsxs("tbody",{children:[s.jsxs("tr",{style:fl.tr,children:[s.jsxs("td",{style:{...fl.td,position:"sticky",left:0,zIndex:1,fontWeight:500,cursor:"pointer",background:F?"#f0f7ff":P?"#fffbeb":"white",borderLeft:P?"3px solid #f59e0b":void 0},onClick:()=>x(b),title:P?`${D.length} suggested allergen(s) — click to review`:"Click to show details",children:[s.jsx("span",{style:{fontSize:"0.65rem",color:"#888",marginRight:"4px"},children:F?"▼":"▶"}),b.name,b.category_name&&s.jsx("span",{style:{fontSize:"0.7rem",color:"#999",marginLeft:"6px"},children:b.category_name}),b.is_prepackaged&&s.jsx("span",{style:{fontSize:"0.6rem",color:"#6366f1",marginLeft:"6px",fontWeight:600},children:"PKG"})]}),w.map(W=>{const O=T.includes(W.id);return s.jsx("td",{style:{...fl.td,textAlign:"center",background:O?"#dcfce7":void 0},children:s.jsx("input",{type:"checkbox",checked:O,onChange:()=>v.mutate({ingredientId:b.id,categoryId:W.id}),disabled:v.isPending,style:{cursor:"pointer"},title:`None apply for ${W.name}`})},`none-${W.id}`)}),S.map(W=>{const O=C.has(W.flagId),U=T.includes(W.categoryId),M=D==null?void 0:D.some(I=>I.flag_id===W.flagId);return s.jsx("td",{style:{...fl.td,textAlign:"center",background:O?W.propagation==="contains"?"#fef2f2":"#dcfce7":M?"#fffbeb":U?"#f8f8f8":void 0,opacity:U?.4:1},children:s.jsx("input",{type:"checkbox",checked:O,onChange:()=>y.mutate({ingredientId:b.id,flagId:W.flagId,action:O?"remove":"add"}),disabled:U||y.isPending,style:{cursor:U?"not-allowed":"pointer"},title:W.flagName+(M?" (suggested)":"")})},W.flagId)})]}),F&&s.jsx("tr",{children:s.jsx("td",{colSpan:L,style:{padding:"0.5rem 0.75rem",background:"#f8fafc",borderBottom:"2px solid #e0e0e0"},children:s.jsxs("div",{style:{display:"flex",gap:"1.5rem",fontSize:"0.8rem"},children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontWeight:600,color:"#555",marginBottom:"0.25rem",fontSize:"0.7rem",textTransform:"uppercase"},children:"Notes"}),s.jsx("div",{style:{color:b.notes?"#333":"#bbb",whiteSpace:"pre-wrap"},children:b.notes||"No notes"})]}),s.jsxs("div",{style:{flex:2},children:[s.jsxs("div",{style:{fontWeight:600,color:"#555",marginBottom:"0.25rem",fontSize:"0.7rem",textTransform:"uppercase"},children:["Label Ingredients ",b.is_prepackaged&&s.jsx("span",{style:{color:"#6366f1"},children:"(prepackaged)"})]}),s.jsx("div",{style:{color:b.product_ingredients?"#333":"#bbb",whiteSpace:"pre-wrap",maxHeight:"80px",overflow:"auto"},children:b.product_ingredients||"Not available"})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontWeight:600,color:"#555",marginBottom:"0.25rem",fontSize:"0.7rem",textTransform:"uppercase"},children:"Keyword Suggestions"}),D!=null&&D.length?s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.2rem"},children:D.map(W=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.15rem 0.3rem",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:"4px"},children:[s.jsxs("span",{children:[s.jsx("strong",{style:{fontSize:"0.75rem"},children:W.flag_name}),s.jsx("span",{style:{color:"#999",fontSize:"0.65rem",marginLeft:"0.25rem"},children:W.matched_keywords.join(", ")})]}),s.jsx("button",{onClick:()=>{w.find(U=>U.flags.some(M=>M.id===W.flag_id))&&y.mutate({ingredientId:b.id,flagId:W.flag_id,action:"add"})},disabled:y.isPending,style:{background:"#f59e0b",color:"white",border:"none",borderRadius:"3px",padding:"0.1rem 0.3rem",fontSize:"0.65rem",fontWeight:600,cursor:"pointer"},children:"Apply"})]},W.flag_id))}):s.jsx("div",{style:{color:"#bbb"},children:"No suggestions"})]})]})})})]},b.id)})]})})]})}const fl={page:{padding:"1.5rem",maxWidth:"1600px",margin:"0 auto"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},emptyState:{padding:"3rem",textAlign:"center",color:"#888",background:"#fafafa",borderRadius:"8px"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.5rem 0.4rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.75rem",fontWeight:600,color:"#555"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.35rem 0.4rem",fontSize:"0.85rem"}};function ZP(n,e){return e==="g"&&n<1?`£${(n*1e3).toFixed(2)}/kg`:e==="ml"&&n<1?`£${(n*1e3).toFixed(2)}/ltr`:`£${n.toFixed(4)}/${e||"?"}`}function ope(){const{token:n}=gn(),e=go(),[t,r]=k.useState(14),[i,o]=k.useState(null),[a,l]=k.useState("all"),{data:d,isLoading:c}=Oe({queryKey:["price-impact",t],queryFn:async()=>{const g=await fetch(`/api/recipes/price-impact?days=${t}`,{headers:{Authorization:`Bearer ${n}`}});if(!g.ok)throw new Error("Failed to fetch price impact");return g.json()},enabled:!!n}),u=(d==null?void 0:d.recipes.filter(g=>a==="all"||g.recipe_type===a))||[],f=(d==null?void 0:d.recipes.filter(g=>g.recipe_type==="dish").length)||0,p=(d==null?void 0:d.recipes.filter(g=>g.recipe_type==="component").length)||0;return s.jsxs("div",{style:gs.page,children:[s.jsxs("div",{style:gs.header,children:[s.jsx("h2",{style:{margin:0},children:"Price Impact Report"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("label",{style:{fontSize:"0.85rem",color:"#666"},children:"Period:"}),s.jsxs("select",{value:t,onChange:g=>r(Number(g.target.value)),style:gs.select,children:[s.jsx("option",{value:7,children:"7 days"}),s.jsx("option",{value:14,children:"14 days"}),s.jsx("option",{value:30,children:"30 days"}),s.jsx("option",{value:60,children:"60 days"}),s.jsx("option",{value:90,children:"90 days"})]})]})]}),c&&s.jsx("div",{style:{padding:"2rem",color:"#888"},children:"Loading..."}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:gs.statsBar,children:[s.jsxs("span",{children:[d.recipes.length," recipes affected"]}),s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{children:[f," dishes"]}),s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{children:[p," components"]}),s.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:"0.25rem"},children:["all","dish","component"].map(g=>s.jsx("button",{onClick:()=>l(g),style:{...gs.filterBtn,...a===g?gs.filterBtnActive:{}},children:g==="all"?"All":g==="dish"?"Dishes":"Recipes"},g))})]}),u.length===0?s.jsxs("div",{style:{padding:"2rem",textAlign:"center",color:"#888"},children:["No recipes affected by ingredient price changes in the last ",t," days."]}):s.jsxs("table",{style:gs.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gs.th,children:"Recipe"}),s.jsx("th",{style:gs.th,children:"Type"}),s.jsx("th",{style:{...gs.th,textAlign:"right"},children:"Previous Cost"}),s.jsx("th",{style:{...gs.th,textAlign:"right"},children:"Current Cost"}),s.jsx("th",{style:{...gs.th,textAlign:"right"},children:"Change"}),s.jsx("th",{style:{...gs.th,textAlign:"center"},children:"Details"})]})}),s.jsx("tbody",{children:u.map(g=>s.jsxs(s.Fragment,{children:[s.jsxs("tr",{style:gs.tr,children:[s.jsx("td",{style:{...gs.td,fontWeight:500},children:s.jsx("span",{style:{cursor:"pointer",color:"#e94560"},onClick:()=>e(g.recipe_type==="dish"?`/dishes/${g.recipe_id}`:`/recipes/${g.recipe_id}`),children:g.recipe_name})}),s.jsx("td",{style:gs.td,children:s.jsx("span",{style:{background:g.recipe_type==="dish"?"#e94560":"#3b82f6",color:"white",padding:"1px 6px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:g.recipe_type.toUpperCase()})}),s.jsx("td",{style:{...gs.td,textAlign:"right",fontFamily:"monospace"},children:g.previous_cost_per_unit!=null?`£${g.previous_cost_per_unit.toFixed(4)}/${g.output_unit}`:"-"}),s.jsx("td",{style:{...gs.td,textAlign:"right",fontFamily:"monospace"},children:g.current_cost_per_unit!=null?`£${g.current_cost_per_unit.toFixed(4)}/${g.output_unit}`:"-"}),s.jsx("td",{style:{...gs.td,textAlign:"right",fontFamily:"monospace",fontWeight:600,color:g.cost_change!=null?g.cost_change>0?"#dc3545":g.cost_change<0?"#22c55e":"#888":"#888"},children:g.cost_change!=null?s.jsxs(s.Fragment,{children:[g.cost_change>0?"+":"",`£${g.cost_change.toFixed(4)}`,g.cost_change_pct!=null&&s.jsxs("span",{style:{fontSize:"0.75rem",marginLeft:"4px"},children:["(",g.cost_change_pct>0?"+":"",g.cost_change_pct,"%)"]})]}):"-"}),s.jsx("td",{style:{...gs.td,textAlign:"center"},children:s.jsxs("button",{onClick:()=>o(i===g.recipe_id?null:g.recipe_id),style:gs.detailBtn,children:[g.ingredient_changes.length," change",g.ingredient_changes.length!==1?"s":"",i===g.recipe_id?" ▴":" ▾"]})})]},g.recipe_id),i===g.recipe_id&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,style:{padding:"0 0.75rem 0.75rem 2rem",background:"#fafafa"},children:s.jsx("div",{style:{fontSize:"0.8rem",color:"#555"},children:g.ingredient_changes.map((m,y)=>s.jsxs("div",{style:{padding:"3px 0",borderBottom:ye(`/invoice/${m.source_invoice_id}`),children:m.source_invoice_number||`#${m.source_invoice_id}`}),m.ingredient_name&&m.old_price!=null&&m.new_price!=null?s.jsxs(s.Fragment,{children:[m.ingredient_name," price changed: ",ZP(m.old_price,m.unit)," → ",ZP(m.new_price,m.unit)]}):m.ingredient_name&&m.new_price!=null&&m.old_price==null?s.jsxs(s.Fragment,{children:[m.ingredient_name," price set: ",ZP(m.new_price,m.unit)]}):m.summary]}),m.cost_impact!=null&&s.jsxs("span",{style:{fontFamily:"monospace",fontWeight:600,fontSize:"0.75rem",color:m.cost_impact>0?"#dc3545":m.cost_impact<0?"#22c55e":"#888",marginLeft:"1rem",whiteSpace:"nowrap"},children:[m.cost_impact>0?"+":"",`£${m.cost_impact.toFixed(4)}`,"/",g.output_unit]})]},y))})})},`${g.recipe_id}-detail`)]}))})]})]})]})}const gs={page:{padding:"1.5rem",maxWidth:"1100px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},select:{padding:"0.4rem 0.6rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.85rem"},statsBar:{display:"flex",gap:"0.75rem",alignItems:"center",padding:"0.5rem 0",marginBottom:"0.5rem",fontSize:"0.85rem",color:"#555"},filterBtn:{padding:"3px 10px",border:"1px solid #ddd",borderRadius:"4px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.75rem",color:"#555"},filterBtnActive:{background:"#e94560",color:"white",borderColor:"#e94560"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},detailBtn:{padding:"2px 8px",border:"1px solid #ddd",borderRadius:"4px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.75rem",color:"#555"}};function ape(){return s.jsx(iJ,{children:s.jsxs(iZ,{children:[s.jsx(Zn,{path:"/upload-app",element:s.jsx(Mce,{})}),s.jsxs(Zn,{element:s.jsx(FJ,{}),children:[s.jsx(Zn,{path:"/",element:s.jsx(Gz,{to:"/dashboard",replace:!0})}),s.jsx(Zn,{path:"/dashboard",element:s.jsx(Oce,{})}),s.jsx(Zn,{path:"/upload",element:s.jsx(Lce,{})}),s.jsx(Zn,{path:"/invoices",element:s.jsx(Nce,{})}),s.jsx(Zn,{path:"/invoice/:id",element:s.jsx(mfe,{})}),s.jsx(Zn,{path:"/disputes",element:s.jsx(bfe,{})}),s.jsx(Zn,{path:"/search/invoices",element:s.jsx(Ufe,{})}),s.jsx(Zn,{path:"/search/line-items",element:s.jsx(qfe,{})}),s.jsx(Zn,{path:"/purchase-orders",element:s.jsx(Vfe,{})}),s.jsx(Zn,{path:"/gp",element:s.jsx(Ffe,{})}),s.jsx(Zn,{path:"/purchases-report",element:s.jsx(Pfe,{})}),s.jsx(Zn,{path:"/purchases",element:s.jsx(jfe,{})}),s.jsx(Zn,{path:"/purchases/reconcile",element:s.jsx(zfe,{})}),s.jsx(Zn,{path:"/allowances-report",element:s.jsx(Ife,{})}),s.jsx(Zn,{path:"/sales-gp",element:s.jsx(Mfe,{})}),s.jsx(Zn,{path:"/usage-variance",element:s.jsx(Wfe,{})}),s.jsx(Zn,{path:"/logbook",element:s.jsx(Tse,{})}),s.jsx(Zn,{path:"/budget",element:s.jsx(Cfe,{})}),s.jsx(Zn,{path:"/event-orders",element:s.jsx(Qfe,{})}),s.jsx(Zn,{path:"/event-orders/:id",element:s.jsx($fe,{})}),s.jsx(Zn,{path:"/resos",element:s.jsx(zJ,{})}),s.jsx(Zn,{path:"/resos-stats",element:s.jsx(_se,{})}),s.jsx(Zn,{path:"/residents-table-chart",element:s.jsx(OJ,{})}),s.jsx(Zn,{path:"/newbook",element:s.jsx(BJ,{})}),s.jsx(Zn,{path:"/ingredients",element:s.jsx(Gfe,{})}),s.jsx(Zn,{path:"/recipes",element:s.jsx(Kfe,{})}),s.jsx(Zn,{path:"/recipes/:id",element:s.jsx(Yfe,{})}),s.jsx(Zn,{path:"/dishes",element:s.jsx(Zfe,{})}),s.jsx(Zn,{path:"/dishes/:id",element:s.jsx(epe,{})}),s.jsx(Zn,{path:"/menus",element:s.jsx(tpe,{})}),s.jsx(Zn,{path:"/menus/:id",element:s.jsx(ipe,{})}),s.jsx(Zn,{path:"/allergens",element:s.jsx(spe,{})}),s.jsx(Zn,{path:"/price-impact",element:s.jsx(ope,{})}),s.jsx(Zn,{path:"/settings",element:s.jsx(EJ,{})}),s.jsx(Zn,{path:"*",element:s.jsx(Gz,{to:"/dashboard",replace:!0})})]})]})})}const lpe=new VZ({defaultOptions:{queries:{staleTime:5*60*1e3,retry:1}}});JP.createRoot(document.getElementById("root")).render(s.jsx(nF.StrictMode,{children:s.jsx(fZ,{basename:"/kitchen",children:s.jsx(GZ,{client:lpe,children:s.jsx(ape,{})})})}));