kitchen/frontend/dist/assets/index-DiXG3yPo.js
jtricerolph 8d688b459d Initial kitchen scaffold — Phase 1 kitchen port (build-verified 2026-07-11)
FastAPI backend (Python 3.11, MSSQL ODBC for SambaPOS, Azure DI OCR),
kitchen_db on central PG. React/TS/Vite frontend with navy sidebar layout.

Backend: auth.py (APP_SLUG=kitchen, SimpleNamespace — archive routes use
.kitchen_id/.is_admin without modification), main.py (51 migrations, scheduler,
internal router for KDS bookings feed), api/internal.py, full archive API
(31 routers: invoices, recipes, menus, sambapos, resos, newbook, disputes,
purchase_orders, etc.), models, migrations, OCR pipeline.
kitchen_id pinned to 1 (B1 — single hotel).

Frontend: AuthGate (app=kitchen, token shim for archive compat — B5b pending),
Layout (navy sidebar, 6 sections, Lucide icons, teal --app-primary),
App.tsx (Outlet pattern, UploadApp outside Layout), index.css (full :root block).
strict: false — archive components have type issues; build clean.

Note: 45 archive components call fetch('/api/...') without /kitchen/ prefix
(B5b). Runtime 404s; deferred until after initial testing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-12 12:15:39 +00:00

445 lines
2.3 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in n)){const o=Object.getOwnPropertyDescriptor(r,i);o&&Object.defineProperty(n,i,o.get?o:{enumerable:!0,get:()=>r[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<l){for(var d=Array(l),c=0;c<l;c++)d[c]=arguments[c+2];i.children=d}if(n&&n.defaultProps)for(r in l=n.defaultProps,l)i[r]===void 0&&(i[r]=l[r]);return{$$typeof:W_,type:n,key:o,ref:a,props:i,_owner:_M.current}}function QX(n,e){return{$$typeof:W_,type:n.type,key:e,ref:n.ref,props:n.props,_owner:n._owner}}function CM(n){return typeof n=="object"&&n!==null&&n.$$typeof===W_}function $X(n){var e={"=":"=0",":":"=2"};return"$"+n.replace(/[=:]/g,function(t){return e[t]})}var R8=/\/+/g;function PE(n,e){return typeof n=="object"&&n!==null&&n.key!=null?$X(""+n.key):e.toString(36)}function e5(n,e,t,r,i){var o=typeof n;(o==="undefined"||o==="boolean")&&(n=null);var a=!1;if(n===null)a=!0;else switch(o){case"string":case"number":a=!0;break;case"object":switch(n.$$typeof){case W_:case LX:a=!0}}if(a)return a=n,i=i(a),n=r===""?"."+PE(a,0):r,P8(i)?(t="",n!=null&&(t=n.replace(R8,"$&/")+"/"),e5(i,e,t,"",function(c){return c})):i!=null&&(CM(i)&&(i=QX(i,t+(!i.key||a&&a.key===i.key?"":(""+i.key).replace(R8,"$&/")+"/")+n)),e.push(i)),1;if(a=0,r=r===""?".":r+":",P8(n))for(var l=0;l<n.length;l++){o=n[l];var d=r+PE(o,l);a+=e5(o,e,t,d,i)}else if(d=YX(n),typeof d=="function")for(n=d.call(n),l=0;!(o=n.next()).done;)o=o.value,d=r+PE(o,l++),a+=e5(o,e,t,d,i);else if(o==="object")throw e=String(n),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(n).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return a}function QC(n,e,t){if(n==null)return n;var r=[],i=0;return e5(n,r,"","",function(o){return e.call(t,o,i++)}),r}function ZX(n){if(n._status===-1){var e=n._result;e=e(),e.then(function(t){(n._status===0||n._status===-1)&&(n._status=1,n._result=t)},function(t){(n._status===0||n._status===-1)&&(n._status=2,n._result=t)}),n._status===-1&&(n._status=0,n._result=e)}if(n._status===1)return n._result.default;throw n._result}var Fa={current:null},t5={transition:null},JX={ReactCurrentDispatcher:Fa,ReactCurrentBatchConfig:t5,ReactCurrentOwner:_M};function y7(){throw Error("act(...) is not supported in production builds of React.")}nr.Children={map:QC,forEach:function(n,e,t){QC(n,function(){e.apply(this,arguments)},t)},count:function(n){var e=0;return QC(n,function(){e++}),e},toArray:function(n){return QC(n,function(e){return e})||[]},only:function(n){if(!CM(n))throw Error("React.Children.only expected to receive a single React element child.");return n}};nr.Component=c1;nr.Fragment=NX;nr.Profiler=UX;nr.PureComponent=jM;nr.StrictMode=WX;nr.Suspense=GX;nr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=JX;nr.act=y7;nr.cloneElement=function(n,e,t){if(n==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+n+".");var r=u7({},n.props),i=n.key,o=n.ref,a=n._owner;if(e!=null){if(e.ref!==void 0&&(o=e.ref,a=_M.current),e.key!==void 0&&(i=""+e.key),n.type&&n.type.defaultProps)var l=n.type.defaultProps;for(d in e)p7.call(e,d)&&!g7.hasOwnProperty(d)&&(r[d]=e[d]===void 0&&l!==void 0?l[d]:e[d])}var d=arguments.length-2;if(d===1)r.children=t;else if(1<d){l=Array(d);for(var c=0;c<d;c++)l[c]=arguments[c+2];r.children=l}return{$$typeof:W_,type:n.type,key:i,ref:o,props:r,_owner:a}};nr.createContext=function(n){return n={$$typeof:qX,_currentValue:n,_currentValue2:n,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},n.Provider={$$typeof:HX,_context:n},n.Consumer=n};nr.createElement=m7;nr.createFactory=function(n){var e=m7.bind(null,n);return e.type=n,e};nr.createRef=function(){return{current:null}};nr.forwardRef=function(n){return{$$typeof:VX,render:n}};nr.isValidElement=CM;nr.lazy=function(n){return{$$typeof:XX,_payload:{_status:-1,_result:n},_init:ZX}};nr.memo=function(n,e){return{$$typeof:KX,type:n,compare:e===void 0?null:e}};nr.startTransition=function(n){var e=t5.transition;t5.transition={};try{n()}finally{t5.transition=e}};nr.unstable_act=y7;nr.useCallback=function(n,e){return Fa.current.useCallback(n,e)};nr.useContext=function(n){return Fa.current.useContext(n)};nr.useDebugValue=function(){};nr.useDeferredValue=function(n){return Fa.current.useDeferredValue(n)};nr.useEffect=function(n,e){return Fa.current.useEffect(n,e)};nr.useId=function(){return Fa.current.useId()};nr.useImperativeHandle=function(n,e,t){return Fa.current.useImperativeHandle(n,e,t)};nr.useInsertionEffect=function(n,e){return Fa.current.useInsertionEffect(n,e)};nr.useLayoutEffect=function(n,e){return Fa.current.useLayoutEffect(n,e)};nr.useMemo=function(n,e){return Fa.current.useMemo(n,e)};nr.useReducer=function(n,e,t){return Fa.current.useReducer(n,e,t)};nr.useRef=function(n){return Fa.current.useRef(n)};nr.useState=function(n){return Fa.current.useState(n)};nr.useSyncExternalStore=function(n,e,t){return Fa.current.useSyncExternalStore(n,e,t)};nr.useTransition=function(){return Fa.current.useTransition()};nr.version="18.3.1";d7.exports=nr;var k=d7.exports;const nF=a7(k),eY=OX({__proto__:null,default:nF},[k]);/**
* @license React
* react-jsx-runtime.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 tY=k,nY=Symbol.for("react.element"),rY=Symbol.for("react.fragment"),iY=Object.prototype.hasOwnProperty,sY=tY.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,oY={key:!0,ref:!0,__self:!0,__source:!0};function x7(n,e,t){var r,i={},o=null,a=null;t!==void 0&&(o=""+t),e.key!==void 0&&(o=""+e.key),e.ref!==void 0&&(a=e.ref);for(r in e)iY.call(e,r)&&!oY.hasOwnProperty(r)&&(i[r]=e[r]);if(n&&n.defaultProps)for(r in e=n.defaultProps,e)i[r]===void 0&&(i[r]=e[r]);return{$$typeof:nY,type:n,key:o,ref:a,props:i,_owner:sY.current}}tF.Fragment=rY;tF.jsx=x7;tF.jsxs=x7;l7.exports=tF;var s=l7.exports,JP={},b7={exports:{}},Ql={},v7={exports:{}},w7={};/**
* @license React
* scheduler.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.
*/(function(n){function e(H,z){var G=H.length;H.push(z);e:for(;0<G;){var te=G-1>>>1,re=H[te];if(0<i(re,z))H[te]=z,H[G]=re,G=te;else break e}}function t(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var z=H[0],G=H.pop();if(G!==z){H[0]=G;e:for(var te=0,re=H.length,me=re>>>1;te<me;){var J=2*(te+1)-1,ne=H[J],ye=J+1,ke=H[ye];if(0>i(ne,G))ye<re&&0>i(ke,ne)?(H[te]=ke,H[ye]=G,te=ye):(H[te]=ne,H[J]=G,te=J);else if(ye<re&&0>i(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()-D<A)}function L(){if(T!==null){var H=n.unstable_now();D=H;var z=!0;try{z=T(!0,H)}finally{z?W():(C=!1,T=null)}}else C=!1}var W;if(typeof w=="function")W=function(){w(L)};else if(typeof MessageChannel<"u"){var O=new MessageChannel,U=O.port2;O.port1.onmessage=L,W=function(){U.postMessage(null)}}else W=function(){v(L,0)};function M(H){T=H,C||(C=!0,W())}function I(H,z){F=v(function(){H(n.unstable_now())},z)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(H){H.callback=null},n.unstable_continueExecution=function(){m||g||(m=!0,M(b))},n.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):A=0<H?Math.floor(1e3/H):5},n.unstable_getCurrentPriorityLevel=function(){return p},n.unstable_getFirstCallbackNode=function(){return t(d)},n.unstable_next=function(H){switch(p){case 1:case 2:case 3:var z=3;break;default:z=p}var G=p;p=z;try{return H()}finally{p=G}},n.unstable_pauseExecution=function(){},n.unstable_requestPaint=function(){},n.unstable_runWithPriority=function(H,z){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var G=p;p=H;try{return z()}finally{p=G}},n.unstable_scheduleCallback=function(H,z,G){var te=n.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?te+G:te):G=te,H){case 1:var re=-1;break;case 2:re=250;break;case 5:re=1073741823;break;case 4:re=1e4;break;default:re=5e3}return re=G+re,H={id:u++,callback:z,priorityLevel:H,startTime:G,expirationTime:re,sortIndex:-1},G>te?(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<arguments.length;t++)e+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+n+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var S7=new Set,aj={};function F0(n,e){Yv(n,e),Yv(n+"Capture",e)}function Yv(n,e){for(aj[n]=e,n=0;n<e.length;n++)S7.add(e[n])}var Sf=!(typeof window>"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||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(hY(e,t,i,r)&&(t=null),r||i===null?cY(e)&&(t===null?n.removeAttribute(e):n.setAttribute(e,""+t)):i.mustUseProperty?n[i.propertyName]=t===null?i.type===3?!1:"":t:(e=i.attributeName,r=i.attributeNamespace,t===null?n.removeAttribute(e):(i=i.type,t=i===3||i===4&&t===!0?"":""+t,r?n.setAttributeNS(r,e,t):n.setAttribute(e,t))))}var Ef=lY.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,$C=Symbol.for("react.element"),Px=Symbol.for("react.portal"),Rx=Symbol.for("react.fragment"),DM=Symbol.for("react.strict_mode"),tR=Symbol.for("react.profiler"),j7=Symbol.for("react.provider"),k7=Symbol.for("react.context"),EM=Symbol.for("react.forward_ref"),nR=Symbol.for("react.suspense"),rR=Symbol.for("react.suspense_list"),PM=Symbol.for("react.memo"),ep=Symbol.for("react.lazy"),_7=Symbol.for("react.offscreen"),M8=Symbol.iterator;function vw(n){return n===null||typeof n!="object"?null:(n=M8&&n[M8]||n["@@iterator"],typeof n=="function"?n:null)}var ns=Object.assign,RE;function Xw(n){if(RE===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);RE=e&&e[1]||""}return`
`+RE+n}var BE=!1;function IE(n,e){if(!n||BE)return"";BE=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var r=c}Reflect.construct(n,[],e)}else{try{e.call()}catch(c){r=c}n.call(e.prototype)}else{try{throw Error()}catch(c){r=c}n()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var i=c.stack.split(`
`),o=r.stack.split(`
`),a=i.length-1,l=o.length-1;1<=a&&0<=l&&i[a]!==o[l];)l--;for(;1<=a&&0<=l;a--,l--)if(i[a]!==o[l]){if(a!==1||l!==1)do if(a--,l--,0>l||i[a]!==o[l]){var d=`
`+i[a].replace(" at new "," at ");return n.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",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<t.length;i++)e["$"+t[i]]=!0;for(t=0;t<n.length;t++)i=e.hasOwnProperty("$"+n[t].value),n[t].selected!==i&&(n[t].selected=i),i&&r&&(n[t].defaultSelected=!0)}else{for(t=""+Bg(t),e=null,i=0;i<n.length;i++){if(n[i].value===t){n[i].selected=!0,r&&(n[i].defaultSelected=!0);return}e!==null||n[i].disabled||(e=n[i])}e!==null&&(e.selected=!0)}}function lR(n,e){if(e.dangerouslySetInnerHTML!=null)throw Error(ft(91));return ns({},e,{value:void 0,defaultValue:void 0,children:""+n._wrapperState.initialValue})}function L8(n,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(ft(92));if(Yw(t)){if(1<t.length)throw Error(ft(93));t=t[0]}e=t}e==null&&(e=""),t=e}n._wrapperState={initialValue:Bg(t)}}function F7(n,e){var t=Bg(e.value),r=Bg(e.defaultValue);t!=null&&(t=""+t,t!==n.value&&(n.value=t),e.defaultValue==null&&n.defaultValue!==t&&(n.defaultValue=t)),r!=null&&(n.defaultValue=""+r)}function N8(n){var e=n.textContent;e===n._wrapperState.initialValue&&e!==""&&e!==null&&(n.value=e)}function D7(n){switch(n){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function dR(n,e){return n==null||n==="http://www.w3.org/1999/xhtml"?D7(e):n==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":n}var JC,E7=function(n){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,t,r,i){MSApp.execUnsafeLocalFunction(function(){return n(e,t,r,i)})}:n}(function(n,e){if(n.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in n)n.innerHTML=e;else{for(JC=JC||document.createElement("div"),JC.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",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<e.length;n++)W8(e[n])}}function M7(n,e){return n(e)}function z7(){}var ME=!1;function O7(n,e,t){if(ME)return n(e,t);ME=!0;try{return M7(n,e,t)}finally{ME=!1,(Jx!==null||eb!==null)&&(z7(),I7())}}function dj(n,e){var t=n.stateNode;if(t===null)return null;var r=aF(t);if(r===null)return null;t=r[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(n=n.type,r=!(n==="button"||n==="input"||n==="select"||n==="textarea")),n=!r;break e;default:n=!1}if(n)return null;if(t&&typeof t!="function")throw Error(ft(231,e,typeof t));return t}var pR=!1;if(Sf)try{var ww={};Object.defineProperty(ww,"passive",{get:function(){pR=!0}}),window.addEventListener("test",ww,ww),window.removeEventListener("test",ww,ww)}catch{pR=!1}function xY(n,e,t,r,i,o,a,l,d){var c=Array.prototype.slice.call(arguments,3);try{e.apply(t,c)}catch(u){this.onError(u)}}var BS=!1,mA=null,yA=!1,gR=null,bY={onError:function(n){BS=!0,mA=n}};function vY(n,e,t,r,i,o,a,l,d){BS=!1,mA=null,xY.apply(bY,arguments)}function wY(n,e,t,r,i,o,a,l,d){if(vY.apply(this,arguments),BS){if(BS){var c=mA;BS=!1,mA=null}else throw Error(ft(198));yA||(yA=!0,gR=c)}}function D0(n){var e=n,t=n;if(n.alternate)for(;e.return;)e=e.return;else{n=e;do e=n,e.flags&4098&&(t=e.return),n=e.return;while(n)}return e.tag===3?t:null}function L7(n){if(n.tag===13){var e=n.memoizedState;if(e===null&&(n=n.alternate,n!==null&&(e=n.memoizedState)),e!==null)return e.dehydrated}return null}function U8(n){if(D0(n)!==n)throw Error(ft(188))}function SY(n){var e=n.alternate;if(!e){if(e=D0(n),e===null)throw Error(ft(188));return e!==n?null:n}for(var t=n,r=e;;){var i=t.return;if(i===null)break;var o=i.alternate;if(o===null){if(r=i.return,r!==null){t=r;continue}break}if(i.child===o.child){for(o=i.child;o;){if(o===t)return U8(i),n;if(o===r)return U8(i),e;o=o.sibling}throw Error(ft(188))}if(t.return!==r.return)t=i,r=o;else{for(var a=!1,l=i.child;l;){if(l===t){a=!0,t=i,r=o;break}if(l===r){a=!0,r=i,t=o;break}l=l.sibling}if(!a){for(l=o.child;l;){if(l===t){a=!0,t=o,r=i;break}if(l===r){a=!0,r=o,t=i;break}l=l.sibling}if(!a)throw Error(ft(189))}}if(t.alternate!==r)throw Error(ft(190))}if(t.tag!==3)throw Error(ft(188));return t.stateNode.current===t?n:e}function N7(n){return n=SY(n),n!==null?W7(n):null}function W7(n){if(n.tag===5||n.tag===6)return n;for(n=n.child;n!==null;){var e=W7(n);if(e!==null)return e;n=n.sibling}return null}var U7=Xl.unstable_scheduleCallback,H8=Xl.unstable_cancelCallback,jY=Xl.unstable_shouldYield,kY=Xl.unstable_requestPaint,ws=Xl.unstable_now,_Y=Xl.unstable_getCurrentPriorityLevel,BM=Xl.unstable_ImmediatePriority,H7=Xl.unstable_UserBlockingPriority,xA=Xl.unstable_NormalPriority,CY=Xl.unstable_LowPriority,q7=Xl.unstable_IdlePriority,rF=null,Iu=null;function AY(n){if(Iu&&typeof Iu.onCommitFiberRoot=="function")try{Iu.onCommitFiberRoot(rF,n,void 0,(n.current.flags&128)===128)}catch{}}var Tc=Math.clz32?Math.clz32:DY,TY=Math.log,FY=Math.LN2;function DY(n){return 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;0<e;)t=31-Tc(e),i=1<<t,r|=n[t],e&=~i;return r}function EY(n,e){switch(n){case 1:case 2:case 4:return e+250;case 8:case 16:case 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 e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function PY(n,e){for(var t=n.suspendedLanes,r=n.pingedLanes,i=n.expirationTimes,o=n.pendingLanes;0<o;){var a=31-Tc(o),l=1<<a,d=i[a];d===-1?(!(l&t)||l&r)&&(i[a]=EY(l,e)):d<=e&&(n.expiredLanes|=l),o&=~l}}function mR(n){return n=n.pendingLanes&-1073741825,n!==0?n:n&1073741824?1073741824:0}function V7(){var n=e2;return e2<<=1,!(e2&4194240)&&(e2=64),n}function zE(n){for(var e=[],t=0;31>t;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<t;){var i=31-Tc(t),o=1<<i;e[i]=0,r[i]=-1,n[i]=-1,t&=~o}}function IM(n,e){var t=n.entangledLanes|=e;for(n=n.entanglements;t;){var r=31-Tc(t),i=1<<r;i&e|n[r]&e&&(n[r]|=e),t&=~i}}var $r=0;function G7(n){return n&=-n,1<n?4<n?n&268435455?16:536870912:4:1}var K7,MM,X7,Y7,Q7,yR=!1,n2=[],xg=null,bg=null,vg=null,cj=new Map,uj=new Map,rp=[],BY="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function q8(n,e){switch(n){case"focusin":case"focusout":xg=null;break;case"dragenter":case"dragleave":bg=null;break;case"mouseover":case"mouseout":vg=null;break;case"pointerover":case"pointerout":cj.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":uj.delete(e.pointerId)}}function Sw(n,e,t,r,i,o){return n===null||n.nativeEvent!==o?(n={blockedOn:e,domEventName:t,eventSystemFlags:r,nativeEvent:o,targetContainers:[i]},e!==null&&(e=q_(e),e!==null&&MM(e)),n):(n.eventSystemFlags|=r,e=n.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),n)}function IY(n,e,t,r,i){switch(e){case"focusin":return xg=Sw(xg,n,e,t,r,i),!0;case"dragenter":return bg=Sw(bg,n,e,t,r,i),!0;case"mouseover":return vg=Sw(vg,n,e,t,r,i),!0;case"pointerover":var o=i.pointerId;return cj.set(o,Sw(cj.get(o)||null,n,e,t,r,i)),!0;case"gotpointercapture":return o=i.pointerId,uj.set(o,Sw(uj.get(o)||null,n,e,t,r,i)),!0}return!1}function $7(n){var e=gm(n.target);if(e!==null){var t=D0(e);if(t!==null){if(e=t.tag,e===13){if(e=L7(t),e!==null){n.blockedOn=e,Q7(n.priority,function(){X7(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){n.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}n.blockedOn=null}function n5(n){if(n.blockedOn!==null)return!1;for(var e=n.targetContainers;0<e.length;){var t=xR(n.domEventName,n.eventSystemFlags,e[0],n.nativeEvent);if(t===null){t=n.nativeEvent;var r=new t.constructor(t.type,t);hR=r,t.target.dispatchEvent(r),hR=null}else return e=q_(t),e!==null&&MM(e),n.blockedOn=t,!1;e.shift()}return!0}function V8(n,e,t){n5(n)&&t.delete(e)}function MY(){yR=!1,xg!==null&&n5(xg)&&(xg=null),bg!==null&&n5(bg)&&(bg=null),vg!==null&&n5(vg)&&(vg=null),cj.forEach(V8),uj.forEach(V8)}function jw(n,e){n.blockedOn===e&&(n.blockedOn=null,yR||(yR=!0,Xl.unstable_scheduleCallback(Xl.unstable_NormalPriority,MY)))}function hj(n){function e(i){return jw(i,n)}if(0<n2.length){jw(n2[0],n);for(var t=1;t<n2.length;t++){var r=n2[t];r.blockedOn===n&&(r.blockedOn=null)}}for(xg!==null&&jw(xg,n),bg!==null&&jw(bg,n),vg!==null&&jw(vg,n),cj.forEach(e),uj.forEach(e),t=0;t<rp.length;t++)r=rp[t],r.blockedOn===n&&(r.blockedOn=null);for(;0<rp.length&&(t=rp[0],t.blockedOn===null);)$7(t),t.blockedOn===null&&rp.shift()}var tb=Ef.ReactCurrentBatchConfig,vA=!0;function zY(n,e,t,r){var i=$r,o=tb.transition;tb.transition=null;try{$r=1,zM(n,e,t,r)}finally{$r=i,tb.transition=o}}function OY(n,e,t,r){var i=$r,o=tb.transition;tb.transition=null;try{$r=4,zM(n,e,t,r)}finally{$r=i,tb.transition=o}}function zM(n,e,t,r){if(vA){var i=xR(n,e,t,r);if(i===null)KE(n,e,r,wA,t),q8(n,r);else if(IY(i,n,e,t,r))r.stopPropagation();else if(q8(n,r),e&4&&-1<BY.indexOf(n)){for(;i!==null;){var o=q_(i);if(o!==null&&K7(o),o=xR(n,e,t,r),o===null&&KE(n,e,r,wA,t),o===i)break;i=o}i!==null&&r.stopPropagation()}else KE(n,e,r,null,t)}}var wA=null;function xR(n,e,t,r){if(wA=null,n=RM(r),n=gm(n),n!==null)if(e=D0(n),e===null)n=null;else if(t=e.tag,t===13){if(n=L7(e),n!==null)return n;n=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;n=null}else e!==n&&(n=null);return wA=n,null}function Z7(n){switch(n){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(_Y()){case BM:return 1;case H7:return 4;case xA:case CY:return 16;case q7:return 536870912;default:return 16}default:return 16}}var dg=null,OM=null,r5=null;function J7(){if(r5)return r5;var n,e=OM,t=e.length,r,i="value"in dg?dg.value:dg.textContent,o=i.length;for(n=0;n<t&&e[n]===i[n];n++);var a=t-n;for(r=1;r<=a&&e[t-r]===i[o-r];r++);return r5=i.slice(n,1<r?1-r:void 0)}function i5(n){var e=n.keyCode;return"charCode"in n?(n=n.charCode,n===0&&e===13&&(n=13)):n=e,n===10&&(n=13),32<=n||n===13?n:0}function r2(){return!0}function G8(){return!1}function $l(n){function e(t,r,i,o,a){this._reactName=t,this._targetInst=i,this.type=r,this.nativeEvent=o,this.target=a,this.currentTarget=null;for(var l in n)n.hasOwnProperty(l)&&(t=n[l],this[l]=t?t(o):o[l]);return this.isDefaultPrevented=(o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===!1)?r2:G8,this.isPropagationStopped=G8,this}return ns(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=r2)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=r2)},persist:function(){},isPersistent:r2}),e}var u1={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(n){return n.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},LM=$l(u1),H_=ns({},u1,{view:0,detail:0}),LY=$l(H_),OE,LE,kw,iF=ns({},H_,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:NM,button:0,buttons:0,relatedTarget:function(n){return n.relatedTarget===void 0?n.fromElement===n.srcElement?n.toElement:n.fromElement:n.relatedTarget},movementX:function(n){return"movementX"in n?n.movementX:(n!==kw&&(kw&&n.type==="mousemove"?(OE=n.screenX-kw.screenX,LE=n.screenY-kw.screenY):LE=OE=0,kw=n),OE)},movementY:function(n){return"movementY"in n?n.movementY:LE}}),K8=$l(iF),NY=ns({},iF,{dataTransfer:0}),WY=$l(NY),UY=ns({},H_,{relatedTarget:0}),NE=$l(UY),HY=ns({},u1,{animationName:0,elapsedTime:0,pseudoElement:0}),qY=$l(HY),VY=ns({},u1,{clipboardData:function(n){return"clipboardData"in n?n.clipboardData:window.clipboardData}}),GY=$l(VY),KY=ns({},u1,{data:0}),X8=$l(KY),XY={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},YY={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},QY={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function $Y(n){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(n):(n=QY[n])?!!e[n]:!1}function NM(){return $Y}var ZY=ns({},H_,{key:function(n){if(n.key){var e=XY[n.key]||n.key;if(e!=="Unidentified")return e}return n.type==="keypress"?(n=i5(n),n===13?"Enter":String.fromCharCode(n)):n.type==="keydown"||n.type==="keyup"?YY[n.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:NM,charCode:function(n){return n.type==="keypress"?i5(n):0},keyCode:function(n){return n.type==="keydown"||n.type==="keyup"?n.keyCode:0},which:function(n){return n.type==="keypress"?i5(n):n.type==="keydown"||n.type==="keyup"?n.keyCode:0}}),JY=$l(ZY),eQ=ns({},iF,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Y8=$l(eQ),tQ=ns({},H_,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:NM}),nQ=$l(tQ),rQ=ns({},u1,{propertyName:0,elapsedTime:0,pseudoElement:0}),iQ=$l(rQ),sQ=ns({},iF,{deltaX:function(n){return"deltaX"in n?n.deltaX:"wheelDeltaX"in n?-n.wheelDeltaX:0},deltaY:function(n){return"deltaY"in n?n.deltaY:"wheelDeltaY"in n?-n.wheelDeltaY:"wheelDelta"in n?-n.wheelDelta:0},deltaZ:0,deltaMode:0}),oQ=$l(sQ),aQ=[9,13,27,32],WM=Sf&&"CompositionEvent"in window,IS=null;Sf&&"documentMode"in document&&(IS=document.documentMode);var lQ=Sf&&"TextEvent"in window&&!IS,eW=Sf&&(!WM||IS&&8<IS&&11>=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.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return eW&&e.locale!=="ko"?null:e.data;default:return null}}var uQ={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Z8(n){var e=n&&n.nodeName&&n.nodeName.toLowerCase();return e==="input"?!!uQ[n.type]:e==="textarea"}function rW(n,e,t,r){B7(r),e=SA(e,"onChange"),0<e.length&&(t=new LM("onChange","change",null,t,r),n.push({event:t,listeners:e}))}var MS=null,fj=null;function hQ(n){pW(n,0)}function sF(n){var e=zx(n);if(A7(e))return n}function fQ(n,e){if(n==="change")return e}var iW=!1;if(Sf){var WE;if(Sf){var UE="oninput"in document;if(!UE){var J8=document.createElement("div");J8.setAttribute("oninput","return;"),UE=typeof J8.oninput=="function"}WE=UE}else WE=!1;iW=WE&&(!document.documentMode||9<document.documentMode)}function ez(){MS&&(MS.detachEvent("onpropertychange",sW),fj=MS=null)}function sW(n){if(n.propertyName==="value"&&sF(fj)){var e=[];rW(e,fj,n,RM(n)),O7(hQ,e)}}function pQ(n,e,t){n==="focusin"?(ez(),MS=e,fj=t,MS.attachEvent("onpropertychange",sW)):n==="focusout"&&ez()}function gQ(n){if(n==="selectionchange"||n==="keyup"||n==="keydown")return sF(fj)}function mQ(n,e){if(n==="click")return sF(e)}function yQ(n,e){if(n==="input"||n==="change")return sF(e)}function xQ(n,e){return n===e&&(n!==0||1/n===1/e)||n!==n&&e!==e}var Ec=typeof Object.is=="function"?Object.is:xQ;function pj(n,e){if(Ec(n,e))return!0;if(typeof n!="object"||n===null||typeof e!="object"||e===null)return!1;var t=Object.keys(n),r=Object.keys(e);if(t.length!==r.length)return!1;for(r=0;r<t.length;r++){var i=t[r];if(!eR.call(e,i)||!Ec(n[i],e[i]))return!1}return!0}function tz(n){for(;n&&n.firstChild;)n=n.firstChild;return n}function nz(n,e){var t=tz(n);n=0;for(var r;t;){if(t.nodeType===3){if(r=n+t.textContent.length,n<=e&&r>=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<e.length;t++)n=e[t],n.element.scrollLeft=n.left,n.element.scrollTop=n.top}}var vQ=Sf&&"documentMode"in document&&11>=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"),0<r.length&&(e=new LM("onSelect","select",null,e,t),n.push({event:e,listeners:r}),e.target=Ix)))}function i2(n,e){var t={};return t[n.toLowerCase()]=e.toLowerCase(),t["Webkit"+n]="webkit"+e,t["Moz"+n]="moz"+e,t}var Mx={animationend:i2("Animation","AnimationEnd"),animationiteration:i2("Animation","AnimationIteration"),animationstart:i2("Animation","AnimationStart"),transitionend:i2("Transition","TransitionEnd")},HE={},lW={};Sf&&(lW=document.createElement("div").style,"AnimationEvent"in window||(delete Mx.animationend.animation,delete Mx.animationiteration.animation,delete Mx.animationstart.animation),"TransitionEvent"in window||delete Mx.transitionend.transition);function oF(n){if(HE[n])return HE[n];if(!Mx[n])return n;var e=Mx[n],t;for(t in e)if(e.hasOwnProperty(t)&&t in lW)return HE[n]=e[t];return n}var dW=oF("animationend"),cW=oF("animationiteration"),uW=oF("animationstart"),hW=oF("transitionend"),fW=new Map,iz="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Hg(n,e){fW.set(n,e),F0(e,[n])}for(var qE=0;qE<iz.length;qE++){var VE=iz[qE],wQ=VE.toLowerCase(),SQ=VE[0].toUpperCase()+VE.slice(1);Hg(wQ,"on"+SQ)}Hg(dW,"onAnimationEnd");Hg(cW,"onAnimationIteration");Hg(uW,"onAnimationStart");Hg("dblclick","onDoubleClick");Hg("focusin","onFocus");Hg("focusout","onBlur");Hg(hW,"onTransitionEnd");Yv("onMouseEnter",["mouseout","mouseover"]);Yv("onMouseLeave",["mouseout","mouseover"]);Yv("onPointerEnter",["pointerout","pointerover"]);Yv("onPointerLeave",["pointerout","pointerover"]);F0("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));F0("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));F0("onBeforeInput",["compositionend","keypress","textInput","paste"]);F0("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));F0("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));F0("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var $w="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),jQ=new Set("cancel close invalid load scroll toggle".split(" ").concat($w));function sz(n,e,t){var r=n.type||"unknown-event";n.currentTarget=t,wY(r,e,void 0,n),n.currentTarget=null}function pW(n,e){e=(e&4)!==0;for(var t=0;t<n.length;t++){var r=n[t],i=r.event;r=r.listeners;e:{var o=void 0;if(e)for(var a=r.length-1;0<=a;a--){var l=r[a],d=l.instance,c=l.currentTarget;if(l=l.listener,d!==o&&i.isPropagationStopped())break e;sz(i,l,c),o=d}else for(a=0;a<r.length;a++){if(l=r[a],d=l.instance,c=l.currentTarget,l=l.listener,d!==o&&i.isPropagationStopped())break e;sz(i,l,c),o=d}}}if(yA)throw n=gR,yA=!1,gR=null,n}function vi(n,e){var t=e[_R];t===void 0&&(t=e[_R]=new Set);var r=n+"__bubble";t.has(r)||(gW(e,n,2,!1),t.add(r))}function GE(n,e,t){var r=0;e&&(r|=4),gW(t,n,r,e)}var s2="_reactListening"+Math.random().toString(36).slice(2);function gj(n){if(!n[s2]){n[s2]=!0,S7.forEach(function(t){t!=="selectionchange"&&(jQ.has(t)||GE(t,!1,n),GE(t,!0,n))});var e=n.nodeType===9?n:n.ownerDocument;e===null||e[s2]||(e[s2]=!0,GE("selectionchange",!1,e))}}function gW(n,e,t,r){switch(Z7(e)){case 1:var i=zY;break;case 4:i=OY;break;default:i=zM}t=i.bind(null,e,t,n),i=void 0,!pR||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),r?i!==void 0?n.addEventListener(e,t,{capture:!0,passive:i}):n.addEventListener(e,t,!0):i!==void 0?n.addEventListener(e,t,{passive:i}):n.addEventListener(e,t,!1)}function KE(n,e,t,r,i){var o=r;if(!(e&1)&&!(e&2)&&r!==null)e:for(;;){if(r===null)return;var a=r.tag;if(a===3||a===4){var l=r.stateNode.containerInfo;if(l===i||l.nodeType===8&&l.parentNode===i)break;if(a===4)for(a=r.return;a!==null;){var d=a.tag;if((d===3||d===4)&&(d=a.stateNode.containerInfo,d===i||d.nodeType===8&&d.parentNode===i))return;a=a.return}for(;l!==null;){if(a=gm(l),a===null)return;if(d=a.tag,d===5||d===6){r=o=a;continue e}l=l.parentNode}}r=r.return}O7(function(){var c=o,u=RM(t),f=[];e:{var p=fW.get(n);if(p!==void 0){var g=LM,m=n;switch(n){case"keypress":if(i5(t)===0)break e;case"keydown":case"keyup":g=JY;break;case"focusin":m="focus",g=NE;break;case"focusout":m="blur",g=NE;break;case"beforeblur":case"afterblur":g=NE;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":g=K8;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":g=WY;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":g=nQ;break;case dW:case cW:case uW:g=qY;break;case hW:g=iQ;break;case"scroll":g=LY;break;case"wheel":g=oQ;break;case"copy":case"cut":case"paste":g=GY;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":g=Y8}var y=(e&4)!==0,v=!y&&n==="scroll",x=y?p!==null?p+"Capture":null:p;y=[];for(var w=c,S;w!==null;){S=w;var _=S.stateNode;if(S.tag===5&&_!==null&&(S=_,x!==null&&(_=dj(w,x),_!=null&&y.push(mj(w,_,S)))),v)break;w=w.return}0<y.length&&(p=new g(p,m,null,t,u),f.push({event:p,listeners:y}))}}if(!(e&7)){e:{if(p=n==="mouseover"||n==="pointerover",g=n==="mouseout"||n==="pointerout",p&&t!==hR&&(m=t.relatedTarget||t.fromElement)&&(gm(m)||m[jf]))break e;if((g||p)&&(p=u.window===u?u:(p=u.ownerDocument)?p.defaultView||p.parentWindow:window,g?(m=t.relatedTarget||t.toElement,g=c,m=m?gm(m):null,m!==null&&(v=D0(m),m!==v||m.tag!==5&&m.tag!==6)&&(m=null)):(g=null,m=c),g!==m)){if(y=K8,_="onMouseLeave",x="onMouseEnter",w="mouse",(n==="pointerout"||n==="pointerover")&&(y=Y8,_="onPointerLeave",x="onPointerEnter",w="pointer"),v=g==null?p:zx(g),S=m==null?p:zx(m),p=new y(_,w+"leave",g,t,u),p.target=v,p.relatedTarget=S,_=null,gm(u)===c&&(y=new y(x,w+"enter",m,t,u),y.target=S,y.relatedTarget=v,_=y),v=_,g&&m)t:{for(y=g,x=m,w=0,S=y;S;S=lx(S))w++;for(S=0,_=x;_;_=lx(_))S++;for(;0<w-S;)y=lx(y),w--;for(;0<S-w;)x=lx(x),S--;for(;w--;){if(y===x||x!==null&&y===x.alternate)break t;y=lx(y),x=lx(x)}y=null}else y=null;g!==null&&oz(f,p,g,y,!1),m!==null&&v!==null&&oz(f,v,m,y,!0)}}e:{if(p=c?zx(c):window,g=p.nodeName&&p.nodeName.toLowerCase(),g==="select"||g==="input"&&p.type==="file")var b=fQ;else if(Z8(p))if(iW)b=yQ;else{b=gQ;var C=pQ}else(g=p.nodeName)&&g.toLowerCase()==="input"&&(p.type==="checkbox"||p.type==="radio")&&(b=mQ);if(b&&(b=b(n,c))){rW(f,b,t,u);break e}C&&C(n,p,c),n==="focusout"&&(C=p._wrapperState)&&C.controlled&&p.type==="number"&&aR(p,"number",p.value)}switch(C=c?zx(c):window,n){case"focusin":(Z8(C)||C.contentEditable==="true")&&(Ix=C,bR=c,zS=null);break;case"focusout":zS=bR=Ix=null;break;case"mousedown":vR=!0;break;case"contextmenu":case"mouseup":case"dragend":vR=!1,rz(f,t,u);break;case"selectionchange":if(vQ)break;case"keydown":case"keyup":rz(f,t,u)}var T;if(WM)e:{switch(n){case"compositionstart":var F="onCompositionStart";break e;case"compositionend":F="onCompositionEnd";break e;case"compositionupdate":F="onCompositionUpdate";break e}F=void 0}else Bx?tW(n,t)&&(F="onCompositionEnd"):n==="keydown"&&t.keyCode===229&&(F="onCompositionStart");F&&(eW&&t.locale!=="ko"&&(Bx||F!=="onCompositionStart"?F==="onCompositionEnd"&&Bx&&(T=J7()):(dg=u,OM="value"in dg?dg.value:dg.textContent,Bx=!0)),C=SA(c,F),0<C.length&&(F=new X8(F,n,null,t,u),f.push({event:F,listeners:C}),T?F.data=T:(T=nW(t),T!==null&&(F.data=T)))),(T=lQ?dQ(n,t):cQ(n,t))&&(c=SA(c,"onBeforeInput"),0<c.length&&(u=new X8("onBeforeInput","beforeinput",null,t,u),f.push({event:u,listeners:c}),u.data=T))}pW(f,e)})}function mj(n,e,t){return{instance:n,listener:e,currentTarget:t}}function SA(n,e){for(var t=e+"Capture",r=[];n!==null;){var i=n,o=i.stateNode;i.tag===5&&o!==null&&(i=o,o=dj(n,t),o!=null&&r.unshift(mj(n,o,i)),o=dj(n,e),o!=null&&r.push(mj(n,o,i))),n=n.return}return r}function lx(n){if(n===null)return null;do n=n.return;while(n&&n.tag!==5);return n||null}function oz(n,e,t,r,i){for(var o=e._reactName,a=[];t!==null&&t!==r;){var l=t,d=l.alternate,c=l.stateNode;if(d!==null&&d===r)break;l.tag===5&&c!==null&&(l=c,i?(d=dj(t,o),d!=null&&a.unshift(mj(t,d,l))):i||(d=dj(t,o),d!=null&&a.push(mj(t,d,l)))),t=t.return}a.length!==0&&n.push({event:e,listeners:a})}var kQ=/\r\n?/g,_Q=/\u0000|\uFFFD/g;function az(n){return(typeof n=="string"?n:""+n).replace(kQ,`
`).replace(_Q,"")}function o2(n,e,t){if(e=az(e),az(n)!==e&&t)throw Error(ft(425))}function jA(){}var wR=null,SR=null;function jR(n,e){return n==="textarea"||n==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var kR=typeof setTimeout=="function"?setTimeout:void 0,CQ=typeof clearTimeout=="function"?clearTimeout:void 0,lz=typeof Promise=="function"?Promise:void 0,AQ=typeof queueMicrotask=="function"?queueMicrotask:typeof lz<"u"?function(n){return lz.resolve(null).then(n).catch(TQ)}:kR;function TQ(n){setTimeout(function(){throw n})}function XE(n,e){var t=e,r=0;do{var i=t.nextSibling;if(n.removeChild(t),i&&i.nodeType===8)if(t=i.data,t==="/$"){if(r===0){n.removeChild(i),hj(e);return}r--}else t!=="$"&&t!=="$?"&&t!=="$!"||r++;t=i}while(t);hj(e)}function wg(n){for(;n!=null;n=n.nextSibling){var e=n.nodeType;if(e===1||e===3)break;if(e===8){if(e=n.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return n}function dz(n){n=n.previousSibling;for(var e=0;n;){if(n.nodeType===8){var t=n.data;if(t==="$"||t==="$!"||t==="$?"){if(e===0)return n;e--}else t==="/$"&&e++}n=n.previousSibling}return null}var h1=Math.random().toString(36).slice(2),Du="__reactFiber$"+h1,yj="__reactProps$"+h1,jf="__reactContainer$"+h1,_R="__reactEvents$"+h1,FQ="__reactListeners$"+h1,DQ="__reactHandles$"+h1;function gm(n){var e=n[Du];if(e)return e;for(var t=n.parentNode;t;){if(e=t[jf]||t[Du]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(n=dz(n);n!==null;){if(t=n[Du])return t;n=dz(n)}return e}n=t,t=n.parentNode}return null}function q_(n){return n=n[Du]||n[jf],!n||n.tag!==5&&n.tag!==6&&n.tag!==13&&n.tag!==3?null:n}function zx(n){if(n.tag===5||n.tag===6)return n.stateNode;throw Error(ft(33))}function aF(n){return n[yj]||null}var CR=[],Ox=-1;function qg(n){return{current:n}}function _i(n){0>Ox||(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<t.length;n++){var r=t[n];do r=r(!0);while(r!==null)}bh=null,lF=!1}catch(i){throw bh!==null&&(bh=bh.slice(n+1)),U7(BM,Vg),i}finally{$r=e,YE=!1}}return null}var Lx=[],Nx=0,CA=null,AA=0,kd=[],_d=0,c0=null,cf=1,uf="";function im(n,e){Lx[Nx++]=AA,Lx[Nx++]=CA,CA=n,AA=e}function xW(n,e,t){kd[_d++]=cf,kd[_d++]=uf,kd[_d++]=c0,c0=n;var r=cf;n=uf;var i=32-Tc(r)-1;r&=~(1<<i),t+=1;var o=32-Tc(e)+i;if(30<o){var a=i-i%5;o=(r&(1<<a)-1).toString(32),r>>=a,i-=a,cf=1<<32-Tc(e)+i|t<<i|r,uf=o+n}else cf=1<<o|t<<i|r,uf=n}function HM(n){n.return!==null&&(im(n,1),xW(n,1,0))}function qM(n){for(;n===CA;)CA=Lx[--Nx],Lx[Nx]=null,AA=Lx[--Nx],Lx[Nx]=null;for(;n===c0;)c0=kd[--_d],kd[_d]=null,uf=kd[--_d],kd[_d]=null,cf=kd[--_d],kd[_d]=null}var Vl=null,Nl=null,Ii=!1,kc=null;function bW(n,e){var t=Dd(5,null,null,0);t.elementType="DELETED",t.stateNode=e,t.return=n,e=n.deletions,e===null?(n.deletions=[t],n.flags|=16):e.push(t)}function hz(n,e){switch(n.tag){case 5:var t=n.type;return e=e.nodeType!==1||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(n.stateNode=e,Vl=n,Nl=wg(e.firstChild),!0):!1;case 6:return e=n.pendingProps===""||e.nodeType!==3?null:e,e!==null?(n.stateNode=e,Vl=n,Nl=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=c0!==null?{id:cf,overflow:uf}:null,n.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=Dd(18,null,null,0),t.stateNode=e,t.return=n,n.child=t,Vl=n,Nl=null,!0):!1;default:return!1}}function AR(n){return(n.mode&1)!==0&&(n.flags&128)===0}function TR(n){if(Ii){var e=Nl;if(e){var t=e;if(!hz(n,e)){if(AR(n))throw Error(ft(418));e=wg(t.nextSibling);var r=Vl;e&&hz(n,e)?bW(r,t):(n.flags=n.flags&-4097|2,Ii=!1,Vl=n)}}else{if(AR(n))throw Error(ft(418));n.flags=n.flags&-4097|2,Ii=!1,Vl=n}}}function fz(n){for(n=n.return;n!==null&&n.tag!==5&&n.tag!==3&&n.tag!==13;)n=n.return;Vl=n}function a2(n){if(n!==Vl)return!1;if(!Ii)return fz(n),Ii=!0,!1;var e;if((e=n.tag!==3)&&!(e=n.tag!==5)&&(e=n.type,e=e!=="head"&&e!=="body"&&!jR(n.type,n.memoizedProps)),e&&(e=Nl)){if(AR(n))throw vW(),Error(ft(418));for(;e;)bW(n,e),e=wg(e.nextSibling)}if(fz(n),n.tag===13){if(n=n.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(ft(317));e:{for(n=n.nextSibling,e=0;n;){if(n.nodeType===8){var t=n.data;if(t==="/$"){if(e===0){Nl=wg(n.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}n=n.nextSibling}Nl=null}}else Nl=Vl?wg(n.stateNode.nextSibling):null;return!0}function vW(){for(var n=Nl;n;)n=wg(n.nextSibling)}function $v(){Nl=Vl=null,Ii=!1}function VM(n){kc===null?kc=[n]:kc.push(n)}var PQ=Ef.ReactCurrentBatchConfig;function _w(n,e,t){if(n=t.ref,n!==null&&typeof n!="function"&&typeof n!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(ft(309));var r=t.stateNode}if(!r)throw Error(ft(147,n));var i=r,o=""+n;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===o?e.ref:(e=function(a){var l=i.refs;a===null?delete l[o]:l[o]=a},e._stringRef=o,e)}if(typeof n!="string")throw Error(ft(284));if(!t._owner)throw Error(ft(290,n))}return n}function l2(n,e){throw n=Object.prototype.toString.call(e),Error(ft(31,n==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":n))}function pz(n){var e=n._init;return e(n._payload)}function wW(n){function e(x,w){if(n){var S=x.deletions;S===null?(x.deletions=[w],x.flags|=16):S.push(w)}}function t(x,w){if(!n)return null;for(;w!==null;)e(x,w),w=w.sibling;return null}function r(x,w){for(x=new Map;w!==null;)w.key!==null?x.set(w.key,w):x.set(w.index,w),w=w.sibling;return x}function i(x,w){return x=_g(x,w),x.index=0,x.sibling=null,x}function o(x,w,S){return x.index=S,n?(S=x.alternate,S!==null?(S=S.index,S<w?(x.flags|=2,w):S):(x.flags|=2,w)):(x.flags|=1048576,w)}function a(x){return n&&x.alternate===null&&(x.flags|=2),x}function l(x,w,S,_){return w===null||w.tag!==6?(w=nP(S,x.mode,_),w.return=x,w):(w=i(w,S),w.return=x,w)}function d(x,w,S,_){var b=S.type;return b===Rx?u(x,w,S.props.children,_,S.key):w!==null&&(w.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===ep&&pz(b)===w.type)?(_=i(w,S.props),_.ref=_w(x,w,S),_.return=x,_):(_=u5(S.type,S.key,S.props,null,x.mode,_),_.ref=_w(x,w,S),_.return=x,_)}function c(x,w,S,_){return w===null||w.tag!==4||w.stateNode.containerInfo!==S.containerInfo||w.stateNode.implementation!==S.implementation?(w=rP(S,x.mode,_),w.return=x,w):(w=i(w,S.children||[]),w.return=x,w)}function u(x,w,S,_,b){return w===null||w.tag!==7?(w=s0(S,x.mode,_,b),w.return=x,w):(w=i(w,S),w.return=x,w)}function f(x,w,S){if(typeof w=="string"&&w!==""||typeof w=="number")return w=nP(""+w,x.mode,S),w.return=x,w;if(typeof w=="object"&&w!==null){switch(w.$$typeof){case $C:return S=u5(w.type,w.key,w.props,null,x.mode,S),S.ref=_w(x,null,w),S.return=x,S;case Px:return w=rP(w,x.mode,S),w.return=x,w;case ep:var _=w._init;return f(x,_(w._payload),S)}if(Yw(w)||vw(w))return w=s0(w,x.mode,S,null),w.return=x,w;l2(x,w)}return null}function p(x,w,S,_){var b=w!==null?w.key:null;if(typeof S=="string"&&S!==""||typeof S=="number")return b!==null?null:l(x,w,""+S,_);if(typeof S=="object"&&S!==null){switch(S.$$typeof){case $C:return S.key===b?d(x,w,S,_):null;case Px:return S.key===b?c(x,w,S,_):null;case ep:return b=S._init,p(x,w,b(S._payload),_)}if(Yw(S)||vw(S))return b!==null?null:u(x,w,S,_,null);l2(x,S)}return null}function g(x,w,S,_,b){if(typeof _=="string"&&_!==""||typeof _=="number")return x=x.get(S)||null,l(w,x,""+_,b);if(typeof _=="object"&&_!==null){switch(_.$$typeof){case $C:return x=x.get(_.key===null?S:_.key)||null,d(w,x,_,b);case Px:return x=x.get(_.key===null?S:_.key)||null,c(w,x,_,b);case ep:var C=_._init;return g(x,w,S,C(_._payload),b)}if(Yw(_)||vw(_))return x=x.get(S)||null,u(w,x,_,b,null);l2(w,_)}return null}function m(x,w,S,_){for(var b=null,C=null,T=w,F=w=0,A=null;T!==null&&F<S.length;F++){T.index>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(;F<S.length;F++)T=f(x,S[F],_),T!==null&&(w=o(T,w,F),C===null?b=T:C.sibling=T,C=T);return Ii&&im(x,F),b}for(T=r(x,T);F<S.length;F++)A=g(T,x,F,S[F],_),A!==null&&(n&&A.alternate!==null&&T.delete(A.key===null?F:A.key),w=o(A,w,F),C===null?b=A:C.sibling=A,C=A);return n&&T.forEach(function(P){return e(x,P)}),Ii&&im(x,F),b}function y(x,w,S,_){var b=vw(S);if(typeof b!="function")throw Error(ft(150));if(S=b.call(S),S==null)throw Error(ft(151));for(var C=b=null,T=w,F=w=0,A=null,D=S.next();T!==null&&!D.done;F++,D=S.next()){T.index>F?(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;e<n.length;e++){var r=n[e],i=r.callback;if(i!==null){if(r.callback=null,r=t,typeof i!="function")throw Error(ft(191,i));i.call(r)}}}var V_={},Mu=qg(V_),xj=qg(V_),bj=qg(V_);function ym(n){if(n===V_)throw Error(ft(174));return n}function $M(n,e){switch(yi(bj,e),yi(xj,n),yi(Mu,V_),n=e.nodeType,n){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:dR(null,"");break;default:n=n===8?e.parentNode:e,e=n.namespaceURI||null,n=n.tagName,e=dR(e,n)}_i(Mu),yi(Mu,e)}function Jv(){_i(Mu),_i(xj),_i(bj)}function _W(n){ym(bj.current);var e=ym(Mu.current),t=dR(e,n.type);e!==t&&(yi(xj,n),yi(Mu,t))}function ZM(n){xj.current===n&&(_i(Mu),_i(xj))}var Qi=qg(0);function EA(n){for(var e=n;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===n)break;for(;e.sibling===null;){if(e.return===null||e.return===n)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var QE=[];function JM(){for(var n=0;n<QE.length;n++)QE[n]._workInProgressVersionPrimary=null;QE.length=0}var o5=Ef.ReactCurrentDispatcher,$E=Ef.ReactCurrentBatchConfig,u0=0,Ji=null,zs=null,uo=null,PA=!1,OS=!1,vj=0,RQ=0;function Vo(){throw Error(ft(321))}function e6(n,e){if(e===null)return!1;for(var t=0;t<e.length&&t<n.length;t++)if(!Ec(n[t],e[t]))return!1;return!0}function t6(n,e,t,r,i,o){if(u0=o,Ji=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,o5.current=n===null||n.memoizedState===null?zQ:OQ,n=t(r,i),OS){o=0;do{if(OS=!1,vj=0,25<=o)throw Error(ft(301));o+=1,uo=zs=null,e.updateQueue=null,o5.current=LQ,n=t(r,i)}while(OS)}if(o5.current=RA,e=zs!==null&&zs.next!==null,u0=0,uo=zs=Ji=null,PA=!1,e)throw Error(ft(300));return n}function n6(){var n=vj!==0;return vj=0,n}function Zc(){var n={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return uo===null?Ji.memoizedState=uo=n:uo=uo.next=n,uo}function Ld(){if(zs===null){var n=Ji.alternate;n=n!==null?n.memoizedState:null}else n=zs.next;var e=uo===null?Ji.memoizedState:uo.next;if(e!==null)uo=e,zs=n;else{if(n===null)throw Error(ft(310));zs=n,n={memoizedState:zs.memoizedState,baseState:zs.baseState,baseQueue:zs.baseQueue,queue:zs.queue,next:null},uo===null?Ji.memoizedState=uo=n:uo=uo.next=n}return uo}function wj(n,e){return typeof e=="function"?e(n):e}function ZE(n){var e=Ld(),t=e.queue;if(t===null)throw Error(ft(311));t.lastRenderedReducer=n;var r=zs,i=r.baseQueue,o=t.pending;if(o!==null){if(i!==null){var a=i.next;i.next=o.next,o.next=a}r.baseQueue=i=o,t.pending=null}if(i!==null){o=i.next,r=r.baseState;var l=a=null,d=null,c=o;do{var u=c.lane;if((u0&u)===u)d!==null&&(d=d.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),r=c.hasEagerState?c.eagerState:n(r,c.action);else{var f={lane:u,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};d===null?(l=d=f,a=r):d=d.next=f,Ji.lanes|=u,h0|=u}c=c.next}while(c!==null&&c!==o);d===null?a=r:d.next=l,Ec(r,e.memoizedState)||(Ja=!0),e.memoizedState=r,e.baseState=a,e.baseQueue=d,t.lastRenderedState=r}if(n=t.interleaved,n!==null){i=n;do o=i.lane,Ji.lanes|=o,h0|=o,i=i.next;while(i!==n)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function JE(n){var e=Ld(),t=e.queue;if(t===null)throw Error(ft(311));t.lastRenderedReducer=n;var r=t.dispatch,i=t.pending,o=e.memoizedState;if(i!==null){t.pending=null;var a=i=i.next;do o=n(o,a.action),a=a.next;while(a!==i);Ec(o,e.memoizedState)||(Ja=!0),e.memoizedState=o,e.baseQueue===null&&(e.baseState=o),t.lastRenderedState=o}return[o,r]}function CW(){}function AW(n,e){var t=Ji,r=Ld(),i=e(),o=!Ec(r.memoizedState,i);if(o&&(r.memoizedState=i,Ja=!0),r=r.queue,r6(DW.bind(null,t,r,n),[n]),r.getSnapshot!==e||o||uo!==null&&uo.memoizedState.tag&1){if(t.flags|=2048,Sj(9,FW.bind(null,t,r,i,e),void 0,null),po===null)throw Error(ft(349));u0&30||TW(t,e,i)}return i}function TW(n,e,t){n.flags|=16384,n={getSnapshot:e,value:t},e=Ji.updateQueue,e===null?(e={lastEffect:null,stores:null},Ji.updateQueue=e,e.stores=[n]):(t=e.stores,t===null?e.stores=[n]:t.push(n))}function FW(n,e,t,r){e.value=t,e.getSnapshot=r,EW(e)&&PW(n)}function DW(n,e,t){return t(function(){EW(e)&&PW(n)})}function EW(n){var e=n.getSnapshot;n=n.value;try{var t=e();return!Ec(n,t)}catch{return!0}}function PW(n){var e=kf(n,1);e!==null&&Fc(e,n,1,-1)}function yz(n){var e=Zc();return typeof n=="function"&&(n=n()),e.memoizedState=e.baseState=n,n={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:wj,lastRenderedState:n},e.queue=n,n=n.dispatch=MQ.bind(null,Ji,n),[e.memoizedState,n]}function Sj(n,e,t,r){return n={tag:n,create:e,destroy:t,deps:r,next:null},e=Ji.updateQueue,e===null?(e={lastEffect:null,stores:null},Ji.updateQueue=e,e.lastEffect=n.next=n):(t=e.lastEffect,t===null?e.lastEffect=n.next=n:(r=t.next,t.next=n,n.next=r,e.lastEffect=n)),n}function RW(){return Ld().memoizedState}function a5(n,e,t,r){var i=Zc();Ji.flags|=n,i.memoizedState=Sj(1|e,t,void 0,r===void 0?null:r)}function dF(n,e,t,r){var i=Ld();r=r===void 0?null:r;var o=void 0;if(zs!==null){var a=zs.memoizedState;if(o=a.destroy,r!==null&&e6(r,a.deps)){i.memoizedState=Sj(e,t,o,r);return}}Ji.flags|=n,i.memoizedState=Sj(1|e,t,o,r)}function xz(n,e){return a5(8390656,8,n,e)}function r6(n,e){return dF(2048,8,n,e)}function BW(n,e){return dF(4,2,n,e)}function IW(n,e){return dF(4,4,n,e)}function MW(n,e){if(typeof e=="function")return n=n(),e(n),function(){e(null)};if(e!=null)return n=n(),e.current=n,function(){e.current=null}}function zW(n,e,t){return t=t!=null?t.concat([n]):null,dF(4,4,MW.bind(null,e,n),t)}function i6(){}function OW(n,e){var t=Ld();e=e===void 0?null:e;var r=t.memoizedState;return r!==null&&e!==null&&e6(e,r[1])?r[0]:(t.memoizedState=[n,e],n)}function LW(n,e){var t=Ld();e=e===void 0?null:e;var r=t.memoizedState;return r!==null&&e!==null&&e6(e,r[1])?r[0]:(n=n(),t.memoizedState=[n,e],n)}function NW(n,e,t){return u0&21?(Ec(t,e)||(t=V7(),Ji.lanes|=t,h0|=t,n.baseState=!0),e):(n.baseState&&(n.baseState=!1,Ja=!0),n.memoizedState=t)}function BQ(n,e){var t=$r;$r=t!==0&&4>t?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<t&&(e+="H"+t.toString(32)),e+=":"}else t=RQ++,e=":"+e+"r"+t.toString(32)+":";return n.memoizedState=e},unstable_isNewReconciler:!1},OQ={readContext:Od,useCallback:OW,useContext:Od,useEffect:r6,useImperativeHandle:zW,useInsertionEffect:BW,useLayoutEffect:IW,useMemo:LW,useReducer:ZE,useRef:RW,useState:function(){return ZE(wj)},useDebugValue:i6,useDeferredValue:function(n){var e=Ld();return NW(e,zs.memoizedState,n)},useTransition:function(){var n=ZE(wj)[0],e=Ld().memoizedState;return[n,e]},useMutableSource:CW,useSyncExternalStore:AW,useId:WW,unstable_isNewReconciler:!1},LQ={readContext:Od,useCallback:OW,useContext:Od,useEffect:r6,useImperativeHandle:zW,useInsertionEffect:BW,useLayoutEffect:IW,useMemo:LW,useReducer:JE,useRef:RW,useState:function(){return JE(wj)},useDebugValue:i6,useDeferredValue:function(n){var e=Ld();return zs===null?e.memoizedState=n:NW(e,zs.memoizedState,n)},useTransition:function(){var n=JE(wj)[0],e=Ld().memoizedState;return[n,e]},useMutableSource:CW,useSyncExternalStore:AW,useId:WW,unstable_isNewReconciler:!1};function ac(n,e){if(n&&n.defaultProps){e=ns({},e),n=n.defaultProps;for(var t in n)e[t]===void 0&&(e[t]=n[t]);return e}return e}function DR(n,e,t,r){e=n.memoizedState,t=t(r,e),t=t==null?e:ns({},e,t),n.memoizedState=t,n.lanes===0&&(n.updateQueue.baseState=t)}var cF={isMounted:function(n){return(n=n._reactInternals)?D0(n)===n:!1},enqueueSetState:function(n,e,t){n=n._reactInternals;var r=_a(),i=kg(n),o=ff(r,i);o.payload=e,t!=null&&(o.callback=t),e=Sg(n,o,i),e!==null&&(Fc(e,n,i,r),s5(e,n,i))},enqueueReplaceState:function(n,e,t){n=n._reactInternals;var r=_a(),i=kg(n),o=ff(r,i);o.tag=1,o.payload=e,t!=null&&(o.callback=t),e=Sg(n,o,i),e!==null&&(Fc(e,n,i,r),s5(e,n,i))},enqueueForceUpdate:function(n,e){n=n._reactInternals;var t=_a(),r=kg(n),i=ff(t,r);i.tag=2,e!=null&&(i.callback=e),e=Sg(n,i,r),e!==null&&(Fc(e,n,r,t),s5(e,n,r))}};function bz(n,e,t,r,i,o,a){return n=n.stateNode,typeof n.shouldComponentUpdate=="function"?n.shouldComponentUpdate(r,o,a):e.prototype&&e.prototype.isPureReactComponent?!pj(t,r)||!pj(i,o):!0}function VW(n,e,t){var r=!1,i=Ig,o=e.contextType;return typeof o=="object"&&o!==null?o=Od(o):(i=nl(e)?d0:ia.current,r=e.contextTypes,o=(r=r!=null)?Qv(n,i):Ig),e=new e(t,o),n.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=cF,n.stateNode=e,e._reactInternals=n,r&&(n=n.stateNode,n.__reactInternalMemoizedUnmaskedChildContext=i,n.__reactInternalMemoizedMaskedChildContext=o),e}function vz(n,e,t,r){n=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,r),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,r),e.state!==n&&cF.enqueueReplaceState(e,e.state,null)}function ER(n,e,t,r){var i=n.stateNode;i.props=t,i.state=n.memoizedState,i.refs={},QM(n);var o=e.contextType;typeof o=="object"&&o!==null?i.context=Od(o):(o=nl(e)?d0:ia.current,i.context=Qv(n,o)),i.state=n.memoizedState,o=e.getDerivedStateFromProps,typeof o=="function"&&(DR(n,e,o,t),i.state=n.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(e=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),e!==i.state&&cF.enqueueReplaceState(i,i.state,null),DA(n,t,i,r),i.state=n.memoizedState),typeof i.componentDidMount=="function"&&(n.flags|=4194308)}function e1(n,e){try{var t="",r=e;do t+=fY(r),r=r.return;while(r);var i=t}catch(o){i=`
Error generating stack: `+o.message+`
`+o.stack}return{value:n,source:e,stack:i,digest:null}}function eP(n,e,t){return{value:n,source:null,stack:t??null,digest:e??null}}function PR(n,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var NQ=typeof WeakMap=="function"?WeakMap:Map;function GW(n,e,t){t=ff(-1,t),t.tag=3,t.payload={element:null};var r=e.value;return t.callback=function(){IA||(IA=!0,UR=r),PR(n,e)},t}function KW(n,e,t){t=ff(-1,t),t.tag=3;var r=n.type.getDerivedStateFromError;if(typeof r=="function"){var i=e.value;t.payload=function(){return r(i)},t.callback=function(){PR(n,e)}}var o=n.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(t.callback=function(){PR(n,e),typeof r!="function"&&(jg===null?jg=new Set([this]):jg.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),t}function wz(n,e,t){var r=n.pingCache;if(r===null){r=n.pingCache=new NQ;var i=new Set;r.set(e,i)}else i=r.get(e),i===void 0&&(i=new Set,r.set(e,i));i.has(t)||(i.add(t),n=e$.bind(null,n,e,t),e.then(n,n))}function Sz(n){do{var e;if((e=n.tag===13)&&(e=n.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return n;n=n.return}while(n!==null);return null}function jz(n,e,t,r,i){return n.mode&1?(n.flags|=65536,n.lanes=i,n):(n===e?n.flags|=65536:(n.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(e=ff(-1,1),e.tag=2,Sg(t,e,1))),t.lanes|=1),n)}var WQ=Ef.ReactCurrentOwner,Ja=!1;function va(n,e,t,r){e.child=n===null?SW(e,null,t,r):Zv(e,n.child,t,r)}function kz(n,e,t,r,i){t=t.render;var o=e.ref;return nb(e,i),r=t6(n,e,t,r,o,i),t=n6(),n!==null&&!Ja?(e.updateQueue=n.updateQueue,e.flags&=-2053,n.lanes&=~i,_f(n,e,i)):(Ii&&t&&HM(e),e.flags|=1,va(n,e,r,i),e.child)}function _z(n,e,t,r,i){if(n===null){var o=t.type;return typeof o=="function"&&!h6(o)&&o.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=o,XW(n,e,o,r,i)):(n=u5(t.type,null,r,e,e.mode,i),n.ref=e.ref,n.return=e,e.child=n)}if(o=n.child,!(n.lanes&i)){var a=o.memoizedProps;if(t=t.compare,t=t!==null?t:pj,t(a,r)&&n.ref===e.ref)return _f(n,e,i)}return e.flags|=1,n=_g(o,r),n.ref=e.ref,n.return=e,e.child=n}function XW(n,e,t,r,i){if(n!==null){var o=n.memoizedProps;if(pj(o,r)&&n.ref===e.ref)if(Ja=!1,e.pendingProps=r=o,(n.lanes&i)!==0)n.flags&131072&&(Ja=!0);else return e.lanes=n.lanes,_f(n,e,i)}return RR(n,e,t,r,i)}function YW(n,e,t){var r=e.pendingProps,i=r.children,o=n!==null?n.memoizedState:null;if(r.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},yi(Hx,Bl),Bl|=t;else{if(!(t&1073741824))return n=o!==null?o.baseLanes|t:t,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:n,cachePool:null,transitions:null},e.updateQueue=null,yi(Hx,Bl),Bl|=n,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=o!==null?o.baseLanes:t,yi(Hx,Bl),Bl|=r}else o!==null?(r=o.baseLanes|t,e.memoizedState=null):r=t,yi(Hx,Bl),Bl|=r;return va(n,e,i,t),e.child}function QW(n,e){var t=e.ref;(n===null&&t!==null||n!==null&&n.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function RR(n,e,t,r,i){var o=nl(t)?d0:ia.current;return o=Qv(e,o),nb(e,i),t=t6(n,e,t,r,o,i),r=n6(),n!==null&&!Ja?(e.updateQueue=n.updateQueue,e.flags&=-2053,n.lanes&=~i,_f(n,e,i)):(Ii&&r&&HM(e),e.flags|=1,va(n,e,t,i),e.child)}function Cz(n,e,t,r,i){if(nl(t)){var o=!0;_A(e)}else o=!1;if(nb(e,i),e.stateNode===null)l5(n,e),VW(e,t,r),ER(e,t,r,i),r=!0;else if(n===null){var a=e.stateNode,l=e.memoizedProps;a.props=l;var d=a.context,c=t.contextType;typeof c=="object"&&c!==null?c=Od(c):(c=nl(t)?d0:ia.current,c=Qv(e,c));var u=t.getDerivedStateFromProps,f=typeof u=="function"||typeof a.getSnapshotBeforeUpdate=="function";f||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(l!==r||d!==c)&&vz(e,a,r,c),tp=!1;var p=e.memoizedState;a.state=p,DA(e,r,a,i),d=e.memoizedState,l!==r||p!==d||tl.current||tp?(typeof u=="function"&&(DR(e,t,u,r),d=e.memoizedState),(l=tp||bz(e,t,l,r,p,d,c))?(f||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount=="function"&&(e.flags|=4194308)):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=d),a.props=r,a.state=d,a.context=c,r=l):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{a=e.stateNode,kW(n,e),l=e.memoizedProps,c=e.type===e.elementType?l:ac(e.type,l),a.props=c,f=e.pendingProps,p=a.context,d=t.contextType,typeof d=="object"&&d!==null?d=Od(d):(d=nl(t)?d0:ia.current,d=Qv(e,d));var g=t.getDerivedStateFromProps;(u=typeof g=="function"||typeof a.getSnapshotBeforeUpdate=="function")||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(l!==f||p!==d)&&vz(e,a,r,d),tp=!1,p=e.memoizedState,a.state=p,DA(e,r,a,i);var m=e.memoizedState;l!==f||p!==m||tl.current||tp?(typeof g=="function"&&(DR(e,t,g,r),m=e.memoizedState),(c=tp||bz(e,t,c,r,p,m,d)||!1)?(u||typeof a.UNSAFE_componentWillUpdate!="function"&&typeof a.componentWillUpdate!="function"||(typeof a.componentWillUpdate=="function"&&a.componentWillUpdate(r,m,d),typeof a.UNSAFE_componentWillUpdate=="function"&&a.UNSAFE_componentWillUpdate(r,m,d)),typeof a.componentDidUpdate=="function"&&(e.flags|=4),typeof a.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof a.componentDidUpdate!="function"||l===n.memoizedProps&&p===n.memoizedState||(e.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||l===n.memoizedProps&&p===n.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=m),a.props=r,a.state=m,a.context=d,r=c):(typeof a.componentDidUpdate!="function"||l===n.memoizedProps&&p===n.memoizedState||(e.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||l===n.memoizedProps&&p===n.memoizedState||(e.flags|=1024),r=!1)}return BR(n,e,t,r,o,i)}function BR(n,e,t,r,i,o){QW(n,e);var a=(e.flags&128)!==0;if(!r&&!a)return i&&uz(e,t,!1),_f(n,e,o);r=e.stateNode,WQ.current=e;var l=a&&typeof t.getDerivedStateFromError!="function"?null:r.render();return e.flags|=1,n!==null&&a?(e.child=Zv(e,n.child,null,o),e.child=Zv(e,null,l,o)):va(n,e,l,o),e.memoizedState=r.state,i&&uz(e,t,!0),e.child}function $W(n){var e=n.stateNode;e.pendingContext?cz(n,e.pendingContext,e.pendingContext!==e.context):e.context&&cz(n,e.context,!1),$M(n,e.containerInfo)}function Az(n,e,t,r,i){return $v(),VM(i),e.flags|=256,va(n,e,t,r),e.child}var IR={dehydrated:null,treeContext:null,retryLane:0};function MR(n){return{baseLanes:n,cachePool:null,transitions:null}}function ZW(n,e,t){var r=e.pendingProps,i=Qi.current,o=!1,a=(e.flags&128)!==0,l;if((l=a)||(l=n!==null&&n.memoizedState===null?!1:(i&2)!==0),l?(o=!0,e.flags&=-129):(n===null||n.memoizedState!==null)&&(i|=1),yi(Qi,i&1),n===null)return TR(e),n=e.memoizedState,n!==null&&(n=n.dehydrated,n!==null)?(e.mode&1?n.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(a=r.children,n=r.fallback,o?(r=e.mode,o=e.child,a={mode:"hidden",children:a},!(r&1)&&o!==null?(o.childLanes=0,o.pendingProps=a):o=fF(a,r,0,null),n=s0(n,r,t,null),o.return=e,n.return=e,o.sibling=n,e.child=o,e.child.memoizedState=MR(t),e.memoizedState=IR,n):s6(e,a));if(i=n.memoizedState,i!==null&&(l=i.dehydrated,l!==null))return UQ(n,e,a,r,l,i,t);if(o){o=r.fallback,a=e.mode,i=n.child,l=i.sibling;var d={mode:"hidden",children:r.children};return!(a&1)&&e.child!==i?(r=e.child,r.childLanes=0,r.pendingProps=d,e.deletions=null):(r=_g(i,d),r.subtreeFlags=i.subtreeFlags&14680064),l!==null?o=_g(l,o):(o=s0(o,a,t,null),o.flags|=2),o.return=e,r.return=e,r.sibling=o,e.child=r,r=o,o=e.child,a=n.child.memoizedState,a=a===null?MR(t):{baseLanes:a.baseLanes|t,cachePool:null,transitions:a.transitions},o.memoizedState=a,o.childLanes=n.childLanes&~t,e.memoizedState=IR,r}return o=n.child,n=o.sibling,r=_g(o,{mode:"visible",children:r.children}),!(e.mode&1)&&(r.lanes=t),r.return=e,r.sibling=null,n!==null&&(t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)),e.child=r,e.memoizedState=null,r}function s6(n,e){return e=fF({mode:"visible",children:e},n.mode,0,null),e.return=n,n.child=e}function d2(n,e,t,r){return r!==null&&VM(r),Zv(e,n.child,null,t),n=s6(e,e.pendingProps.children),n.flags|=2,e.memoizedState=null,n}function UQ(n,e,t,r,i,o,a){if(t)return e.flags&256?(e.flags&=-257,r=eP(Error(ft(422))),d2(n,e,a,r)):e.memoizedState!==null?(e.child=n.child,e.flags|=128,null):(o=r.fallback,i=e.mode,r=fF({mode:"visible",children:r.children},i,0,null),o=s0(o,i,a,null),o.flags|=2,r.return=e,o.return=e,r.sibling=o,e.child=r,e.mode&1&&Zv(e,n.child,null,a),e.child.memoizedState=MR(a),e.memoizedState=IR,o);if(!(e.mode&1))return d2(n,e,a,null);if(i.data==="$!"){if(r=i.nextSibling&&i.nextSibling.dataset,r)var l=r.dgst;return r=l,o=Error(ft(419)),r=eP(o,r,void 0),d2(n,e,a,r)}if(l=(a&n.childLanes)!==0,Ja||l){if(r=po,r!==null){switch(a&-a){case 4:i=2;break;case 16:i=8;break;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:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(r.suspendedLanes|a)?0:i,i!==0&&i!==o.retryLane&&(o.retryLane=i,kf(n,i),Fc(r,n,i,-1))}return u6(),r=eP(Error(ft(421))),d2(n,e,a,r)}return i.data==="$?"?(e.flags|=128,e.child=n.child,e=t$.bind(null,n),i._reactRetry=e,null):(n=o.treeContext,Nl=wg(i.nextSibling),Vl=e,Ii=!0,kc=null,n!==null&&(kd[_d++]=cf,kd[_d++]=uf,kd[_d++]=c0,cf=n.id,uf=n.overflow,c0=e),e=s6(e,r.children),e.flags|=4096,e)}function Tz(n,e,t){n.lanes|=e;var r=n.alternate;r!==null&&(r.lanes|=e),FR(n.return,e,t)}function tP(n,e,t,r,i){var o=n.memoizedState;o===null?n.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:i}:(o.isBackwards=e,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=t,o.tailMode=i)}function JW(n,e,t){var r=e.pendingProps,i=r.revealOrder,o=r.tail;if(va(n,e,r.children,t),r=Qi.current,r&2)r=r&1|2,e.flags|=128;else{if(n!==null&&n.flags&128)e:for(n=e.child;n!==null;){if(n.tag===13)n.memoizedState!==null&&Tz(n,t,e);else if(n.tag===19)Tz(n,t,e);else if(n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break e;for(;n.sibling===null;){if(n.return===null||n.return===e)break e;n=n.return}n.sibling.return=n.return,n=n.sibling}r&=1}if(yi(Qi,r),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(t=e.child,i=null;t!==null;)n=t.alternate,n!==null&&EA(n)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),tP(e,!1,i,t,o);break;case"backwards":for(t=null,i=e.child,e.child=null;i!==null;){if(n=i.alternate,n!==null&&EA(n)===null){e.child=i;break}n=i.sibling,i.sibling=t,t=i,i=n}tP(e,!0,t,null,o);break;case"together":tP(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function l5(n,e){!(e.mode&1)&&n!==null&&(n.alternate=null,e.alternate=null,e.flags|=2)}function _f(n,e,t){if(n!==null&&(e.dependencies=n.dependencies),h0|=e.lanes,!(t&e.childLanes))return null;if(n!==null&&e.child!==n.child)throw Error(ft(153));if(e.child!==null){for(n=e.child,t=_g(n,n.pendingProps),e.child=t,t.return=e;n.sibling!==null;)n=n.sibling,t=t.sibling=_g(n,n.pendingProps),t.return=e;t.sibling=null}return e.child}function HQ(n,e,t){switch(e.tag){case 3:$W(e),$v();break;case 5:_W(e);break;case 1:nl(e.type)&&_A(e);break;case 4:$M(e,e.stateNode.containerInfo);break;case 10:var r=e.type._context,i=e.memoizedProps.value;yi(TA,r._currentValue),r._currentValue=i;break;case 13:if(r=e.memoizedState,r!==null)return r.dehydrated!==null?(yi(Qi,Qi.current&1),e.flags|=128,null):t&e.child.childLanes?ZW(n,e,t):(yi(Qi,Qi.current&1),n=_f(n,e,t),n!==null?n.sibling:null);yi(Qi,Qi.current&1);break;case 19:if(r=(t&e.childLanes)!==0,n.flags&128){if(r)return JW(n,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),yi(Qi,Qi.current),r)break;return null;case 22:case 23:return e.lanes=0,YW(n,e,t)}return _f(n,e,t)}var e9,zR,t9,n9;e9=function(n,e){for(var t=e.child;t!==null;){if(t.tag===5||t.tag===6)n.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}};zR=function(){};t9=function(n,e,t,r){var i=n.memoizedProps;if(i!==r){n=e.stateNode,ym(Mu.current);var o=null;switch(t){case"input":i=sR(n,i),r=sR(n,r),o=[];break;case"select":i=ns({},i,{value:void 0}),r=ns({},r,{value:void 0}),o=[];break;case"textarea":i=lR(n,i),r=lR(n,r),o=[];break;default:typeof i.onClick!="function"&&typeof r.onClick=="function"&&(n.onclick=jA)}cR(t,r);var a;t=null;for(c in i)if(!r.hasOwnProperty(c)&&i.hasOwnProperty(c)&&i[c]!=null)if(c==="style"){var l=i[c];for(a in l)l.hasOwnProperty(a)&&(t||(t={}),t[a]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(aj.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in r){var d=r[c];if(l=i!=null?i[c]:void 0,r.hasOwnProperty(c)&&d!==l&&(d!=null||l!=null))if(c==="style")if(l){for(a in l)!l.hasOwnProperty(a)||d&&d.hasOwnProperty(a)||(t||(t={}),t[a]="");for(a in d)d.hasOwnProperty(a)&&l[a]!==d[a]&&(t||(t={}),t[a]=d[a])}else t||(o||(o=[]),o.push(c,t)),t=d;else c==="dangerouslySetInnerHTML"?(d=d?d.__html:void 0,l=l?l.__html:void 0,d!=null&&l!==d&&(o=o||[]).push(c,d)):c==="children"?typeof d!="string"&&typeof d!="number"||(o=o||[]).push(c,""+d):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(aj.hasOwnProperty(c)?(d!=null&&c==="onScroll"&&vi("scroll",n),o||l===d||(o=[])):(o=o||[]).push(c,d))}t&&(o=o||[]).push("style",t);var c=o;(e.updateQueue=c)&&(e.flags|=4)}};n9=function(n,e,t,r){t!==r&&(e.flags|=4)};function Cw(n,e){if(!Ii)switch(n.tailMode){case"hidden":e=n.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?n.tail=null:t.sibling=null;break;case"collapsed":t=n.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?e||n.tail===null?n.tail=null:n.tail.sibling=null:r.sibling=null}}function Go(n){var e=n.alternate!==null&&n.alternate.child===n.child,t=0,r=0;if(e)for(var i=n.child;i!==null;)t|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=n,i=i.sibling;else for(i=n.child;i!==null;)t|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=n,i=i.sibling;return n.subtreeFlags|=r,n.childLanes=t,e}function qQ(n,e,t){var r=e.pendingProps;switch(qM(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Go(e),null;case 1:return nl(e.type)&&kA(),Go(e),null;case 3:return r=e.stateNode,Jv(),_i(tl),_i(ia),JM(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(n===null||n.child===null)&&(a2(e)?e.flags|=4:n===null||n.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,kc!==null&&(VR(kc),kc=null))),zR(n,e),Go(e),null;case 5:ZM(e);var i=ym(bj.current);if(t=e.type,n!==null&&e.stateNode!=null)t9(n,e,t,r,i),n.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!r){if(e.stateNode===null)throw Error(ft(166));return Go(e),null}if(n=ym(Mu.current),a2(e)){r=e.stateNode,t=e.type;var o=e.memoizedProps;switch(r[Du]=e,r[yj]=o,n=(e.mode&1)!==0,t){case"dialog":vi("cancel",r),vi("close",r);break;case"iframe":case"object":case"embed":vi("load",r);break;case"video":case"audio":for(i=0;i<$w.length;i++)vi($w[i],r);break;case"source":vi("error",r);break;case"img":case"image":case"link":vi("error",r),vi("load",r);break;case"details":vi("toggle",r);break;case"input":z8(r,o),vi("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!o.multiple},vi("invalid",r);break;case"textarea":L8(r,o),vi("invalid",r)}cR(t,o),i=null;for(var a in o)if(o.hasOwnProperty(a)){var l=o[a];a==="children"?typeof l=="string"?r.textContent!==l&&(o.suppressHydrationWarning!==!0&&o2(r.textContent,l,n),i=["children",l]):typeof l=="number"&&r.textContent!==""+l&&(o.suppressHydrationWarning!==!0&&o2(r.textContent,l,n),i=["children",""+l]):aj.hasOwnProperty(a)&&l!=null&&a==="onScroll"&&vi("scroll",r)}switch(t){case"input":ZC(r),O8(r,o,!0);break;case"textarea":ZC(r),N8(r);break;case"select":case"option":break;default:typeof o.onClick=="function"&&(r.onclick=jA)}r=i,e.updateQueue=r,r!==null&&(e.flags|=4)}else{a=i.nodeType===9?i:i.ownerDocument,n==="http://www.w3.org/1999/xhtml"&&(n=D7(t)),n==="http://www.w3.org/1999/xhtml"?t==="script"?(n=a.createElement("div"),n.innerHTML="<script><\/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;r<t.length;r++){var i=t[r];try{var o=n,a=e,l=a;e:for(;l!==null;){switch(l.tag){case 5:Ao=l.stateNode,jc=!1;break e;case 3:Ao=l.stateNode.containerInfo,jc=!0;break e;case 4:Ao=l.stateNode.containerInfo,jc=!0;break e}l=l.return}if(Ao===null)throw Error(ft(160));s9(o,a,i),Ao=null,jc=!1;var d=i.alternate;d!==null&&(d.return=null),i.return=null}catch(c){us(i,e,c)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)o9(e,n),e=e.sibling}function o9(n,e){var t=n.alternate,r=n.flags;switch(n.tag){case 0:case 11:case 14:case 15:if(tc(e,n),Uc(n),r&4){try{LS(3,n,n.return),uF(3,n)}catch(y){us(n,n.return,y)}try{LS(5,n,n.return)}catch(y){us(n,n.return,y)}}break;case 1:tc(e,n),Uc(n),r&512&&t!==null&&Ux(t,t.return);break;case 5:if(tc(e,n),Uc(n),r&512&&t!==null&&Ux(t,t.return),n.flags&32){var i=n.stateNode;try{lj(i,"")}catch(y){us(n,n.return,y)}}if(r&4&&(i=n.stateNode,i!=null)){var o=n.memoizedProps,a=t!==null?t.memoizedProps:o,l=n.type,d=n.updateQueue;if(n.updateQueue=null,d!==null)try{l==="input"&&o.type==="radio"&&o.name!=null&&T7(i,o),uR(l,a);var c=uR(l,o);for(a=0;a<d.length;a+=2){var u=d[a],f=d[a+1];u==="style"?R7(i,f):u==="dangerouslySetInnerHTML"?E7(i,f):u==="children"?lj(i,f):FM(i,u,f,c)}switch(l){case"input":oR(i,o);break;case"textarea":F7(i,o);break;case"select":var p=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!o.multiple;var g=o.value;g!=null?Zx(i,!!o.multiple,g,!1):p!==!!o.multiple&&(o.defaultValue!=null?Zx(i,!!o.multiple,o.defaultValue,!0):Zx(i,!!o.multiple,o.multiple?[]:"",!1))}i[yj]=o}catch(y){us(n,n.return,y)}}break;case 6:if(tc(e,n),Uc(n),r&4){if(n.stateNode===null)throw Error(ft(162));i=n.stateNode,o=n.memoizedProps;try{i.nodeValue=o}catch(y){us(n,n.return,y)}}break;case 3:if(tc(e,n),Uc(n),r&4&&t!==null&&t.memoizedState.isDehydrated)try{hj(e.containerInfo)}catch(y){us(n,n.return,y)}break;case 4:tc(e,n),Uc(n);break;case 13:tc(e,n),Uc(n),i=n.child,i.flags&8192&&(o=i.memoizedState!==null,i.stateNode.isHidden=o,!o||i.alternate!==null&&i.alternate.memoizedState!==null||(l6=ws())),r&4&&Ez(n);break;case 22:if(u=t!==null&&t.memoizedState!==null,n.mode&1?(na=(c=na)||u,tc(e,n),na=c):tc(e,n),Uc(n),r&8192){if(c=n.memoizedState!==null,(n.stateNode.isHidden=c)&&!u&&n.mode&1)for(Ut=n,u=n.child;u!==null;){for(f=Ut=u;Ut!==null;){switch(p=Ut,g=p.child,p.tag){case 0:case 11:case 14:case 15:LS(4,p,p.return);break;case 1:Ux(p,p.return);var m=p.stateNode;if(typeof m.componentWillUnmount=="function"){r=p,t=p.return;try{e=r,m.props=e.memoizedProps,m.state=e.memoizedState,m.componentWillUnmount()}catch(y){us(r,t,y)}}break;case 5:Ux(p,p.return);break;case 22:if(p.memoizedState!==null){Rz(f);continue}}g!==null?(g.return=p,Ut=g):Rz(f)}u=u.sibling}e:for(u=null,f=n;;){if(f.tag===5){if(u===null){u=f;try{i=f.stateNode,c?(o=i.style,typeof o.setProperty=="function"?o.setProperty("display","none","important"):o.display="none"):(l=f.stateNode,d=f.memoizedProps.style,a=d!=null&&d.hasOwnProperty("display")?d.display:null,l.style.display=P7("display",a))}catch(y){us(n,n.return,y)}}}else if(f.tag===6){if(u===null)try{f.stateNode.nodeValue=c?"":f.memoizedProps}catch(y){us(n,n.return,y)}}else if((f.tag!==22&&f.tag!==23||f.memoizedState===null||f===n)&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===n)break e;for(;f.sibling===null;){if(f.return===null||f.return===n)break e;u===f&&(u=null),f=f.return}u===f&&(u=null),f.sibling.return=f.return,f=f.sibling}}break;case 19:tc(e,n),Uc(n),r&4&&Ez(n);break;case 21:break;default:tc(e,n),Uc(n)}}function Uc(n){var e=n.flags;if(e&2){try{e:{for(var t=n.return;t!==null;){if(i9(t)){var r=t;break e}t=t.return}throw Error(ft(160))}switch(r.tag){case 5:var i=r.stateNode;r.flags&32&&(lj(i,""),r.flags&=-33);var o=Dz(n);WR(n,o,i);break;case 3:case 4:var a=r.stateNode.containerInfo,l=Dz(n);NR(n,l,a);break;default:throw Error(ft(161))}}catch(d){us(n,n.return,d)}n.flags&=-3}e&4096&&(n.flags&=-4097)}function XQ(n,e,t){Ut=n,a9(n)}function a9(n,e,t){for(var r=(n.mode&1)!==0;Ut!==null;){var i=Ut,o=i.child;if(i.tag===22&&r){var a=i.memoizedState!==null||c2;if(!a){var l=i.alternate,d=l!==null&&l.memoizedState!==null||na;l=c2;var c=na;if(c2=a,(na=d)&&!c)for(Ut=i;Ut!==null;)a=Ut,d=a.child,a.tag===22&&a.memoizedState!==null?Bz(i):d!==null?(d.return=a,Ut=d):Bz(i);for(;o!==null;)Ut=o,a9(o),o=o.sibling;Ut=i,c2=l,na=c}Pz(n)}else i.subtreeFlags&8772&&o!==null?(o.return=i,Ut=o):Pz(n)}}function Pz(n){for(;Ut!==null;){var e=Ut;if(e.flags&8772){var t=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:na||uF(5,e);break;case 1:var r=e.stateNode;if(e.flags&4&&!na)if(t===null)r.componentDidMount();else{var i=e.elementType===e.type?t.memoizedProps:ac(e.type,t.memoizedProps);r.componentDidUpdate(i,t.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var o=e.updateQueue;o!==null&&mz(e,o,r);break;case 3:var a=e.updateQueue;if(a!==null){if(t=null,e.child!==null)switch(e.child.tag){case 5:t=e.child.stateNode;break;case 1:t=e.child.stateNode}mz(e,a,t)}break;case 5:var l=e.stateNode;if(t===null&&e.flags&4){t=l;var d=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":d.autoFocus&&t.focus();break;case"img":d.src&&(t.src=d.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var c=e.alternate;if(c!==null){var u=c.memoizedState;if(u!==null){var f=u.dehydrated;f!==null&&hj(f)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(ft(163))}na||e.flags&512&&LR(e)}catch(p){us(e,e.return,p)}}if(e===n){Ut=null;break}if(t=e.sibling,t!==null){t.return=e.return,Ut=t;break}Ut=e.return}}function Rz(n){for(;Ut!==null;){var e=Ut;if(e===n){Ut=null;break}var t=e.sibling;if(t!==null){t.return=e.return,Ut=t;break}Ut=e.return}}function Bz(n){for(;Ut!==null;){var e=Ut;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{uF(4,e)}catch(d){us(e,t,d)}break;case 1:var r=e.stateNode;if(typeof r.componentDidMount=="function"){var i=e.return;try{r.componentDidMount()}catch(d){us(e,i,d)}}var o=e.return;try{LR(e)}catch(d){us(e,o,d)}break;case 5:var a=e.return;try{LR(e)}catch(d){us(e,a,d)}}}catch(d){us(e,e.return,d)}if(e===n){Ut=null;break}var l=e.sibling;if(l!==null){l.return=e.return,Ut=l;break}Ut=e.return}}var YQ=Math.ceil,BA=Ef.ReactCurrentDispatcher,o6=Ef.ReactCurrentOwner,Bd=Ef.ReactCurrentBatchConfig,jr=0,po=null,Fs=null,Io=0,Bl=0,Hx=qg(0),Ws=0,jj=null,h0=0,hF=0,a6=0,NS=null,Qa=null,l6=0,t1=1/0,gh=null,IA=!1,UR=null,jg=null,u2=!1,cg=null,MA=0,WS=0,HR=null,d5=-1,c5=0;function _a(){return jr&6?ws():d5!==-1?d5:d5=ws()}function kg(n){return n.mode&1?jr&2&&Io!==0?Io&-Io:PQ.transition!==null?(c5===0&&(c5=V7()),c5):(n=$r,n!==0||(n=window.event,n=n===void 0?16:Z7(n.type)),n):1}function Fc(n,e,t,r){if(50<WS)throw WS=0,HR=null,Error(ft(185));U_(n,t,r),(!(jr&2)||n!==po)&&(n===po&&(!(jr&2)&&(hF|=t),Ws===4&&ip(n,Io)),rl(n,r),t===1&&jr===0&&!(e.mode&1)&&(t1=ws()+500,lF&&Vg()))}function rl(n,e){var t=n.callbackNode;PY(n,e);var r=bA(n,n===po?Io:0);if(r===0)t!==null&&H8(t),n.callbackNode=null,n.callbackPriority=0;else if(e=r&-r,n.callbackPriority!==e){if(t!=null&&H8(t),e===1)n.tag===0?EQ(Iz.bind(null,n)):yW(Iz.bind(null,n)),AQ(function(){!(jr&6)&&Vg()}),t=null;else{switch(G7(r)){case 1:t=BM;break;case 4:t=H7;break;case 16:t=xA;break;case 536870912:t=q7;break;default:t=xA}t=g9(t,l9.bind(null,n))}n.callbackPriority=e,n.callbackNode=t}}function l9(n,e){if(d5=-1,c5=0,jr&6)throw Error(ft(327));var t=n.callbackNode;if(rb()&&n.callbackNode!==t)return null;var r=bA(n,n===po?Io:0);if(r===0)return null;if(r&30||r&n.expiredLanes||e)e=zA(n,r);else{e=r;var i=jr;jr|=2;var o=c9();(po!==n||Io!==e)&&(gh=null,t1=ws()+500,i0(n,e));do try{ZQ();break}catch(l){d9(n,l)}while(!0);KM(),BA.current=o,jr=i,Fs!==null?e=0:(po=null,Io=0,e=Ws)}if(e!==0){if(e===2&&(i=mR(n),i!==0&&(r=i,e=qR(n,i))),e===1)throw t=jj,i0(n,0),ip(n,r),rl(n,ws()),t;if(e===6)ip(n,r);else{if(i=n.current.alternate,!(r&30)&&!QQ(i)&&(e=zA(n,r),e===2&&(o=mR(n),o!==0&&(r=o,e=qR(n,o))),e===1))throw t=jj,i0(n,0),ip(n,r),rl(n,ws()),t;switch(n.finishedWork=i,n.finishedLanes=r,e){case 0:case 1:throw Error(ft(345));case 2:sm(n,Qa,gh);break;case 3:if(ip(n,r),(r&130023424)===r&&(e=l6+500-ws(),10<e)){if(bA(n,0)!==0)break;if(i=n.suspendedLanes,(i&r)!==r){_a(),n.pingedLanes|=n.suspendedLanes&i;break}n.timeoutHandle=kR(sm.bind(null,n,Qa,gh),e);break}sm(n,Qa,gh);break;case 4:if(ip(n,r),(r&4194240)===r)break;for(e=n.eventTimes,i=-1;0<r;){var a=31-Tc(r);o=1<<a,a=e[a],a>i&&(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,10<r){n.timeoutHandle=kR(sm.bind(null,n,Qa,gh),r);break}sm(n,Qa,gh);break;case 5:sm(n,Qa,gh);break;default:throw Error(ft(329))}}}return rl(n,ws()),n.callbackNode===t?l9.bind(null,n):null}function qR(n,e){var t=NS;return n.current.memoizedState.isDehydrated&&(i0(n,e).flags|=256),n=zA(n,e),n!==2&&(e=Qa,Qa=t,e!==null&&VR(e)),n}function VR(n){Qa===null?Qa=n:Qa.push.apply(Qa,n)}function QQ(n){for(var e=n;;){if(e.flags&16384){var t=e.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var r=0;r<t.length;r++){var i=t[r],o=i.getSnapshot;i=i.value;try{if(!Ec(o(),i))return!1}catch{return!1}}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===n)break;for(;e.sibling===null;){if(e.return===null||e.return===n)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function ip(n,e){for(e&=~a6,e&=~hF,n.suspendedLanes|=e,n.pingedLanes&=~e,n=n.expirationTimes;0<e;){var t=31-Tc(e),r=1<<t;n[t]=-1,e&=~r}}function Iz(n){if(jr&6)throw Error(ft(327));rb();var e=bA(n,0);if(!(e&1))return rl(n,ws()),null;var t=zA(n,e);if(n.tag!==0&&t===2){var r=mR(n);r!==0&&(e=r,t=qR(n,r))}if(t===1)throw t=jj,i0(n,0),ip(n,e),rl(n,ws()),t;if(t===6)throw Error(ft(345));return n.finishedWork=n.current.alternate,n.finishedLanes=e,sm(n,Qa,gh),rl(n,ws()),null}function d6(n,e){var t=jr;jr|=1;try{return n(e)}finally{jr=t,jr===0&&(t1=ws()+500,lF&&Vg())}}function f0(n){cg!==null&&cg.tag===0&&!(jr&6)&&rb();var e=jr;jr|=1;var t=Bd.transition,r=$r;try{if(Bd.transition=null,$r=1,n)return n()}finally{$r=r,Bd.transition=t,jr=e,!(jr&6)&&Vg()}}function c6(){Bl=Hx.current,_i(Hx)}function i0(n,e){n.finishedWork=null,n.finishedLanes=0;var t=n.timeoutHandle;if(t!==-1&&(n.timeoutHandle=-1,CQ(t)),Fs!==null)for(t=Fs.return;t!==null;){var r=t;switch(qM(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&kA();break;case 3:Jv(),_i(tl),_i(ia),JM();break;case 5:ZM(r);break;case 4:Jv();break;case 13:_i(Qi);break;case 19:_i(Qi);break;case 10:XM(r.type._context);break;case 22:case 23:c6()}t=t.return}if(po=n,Fs=n=_g(n.current,null),Io=Bl=e,Ws=0,jj=null,a6=hF=h0=0,Qa=NS=null,mm!==null){for(e=0;e<mm.length;e++)if(t=mm[e],r=t.interleaved,r!==null){t.interleaved=null;var i=r.next,o=t.pending;if(o!==null){var a=o.next;o.next=i,r.next=a}t.pending=r}mm=null}return n}function d9(n,e){do{var t=Fs;try{if(KM(),o5.current=RA,PA){for(var r=Ji.memoizedState;r!==null;){var i=r.queue;i!==null&&(i.pending=null),r=r.next}PA=!1}if(u0=0,uo=zs=Ji=null,OS=!1,vj=0,o6.current=null,t===null||t.return===null){Ws=1,jj=e,Fs=null;break}e:{var o=n,a=t.return,l=t,d=e;if(e=Io,l.flags|=32768,d!==null&&typeof d=="object"&&typeof d.then=="function"){var c=d,u=l,f=u.tag;if(!(u.mode&1)&&(f===0||f===11||f===15)){var p=u.alternate;p?(u.updateQueue=p.updateQueue,u.memoizedState=p.memoizedState,u.lanes=p.lanes):(u.updateQueue=null,u.memoizedState=null)}var g=Sz(a);if(g!==null){g.flags&=-257,jz(g,a,l,o,e),g.mode&1&&wz(o,c,e),e=g,d=c;var m=e.updateQueue;if(m===null){var y=new Set;y.add(d),e.updateQueue=y}else m.add(d);break e}else{if(!(e&1)){wz(o,c,e),u6();break e}d=Error(ft(426))}}else if(Ii&&l.mode&1){var v=Sz(a);if(v!==null){!(v.flags&65536)&&(v.flags|=256),jz(v,a,l,o,e),VM(e1(d,l));break e}}o=d=e1(d,l),Ws!==4&&(Ws=2),NS===null?NS=[o]:NS.push(o),o=a;do{switch(o.tag){case 3:o.flags|=65536,e&=-e,o.lanes|=e;var x=GW(o,d,e);gz(o,x);break e;case 1:l=d;var w=o.type,S=o.stateNode;if(!(o.flags&128)&&(typeof w.getDerivedStateFromError=="function"||S!==null&&typeof S.componentDidCatch=="function"&&(jg===null||!jg.has(S)))){o.flags|=65536,e&=-e,o.lanes|=e;var _=KW(o,l,e);gz(o,_);break e}}o=o.return}while(o!==null)}h9(t)}catch(b){e=b,Fs===t&&t!==null&&(Fs=t=t.return);continue}break}while(!0)}function c9(){var n=BA.current;return BA.current=RA,n===null?RA:n}function u6(){(Ws===0||Ws===3||Ws===2)&&(Ws=4),po===null||!(h0&268435455)&&!(hF&268435455)||ip(po,Io)}function zA(n,e){var t=jr;jr|=2;var r=c9();(po!==n||Io!==e)&&(gh=null,i0(n,e));do try{$Q();break}catch(i){d9(n,i)}while(!0);if(KM(),jr=t,BA.current=r,Fs!==null)throw Error(ft(261));return po=null,Io=0,Ws}function $Q(){for(;Fs!==null;)u9(Fs)}function ZQ(){for(;Fs!==null&&!jY();)u9(Fs)}function u9(n){var e=p9(n.alternate,n,Bl);n.memoizedProps=n.pendingProps,e===null?h9(n):Fs=e,o6.current=null}function h9(n){var e=n;do{var t=e.alternate;if(n=e.return,e.flags&32768){if(t=VQ(t,e),t!==null){t.flags&=32767,Fs=t;return}if(n!==null)n.flags|=32768,n.subtreeFlags=0,n.deletions=null;else{Ws=6,Fs=null;return}}else if(t=qQ(t,e,Bl),t!==null){Fs=t;return}if(e=e.sibling,e!==null){Fs=e;return}Fs=e=n}while(e!==null);Ws===0&&(Ws=5)}function sm(n,e,t){var r=$r,i=Bd.transition;try{Bd.transition=null,$r=1,JQ(n,e,t,r)}finally{Bd.transition=i,$r=r}return null}function JQ(n,e,t,r){do rb();while(cg!==null);if(jr&6)throw Error(ft(327));t=n.finishedWork;var i=n.finishedLanes;if(t===null)return null;if(n.finishedWork=null,n.finishedLanes=0,t===n.current)throw Error(ft(177));n.callbackNode=null,n.callbackPriority=0;var o=t.lanes|t.childLanes;if(RY(n,o),n===po&&(Fs=po=null,Io=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||u2||(u2=!0,g9(xA,function(){return rb(),null})),o=(t.flags&15990)!==0,t.subtreeFlags&15990||o){o=Bd.transition,Bd.transition=null;var a=$r;$r=1;var l=jr;jr|=4,o6.current=null,KQ(n,t),o9(t,n),bQ(SR),vA=!!wR,SR=wR=null,n.current=t,XQ(t),kY(),jr=l,$r=a,Bd.transition=o}else n.current=t;if(u2&&(u2=!1,cg=n,MA=i),o=n.pendingLanes,o===0&&(jg=null),AY(t.stateNode),rl(n,ws()),e!==null)for(r=n.onRecoverableError,t=0;t<e.length;t++)i=e[t],r(i.value,{componentStack:i.stack,digest:i.digest});if(IA)throw IA=!1,n=UR,UR=null,n;return MA&1&&n.tag!==0&&rb(),o=n.pendingLanes,o&1?n===HR?WS++:(WS=0,HR=n):WS=0,Vg(),null}function rb(){if(cg!==null){var n=G7(MA),e=Bd.transition,t=$r;try{if(Bd.transition=null,$r=16>n?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;d<l.length;d++){var c=l[d];for(Ut=c;Ut!==null;){var u=Ut;switch(u.tag){case 0:case 11:case 15:LS(8,u,o)}var f=u.child;if(f!==null)f.return=u,Ut=f;else for(;Ut!==null;){u=Ut;var p=u.sibling,g=u.return;if(r9(u),u===c){Ut=null;break}if(p!==null){p.return=g,Ut=p;break}Ut=g}}}var m=o.alternate;if(m!==null){var y=m.child;if(y!==null){m.child=null;do{var v=y.sibling;y.sibling=null,y=v}while(y!==null)}}Ut=o}}if(o.subtreeFlags&2064&&a!==null)a.return=o,Ut=a;else e:for(;Ut!==null;){if(o=Ut,o.flags&2048)switch(o.tag){case 0:case 11:case 15:LS(9,o,o.return)}var x=o.sibling;if(x!==null){x.return=o.return,Ut=x;break e}Ut=o.return}}var w=n.current;for(Ut=w;Ut!==null;){a=Ut;var S=a.child;if(a.subtreeFlags&2064&&S!==null)S.return=a,Ut=S;else e:for(a=w;Ut!==null;){if(l=Ut,l.flags&2048)try{switch(l.tag){case 0:case 11:case 15:uF(9,l)}}catch(b){us(l,l.return,b)}if(l===a){Ut=null;break e}var _=l.sibling;if(_!==null){_.return=l.return,Ut=_;break e}Ut=l.return}}if(jr=i,Vg(),Iu&&typeof Iu.onPostCommitFiberRoot=="function")try{Iu.onPostCommitFiberRoot(rF,n)}catch{}r=!0}return r}finally{$r=t,Bd.transition=e}}return!1}function Mz(n,e,t){e=e1(t,e),e=GW(n,e,1),n=Sg(n,e,1),e=_a(),n!==null&&(U_(n,1,e),rl(n,e))}function us(n,e,t){if(n.tag===3)Mz(n,n,t);else for(;e!==null;){if(e.tag===3){Mz(e,n,t);break}else if(e.tag===1){var r=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(jg===null||!jg.has(r))){n=e1(t,n),n=KW(e,n,1),e=Sg(e,n,1),n=_a(),e!==null&&(U_(e,1,n),rl(e,n));break}}e=e.return}}function e$(n,e,t){var r=n.pingCache;r!==null&&r.delete(e),e=_a(),n.pingedLanes|=n.suspendedLanes&t,po===n&&(Io&t)===t&&(Ws===4||Ws===3&&(Io&130023424)===Io&&500>ws()-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<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Px,key:r==null?null:""+r,children:n,containerInfo:e,implementation:t}}function m9(n){if(!n)return Ig;n=n._reactInternals;e:{if(D0(n)!==n||n.tag!==1)throw Error(ft(170));var e=n;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(nl(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(ft(171))}if(n.tag===1){var t=n.type;if(nl(t))return mW(n,t,e)}return e}function y9(n,e,t,r,i,o,a,l,d){return n=f6(t,r,!0,n,i,o,a,l,d),n.context=m9(null),t=n.current,r=_a(),i=kg(t),o=ff(r,i),o.callback=e??null,Sg(t,o,i),n.current.lanes=i,U_(n,i,r),rl(n,r),n}function pF(n,e,t,r){var i=e.current,o=_a(),a=kg(i);return t=m9(t),e.context===null?e.context=t:e.pendingContext=t,e=ff(o,a),e.payload={element:n},r=r===void 0?null:r,r!==null&&(e.callback=r),n=Sg(i,e,a),n!==null&&(Fc(n,i,a,o),s5(n,i,a)),a}function OA(n){if(n=n.current,!n.child)return null;switch(n.child.tag){case 5:return n.child.stateNode;default:return n.child.stateNode}}function zz(n,e){if(n=n.memoizedState,n!==null&&n.dehydrated!==null){var t=n.retryLane;n.retryLane=t!==0&&t<e?t:e}}function p6(n,e){zz(n,e),(n=n.alternate)&&zz(n,e)}function a$(){return null}var x9=typeof reportError=="function"?reportError:function(n){console.error(n)};function g6(n){this._internalRoot=n}gF.prototype.render=g6.prototype.render=function(n){var e=this._internalRoot;if(e===null)throw Error(ft(409));pF(n,e,null,null)};gF.prototype.unmount=g6.prototype.unmount=function(){var n=this._internalRoot;if(n!==null){this._internalRoot=null;var e=n.containerInfo;f0(function(){pF(null,n,null,null)}),e[jf]=null}};function gF(n){this._internalRoot=n}gF.prototype.unstable_scheduleHydration=function(n){if(n){var e=Y7();n={blockedOn:null,target:n,priority:e};for(var t=0;t<rp.length&&e!==0&&e<rp[t].priority;t++);rp.splice(t,0,n),t===0&&$7(n)}};function m6(n){return!(!n||n.nodeType!==1&&n.nodeType!==9&&n.nodeType!==11)}function mF(n){return!(!n||n.nodeType!==1&&n.nodeType!==9&&n.nodeType!==11&&(n.nodeType!==8||n.nodeValue!==" react-mount-point-unstable "))}function Oz(){}function l$(n,e,t,r,i){if(i){if(typeof r=="function"){var o=r;r=function(){var c=OA(a);o.call(c)}}var a=y9(e,r,n,0,null,!1,!1,"",Oz);return n._reactRootContainer=a,n[jf]=a.current,gj(n.nodeType===8?n.parentNode:n),f0(),a}for(;i=n.lastChild;)n.removeChild(i);if(typeof r=="function"){var l=r;r=function(){var c=OA(d);l.call(c)}}var d=f6(n,0,!1,null,null,!1,!1,"",Oz);return n._reactRootContainer=d,n[jf]=d.current,gj(n.nodeType===8?n.parentNode:n),f0(function(){pF(e,d,t,r)}),d}function yF(n,e,t,r,i){var o=t._reactRootContainer;if(o){var a=o;if(typeof i=="function"){var l=i;i=function(){var d=OA(a);l.call(d)}}pF(e,a,n,i)}else a=l$(t,e,n,i,r);return OA(a)}K7=function(n){switch(n.tag){case 3:var e=n.stateNode;if(e.current.memoizedState.isDehydrated){var t=Qw(e.pendingLanes);t!==0&&(IM(e,t|1),rl(e,ws()),!(jr&6)&&(t1=ws()+500,Vg()))}break;case 13:f0(function(){var r=kf(n,1);if(r!==null){var i=_a();Fc(r,n,1,i)}}),p6(n,1)}};MM=function(n){if(n.tag===13){var e=kf(n,134217728);if(e!==null){var t=_a();Fc(e,n,134217728,t)}p6(n,134217728)}};X7=function(n){if(n.tag===13){var e=kg(n),t=kf(n,e);if(t!==null){var r=_a();Fc(t,n,e,r)}p6(n,e)}};Y7=function(){return $r};Q7=function(n,e){var t=$r;try{return $r=n,e()}finally{$r=t}};fR=function(n,e,t){switch(e){case"input":if(oR(n,t),e=t.name,t.type==="radio"&&e!=null){for(t=n;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<t.length;e++){var r=t[e];if(r!==n&&r.form===n.form){var i=aF(r);if(!i)throw Error(ft(90));A7(r),oR(r,i)}}}break;case"textarea":F7(n,t);break;case"select":e=t.value,e!=null&&Zx(n,!!t.multiple,e,!1)}};M7=d6;z7=f0;var d$={usingClientEntryPoint:!1,Events:[q_,zx,aF,B7,I7,d6]},Aw={findFiberByHostInstance:gm,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},c$={bundleType:Aw.bundleType,version:Aw.version,rendererPackageName:Aw.rendererPackageName,rendererConfig:Aw.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Ef.ReactCurrentDispatcher,findHostInstanceByFiber:function(n){return n=N7(n),n===null?null:n.stateNode},findFiberByHostInstance:Aw.findFiberByHostInstance||a$,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var h2=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!h2.isDisabled&&h2.supportsFiber)try{rF=h2.inject(c$),Iu=h2}catch{}}Ql.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=d$;Ql.createPortal=function(n,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!m6(e))throw Error(ft(200));return o$(n,e,null,t)};Ql.createRoot=function(n,e){if(!m6(n))throw Error(ft(299));var t=!1,r="",i=x9;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(r=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=f6(n,1,!1,null,null,t,!1,r,i),n[jf]=e.current,gj(n.nodeType===8?n.parentNode:n),new g6(e)};Ql.findDOMNode=function(n){if(n==null)return null;if(n.nodeType===1)return n;var e=n._reactInternals;if(e===void 0)throw typeof n.render=="function"?Error(ft(188)):(n=Object.keys(n).join(","),Error(ft(268,n)));return n=N7(e),n=n===null?null:n.stateNode,n};Ql.flushSync=function(n){return f0(n)};Ql.hydrate=function(n,e,t){if(!mF(e))throw Error(ft(200));return yF(null,n,e,!0,t)};Ql.hydrateRoot=function(n,e,t){if(!m6(n))throw Error(ft(405));var r=t!=null&&t.hydratedSources||null,i=!1,o="",a=x9;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onRecoverableError!==void 0&&(a=t.onRecoverableError)),e=y9(e,null,n,1,t??null,i,!1,o,a),n[jf]=e.current,gj(n),r)for(n=0;n<r.length;n++)t=r[n],i=t._getVersion,i=i(t._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[t,i]:e.mutableSourceEagerHydrationData.push(t,i);return new gF(e)};Ql.render=function(n,e,t){if(!mF(e))throw Error(ft(200));return yF(null,n,e,!1,t)};Ql.unmountComponentAtNode=function(n){if(!mF(n))throw Error(ft(40));return n._reactRootContainer?(f0(function(){yF(null,null,n,!1,function(){n._reactRootContainer=null,n[jf]=null})}),!0):!1};Ql.unstable_batchedUpdates=d6;Ql.unstable_renderSubtreeIntoContainer=function(n,e,t,r){if(!mF(t))throw Error(ft(200));if(n==null||n._reactInternals===void 0)throw Error(ft(38));return yF(n,e,t,!1,r)};Ql.version="18.3.1-next-f1338f8080-20240426";function b9(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"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<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(n[r]=t[r])}return n},kj.apply(null,arguments)}var ug;(function(n){n.Pop="POP",n.Push="PUSH",n.Replace="REPLACE"})(ug||(ug={}));const Nz="popstate";function h$(n){n===void 0&&(n={});function e(r,i){let{pathname:o,search:a,hash:l}=r.location;return GR("",{pathname:o,search:a,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function t(r,i){return typeof i=="string"?i:LA(i)}return p$(e,t,null,n)}function es(n,e){if(n===!1||n===null||typeof n>"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<a.length;++c)l=C$(a[c],d);return l}function v9(n,e,t,r){e===void 0&&(e=[]),t===void 0&&(t=[]),r===void 0&&(r="");let i=(o,a,l)=>{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<r.length;++l){let d=r[l],c=l===r.length-1,u=o==="/"?e:e.slice(o.length)||"/",f=KR({path:d.relativePath,caseSensitive:d.caseSensitive,end:c},u),p=d.route;if(!f)return null;Object.assign(i,f.params),a.push({params:i,pathname:Cg([o,f.pathname]),pathnameBase:R$(Cg([o,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(o=Cg([o,f.pathnameBase]))}return a}function KR(n,e){typeof n=="string"&&(n={path:n,caseSensitive:!1,end:!0});let[t,r]=A$(n.path,n.caseSensitive,n.end),i=e.match(t);if(!i)return null;let o=i[0],a=o.replace(/(.)\/+$/,"$1"),l=i.slice(1);return{params:r.reduce((c,u,f)=>{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 <Link to="..."> 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<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(n[r]=t[r])}return n},_j.apply(null,arguments)}const xF=k.createContext(null),k9=k.createContext(null),Pf=k.createContext(null),bF=k.createContext(null),Uu=k.createContext({outlet:null,matches:[],isDataRoute:!1}),_9=k.createContext(null);function O$(n,e){let{relative:t}=e===void 0?{}:e;p1()||es(!1);let{basename:r,navigator:i}=k.useContext(Pf),{hash:o,pathname:a,search:l}=vF(n,{relative:t}),d=a;return r!=="/"&&(d=a==="/"?r:Cg([r,a])),i.createHref({pathname:d,search:l,hash:o})}function p1(){return k.useContext(bF)!=null}function E0(){return p1()||es(!1),k.useContext(bF).location}function C9(n){k.useContext(Pf).static||k.useLayoutEffect(n)}function go(){let{isDataRoute:n}=k.useContext(Uu);return n?J$():L$()}function L$(){p1()||es(!1);let n=k.useContext(xF),{basename:e,future:t,navigator:r}=k.useContext(Pf),{matches:i}=k.useContext(Uu),{pathname:o}=E0(),a=JSON.stringify(x6(i,t.v7_relativeSplatPath)),l=k.useRef(!1);return C9(()=>{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<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(c=u),f.route.id){let{loaderData:p,errors:g}=t,m=f.route.loader&&p[f.route.id]===void 0&&(!g||g[f.route.id]===void 0);if(f.route.lazy||m){d=!0,c>=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<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(n[r]=t[r])}return n},NA.apply(null,arguments)}function D9(n,e){if(n==null)return{};var t={};for(var r in n)if({}.hasOwnProperty.call(n,r)){if(e.indexOf(r)!==-1)continue;t[r]=n[r]}return t}function sZ(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function oZ(n,e){return n.button===0&&(!e||e==="_self")&&!sZ(n)}function YR(n){return n===void 0&&(n=""),new URLSearchParams(typeof n=="string"||Array.isArray(n)||n instanceof URLSearchParams?n:Object.keys(n).reduce((e,t)=>{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<l;u++){const f=r?u:a[u],p=n[f],g=e[f];if(p===g){d[f]=p,(r?u<o:CZ.call(n,f))&&c++;continue}if(p===null||g===null||typeof p!="object"||typeof g!="object"){d[f]=g;continue}const m=P9(p,g,t+1);d[f]=m,m===p&&c++}return o===l&&c===o?n:d}function WA(n,e){if(!e||Object.keys(n).length!==Object.keys(e).length)return!1;for(const t in n)if(n[t]!==e[t])return!1;return!0}function $z(n){return Array.isArray(n)&&n.length===Object.keys(n).length}function ZR(n){if(!Zz(n))return!1;const e=n.constructor;if(e===void 0)return!0;const t=e.prototype;return!(!Zz(t)||!t.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(n)!==Object.prototype)}function Zz(n){return Object.prototype.toString.call(n)==="[object Object]"}function AZ(n){return new Promise(e=>{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"&&t<w||typeof w=="function"&&w(t,x);if(e||!b){p(x);return}t++,(C=n.onFail)==null||C.call(n,t,x),AZ(_).then(()=>c()?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<S)}return l};e.options.persister?e.fetchFn=()=>{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,z<I.aliases.length-1?", ":""]},H))]}),(I.order_email||I.account_number)&&s.jsxs("div",{style:Pt.poDetails,children:[I.order_email&&s.jsxs("span",{children:["Order email: ",I.order_email]}),I.account_number&&s.jsxs("span",{children:["Account #: ",I.account_number]})]}),s.jsxs("span",{style:Pt.date,children:["Added: ",new Date(I.created_at).toLocaleDateString()]})]}),s.jsxs("div",{style:Pt.cardActions,children:[s.jsx("button",{onClick:()=>P(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?"&#128065;":"&#128274;"}),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;_<y;_++)x.push(null);if(u)for(const _ of u.days)x.push(_);else for(let _=1;_<=v;_++)x.push(null);const w=_=>{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;He<Z&&(Z=He),Ge>ge&&(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<De;ee++)ue.push(null);for(let ee=1;ee<=qe;ee++)ue.push(new Date(i,a-1,ee));const Ze=new Map;return F==null||F.forEach(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<Ne+we;)Be.push([]);let Ve=!0;for(let Re=Ne;Re<Ne+we;Re++){for(const Le of Be[Re])if(!(X+5<=Le.start||Q>=Le.end+5)){Ve=!1;break}if(!Ve)break}if(Ve){for(let Re=Ne;Re<Ne+we;Re++)Be[Re].push({start:Q,end:X});st=!0}else Ne++}return{...K,gridRow:Ne,rowSpan:we,bookingStart:Q,bookingEnd:X}}),He=24,Ge=Be.length*He+20,ae=()=>{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;st<de.length-1;st++){const Ve=de[st].close,Re=de[st+1].open,Le=Math.floor(Ve/100)*60+Ve%100,rt=Math.floor(Re/100)*60+Re%100,$e=Le-ee*60,Je=rt-ee*60-$e;if(Je>0){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<t?6:0):e===i?(t-n)/r+2:(n-e)/r+4}function _6(n){const t=n.r/255,r=n.g/255,i=n.b/255,o=Math.max(t,r,i),a=Math.min(t,r,i),l=(o+a)/2;let d,c,u;return o!==a&&(u=o-a,c=l>.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<e.length;r++){for(a=l=e[r],i=0;i<t.length;i++)o=t[i],l=l.replace(o,cO[o]);o=parseInt(uO[a],16),n[l]=[o>>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;i<o;i++)e.call(t,n[i],i);else if(Yn(n))for(a=Object.keys(n),o=a.length,i=0;i<o;i++)e.call(t,n[a[i]],a[i])}function HA(n,e){let t,r,i,o;if(!n||!e||n.length!==e.length)return!1;for(t=0,r=n.length;t<r;++t)if(i=n[t],o=e[t],i.datasetIndex!==o.datasetIndex||i.index!==o.index)return!1;return!0}function qA(n){if(ki(n))return n.map(qA);if(Yn(n)){const e=Object.create(null),t=Object.keys(n),r=t.length;let i=0;for(;i<r;++i)e[t[i]]=qA(n[t[i]]);return e}return n}function Y9(n){return["__proto__","prototype","constructor"].indexOf(n)===-1}function dee(n,e,t,r){if(!Y9(n))return;const i=e[n],o=t[n];Yn(i)&&Yn(o)?Fj(i,o,r):e[n]=qA(o)}function Fj(n,e,t){const r=ki(e)?e:[e],i=r.length;if(!Yn(n))return n;t=t||{};const o=t.merger||dee;let a;for(let l=0;l<i;++l){if(a=r[l],!Yn(a))continue;const d=Object.keys(a);for(let c=0,u=d.length;c<u;++c)o(d[c],n,a,t)}return n}function US(n,e){return Fj(n,e,{merger:cee})}function cee(n,e,t){if(!Y9(n))return;const r=e[n],i=t[n];Yn(r)&&Yn(i)?US(r,i):Object.prototype.hasOwnProperty.call(e,n)||(e[n]=qA(i))}const fO={"":n=>n,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)<t}function gO(n){const e=Math.round(n);n=HS(n,e,n/1e3)?e:n;const t=Math.pow(10,Math.floor(Q9(n))),r=n/t;return(r<=1?1:r<=2?2:r<=5?5:10)*t}function gee(n){const e=[],t=Math.sqrt(n);let r;for(r=1;r<t;r++)n%r===0&&(e.push(r),e.push(n/r));return t===(t|0)&&e.push(t),e.sort((i,o)=>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;r<i;r++)o=n[r][t],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function fo(n){return n*(Or/180)}function $9(n){return n*(180/Or)}function mO(n){if(!sl(n))return;let e=1,t=0;for(;Math.round(n*e)/e!==n;)e*=10,t++;return t}function hB(n,e){const t=e.x-n.x,r=e.y-n.y,i=Math.sqrt(t*t+r*r);let o=Math.atan2(r,t);return o<-.5*Or&&(o+=Eo),{angle:o,distance:i}}function r1(n,e){return Math.sqrt(Math.pow(e.x-n.x,2)+Math.pow(e.y-n.y,2))}function bee(n,e){return(n-e+pee)%Eo-Or}function Yf(n){return(n%Eo+Eo)%Eo}function KA(n,e,t,r){const i=Yf(n),o=Yf(e),a=Yf(t),l=Yf(o-i),d=Yf(a-i),c=Yf(i-o),u=Yf(i-a);return i===o||i===a||r&&o===a||l>d&&c<u}function Wl(n,e,t){return Math.max(e,Math.min(t,n))}function vee(n){return Wl(n,-32768,32767)}function bm(n,e,t,r=1e-6){return n>=Math.min(e,t)-r&&n<=Math.max(e,t)+r}function D6(n,e,t){t=t||(a=>n[a]<e);let r=n.length-1,i=0,o;for(;r-i>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 o<t||o===t&&n[i+1][e]===t}:i=>n[i][e]<t),wee=(n,e,t)=>D6(n,t,r=>n[r][e]>=t);function See(n,e,t){let r=0,i=n.length;for(;r<i&&n[r]<e;)r++;for(;i>r&&n[i-1]>t;)i--;return r>0||i<n.length?n.slice(r,i):n}const Z9=["push","pop","shift","splice","unshift"];function jee(n,e){if(n._chartjs){n._chartjs.listeners.push(e);return}Object.defineProperty(n,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),Z9.forEach(t=>{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;r<i;++r){const o=t[r];n=n[o]||(n[o]=Object.create(null))}return n}function lP(n,e,t){return typeof e=="string"?Fj(VS(n,e),t):Fj(VS(n,""),e)}class Mee{constructor(e,t){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=r=>r.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.x<e.right+t&&n.y>e.top-t&&n.y<e.bottom+t}function wF(n,e){n.save(),n.beginPath(),n.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),n.clip()}function SF(n){n.restore()}function Oee(n,e,t,r,i){if(!e)return n.lineTo(t.x,t.y);if(i==="middle"){const o=(e.x+t.x)/2;n.lineTo(o,e.y),n.lineTo(o,t.y)}else i==="after"!=!!r?n.lineTo(e.x,t.y):n.lineTo(t.x,e.y);n.lineTo(t.x,t.y)}function Lee(n,e,t,r){if(!e)return n.lineTo(t.x,t.y);n.bezierCurveTo(r?e.cp1x:e.cp2x,r?e.cp1y:e.cp2y,r?t.cp2x:t.cp1x,r?t.cp2y:t.cp1y,t.x,t.y)}function Nee(n,e){e.translation&&n.translate(e.translation[0],e.translation[1]),Ur(e.rotation)||n.rotate(e.rotation),e.color&&(n.fillStyle=e.color),e.textAlign&&(n.textAlign=e.textAlign),e.textBaseline&&(n.textBaseline=e.textBaseline)}function Wee(n,e,t,r,i){if(i.strikethrough||i.underline){const o=n.measureText(r),a=e-o.actualBoundingBoxLeft,l=e+o.actualBoundingBoxRight,d=t-o.actualBoundingBoxAscent,c=t+o.actualBoundingBoxDescent,u=i.strikethrough?(d+c)/2:c;n.strokeStyle=n.fillStyle,n.beginPath(),n.lineWidth=i.decorationWidth||2,n.moveTo(a,u),n.lineTo(l,u),n.stroke()}}function Uee(n,e){const t=n.fillStyle;n.fillStyle=e.color,n.fillRect(e.left,e.top,e.width,e.height),n.fillStyle=t}function Ej(n,e,t,r,i,o={}){const a=ki(e)?e:[e],l=o.strokeWidth>0&&o.strokeColor!=="";let d,c;for(n.save(),n.font=i.string,Nee(n,o),d=0;d<a.length;++d)c=a[d],o.backdrop&&Uee(n,o.backdrop),l&&(o.strokeColor&&(n.strokeStyle=o.strokeColor),Ur(o.strokeWidth)||(n.lineWidth=o.strokeWidth),n.strokeText(c,t,r,o.maxWidth)),n.fillText(c,t,r,o.maxWidth),Wee(n,t,r,c,o),r+=Number(i.lineHeight);n.restore()}function Pj(n,e){const{x:t,y:r,w:i,h:o,radius:a}=e;n.arc(t+a.topLeft,r+a.topLeft,a.topLeft,1.5*Or,Or,!0),n.lineTo(t,r+o-a.bottomLeft),n.arc(t+a.bottomLeft,r+o-a.bottomLeft,a.bottomLeft,Or,Po,!0),n.lineTo(t+i-a.bottomRight,r+o),n.arc(t+i-a.bottomRight,r+o-a.bottomRight,a.bottomRight,Po,0,!0),n.lineTo(t+i,r+a.topRight),n.arc(t+i-a.topRight,r+a.topRight,a.topRight,0,-Po,!0),n.lineTo(t+a.topLeft,r)}const Hee=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,qee=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function Vee(n,e){const t=(""+n).match(Hee);if(!t||t[1]==="normal")return e*1.2;switch(n=+t[2],t[3]){case"px":return n;case"%":n/=100;break}return e*n}const Gee=n=>+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;i<o;++i)if(a=n[i],a!==void 0&&a!==void 0)return a}function Kee(n,e,t){const{min:r,max:i}=n,o=X9(e,(i-r)/2),a=(l,d)=>t&&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)=>e<n.length&&!n[e].skip&&n[e],cU=n=>n==="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<r-1;++u)if(d=c,c=s1(n,u+1),!(!d||!c)){if(HS(e[u],0,rte)){t[u]=t[u+1]=0;continue}i=t[u]/e[u],o=t[u+1]/e[u],l=Math.pow(i,2)+Math.pow(o,2),!(l<=9)&&(a=3/Math.sqrt(l),t[u]=i*a*e[u],t[u+1]=o*a*e[u])}}function ote(n,e,t="x"){const r=cU(t),i=n.length;let o,a,l,d=s1(n,0);for(let c=0;c<i;++c){if(a=l,l=d,d=s1(n,c+1),!l)continue;const u=l[t],f=l[r];a&&(o=(u-a[t])/3,l[`cp1${t}`]=u-o,l[`cp1${r}`]=f-o*e[c]),d&&(o=(d[t]-u)/3,l[`cp2${t}`]=u+o,l[`cp2${r}`]=f+o*e[c])}}function ate(n,e="x"){const t=cU(e),r=n.length,i=Array(r).fill(0),o=Array(r);let a,l,d,c=s1(n,0);for(a=0;a<r;++a)if(l=d,d=c,c=s1(n,a+1),!!d){if(c){const u=c[e]-d[e];i[a]=u!==0?(c[t]-d[t])/u:0}o[a]=l?c?zu(i[a-1])!==zu(i[a])?0:(i[a-1]+i[a])/2:i[a-1]:i[a]}ste(n,i,o),ote(n,o,e)}function b2(n,e,t){return Math.max(Math.min(n,t),e)}function lte(n,e){let t,r,i,o,a,l=Dj(n[0],e);for(t=0,r=n.length;t<r;++t)a=o,o=l,l=t<r-1&&Dj(n[t+1],e),o&&(i=n[t],a&&(i.cp1x=b2(i.cp1x,e.left,e.right),i.cp1y=b2(i.cp1y,e.top,e.bottom)),l&&(i.cp2x=b2(i.cp2x,e.left,e.right),i.cp2y=b2(i.cp2y,e.top,e.bottom)))}function dte(n,e,t,r,i){let o,a,l,d;if(e.spanGaps&&(n=n.filter(c=>!c.skip)),e.cubicInterpolationMode==="monotone")ate(n,i);else{let c=r?n[n.length-1]:n[0];for(o=0,a=n.length;o<a;++o)l=n[o],d=ite(c,l,n[Math.min(o+1,a-(r?0:1))%a],e.tension),l.cp1x=d.previous.x,l.cp1y=d.previous.y,l.cp2x=d.next.x,l.cp2y=d.next.y,c=l}e.capBezierPoints&&lte(n,t)}function z6(){return typeof window<"u"&&typeof document<"u"}function O6(n){let e=n.parentNode;return e&&e.toString()==="[object ShadowRoot]"&&(e=e.host),e}function XA(n,e,t){let r;return typeof n=="string"?(r=parseInt(n,10),n.indexOf("%")!==-1&&(r=r/100*e.parentNode[t])):r=n,r}const jF=n=>n.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;p<g&&a(l(e[c%d][r]),i,o);++p)c--,u--;c%=d,u%=d}return u<c&&(u+=d),{start:c,end:u,loop:f,style:n.style}}function Ste(n,e,t){if(!t)return[n];const{property:r,start:i,end:o}=t,a=e.length,{compare:l,between:d,normalize:c}=fU(r),{start:u,end:f,loop:p,style:g}=wte(n,e,t),m=[];let y=!1,v=null,x,w,S;const _=()=>d(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;i<r.length;i++){const o=Ste(r[i],n.points,e);o.length&&t.push(...o)}return t}function kte(n,e,t,r){let i=0,o=e-1;if(t&&!r)for(;i<e&&!n[i].skip;)i++;for(;i<e&&n[i].skip;)i++;for(i%=e,t&&(o+=i);o>i&&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=l<a?l+i:l,c=!!n._fullLoop&&a===0&&l===i-1;return FO(n,_te(t,a,d,c),t,e)}function FO(n,e,t,r){return!r||!r.setContext||!t?e:Ate(n,e,t,r)}function Ate(n,e,t,r){const i=n._chart.getContext(),o=DO(n.options),{_datasetIndex:a,options:{spanGaps:l}}=n,d=t.length,c=[];let u=o,f=e[0].start,p=f;function g(m,y,v,x){const w=l?-1:1;if(m!==y){for(m+=d;t[m%d].skip;)m-=w;for(;t[y%d].skip;)y+=w;m%d!==y%d&&(c.push({start:m%d,end:y%d,loop:v,style:x}),u=x,f=y%d)}}for(const m of e){f=l?f:m.start;let y=t[f%d],v;for(p=f+1;p<=m.end;p++){const x=t[p%d];v=DO(r.setContext(P0(i,{type:"segment",p0:y,p1:x,p0DataIndex:(p-1)%d,p1DataIndex:p%d,datasetIndex:a}))),Tte(v,u)&&g(f,p-1,m.loop,u),y=x,u=v}f<p-1&&g(f,p-1,m.loop,u)}return c}function DO(n){return{backgroundColor:n.backgroundColor,borderCapStyle:n.borderCapStyle,borderDash:n.borderDash,borderDashOffset:n.borderDashOffset,borderJoinStyle:n.borderJoinStyle,borderWidth:n.borderWidth,borderColor:n.borderColor}}function Tte(n,e){if(!e)return!1;const t=[],r=function(i,o){return P6(o)?(t.includes(o)||t.push(o),t.indexOf(o)):o};return JSON.stringify(n,r)!==JSON.stringify(e,r)}function v2(n,e,t){return n.options.clip?n[t]:e[t]}function Fte(n,e){const{xScale:t,yScale:r}=n;return t&&r?{left:v2(t,e,"left"),right:v2(t,e,"right"),top:v2(r,e,"top"),bottom:v2(r,e,"bottom")}:e}function Dte(n,e){const t=e._clip;if(t.disabled)return!1;const r=Fte(e,n.chartArea);return{left:t.left===!1?0:r.left-(t.left===!0?0:t.left),right:t.right===!1?n.width:r.right+(t.right===!0?0:t.right),top:t.top===!1?0:r.top-(t.top===!0?0:t.top),bottom:t.bottom===!1?n.height:r.bottom+(t.bottom===!0?0:t.bottom)}}/*!
* Chart.js v4.5.1
* https://www.chartjs.org
* (c) 2025 Chart.js Contributors
* Released under the MIT License
*/class Ete{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(e,t,r,i){const o=t.listeners[i],a=t.duration;o.forEach(l=>l({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||t<r),!this._active){this._target[i]=l,this._notify(!0);return}if(t<0){this._target[i]=o;return}d=t/r%2,d=a&&d>1?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<r.length;i++)r[i][t]()}}class L6{constructor(e,t){this._chart=e,this._properties=new Map,this.configure(t)}configure(e){if(!Yn(e))return;const t=Object.keys(hs.animation),r=this._properties;Object.getOwnPropertyNames(e).forEach(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;i<r.length;i++){const o=n[r[i]];o&&o.active()&&t.push(o.wait())}return Promise.all(t)}function Ite(n,e){if(!e)return;let t=n.options;if(!t){n.options=e;return}return t.$shared&&(n.options=t=Object.assign({},t,{$shared:!1,$animations:{}})),t}function PO(n,e){const t=n&&n.options||{},r=t.reverse,i=t.min===void 0?e:0,o=t.max===void 0?e:0;return{start:r?o:i,end:r?i:o}}function Mte(n,e,t){if(t===!1)return!1;const r=PO(n,t),i=PO(e,t);return{top:i.end,right:r.end,bottom:i.start,left:r.start}}function zte(n){let e,t,r,i;return Yn(n)?(e=n.top,t=n.right,r=n.bottom,i=n.left):e=t=r=i=n,{top:e,right:t,bottom:r,left:i,disabled:n===!1}}function pU(n,e){const t=[],r=n._getSortedDatasetMetas(e);let i,o;for(i=0,o=r.length;i<o;++i)t.push(r[i].index);return t}function RO(n,e,t,r={}){const i=n.keys,o=r.mode==="single";let a,l,d,c;if(e===null)return;let u=!1;for(a=0,l=i.length;a<l;++a){if(d=+i[a],d===t){if(u=!0,r.all)continue;break}c=n.values[d],sl(c)&&(o||e===0||zu(e)===zu(c))&&(e+=c)}return!u&&!r.all?0:e}function Ote(n,e){const{iScale:t,vScale:r}=e,i=t.axis==="x"?"x":"y",o=r.axis==="x"?"x":"y",a=Object.keys(n),l=new Array(a.length);let d,c,u;for(d=0,c=a.length;d<c;++d)u=a[d],l[d]={[i]:u,[o]:n[u]};return l}function dP(n,e){const t=n&&n.options.stacked;return t||t===void 0&&e.stack!==void 0}function Lte(n,e,t){return`${n.id}.${e.id}.${t.stack||t.type}`}function Nte(n){const{min:e,max:t,minDefined:r,maxDefined:i}=n.getUserBounds();return{min:r?e:Number.NEGATIVE_INFINITY,max:i?t:Number.POSITIVE_INFINITY}}function Wte(n,e,t){const r=n[e]||(n[e]={});return r[t]||(r[t]={})}function BO(n,e,t,r){for(const i of e.getMatchingVisibleMetas(r).reverse()){const o=n[i.index];if(t&&o>0||!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;g<f;++g){const m=e[g],{[d]:y,[c]:v}=m,x=m._stacks||(m._stacks={});p=x[c]=Wte(i,u,y),p[l]=v,p._top=BO(p,a,!0,r.type),p._bottom=BO(p,a,!1,r.type);const w=p._visualValues||(p._visualValues={});w[l]=v}}function cP(n,e){const t=n.scales;return Object.keys(t).filter(r=>t[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]<c[l];for(u=0;u<t;++u)r._parsed[u+e]=f=p[u],d&&(g()&&(d=!1),c=f);r._sorted=d}a&&IO(this,p)}parsePrimitiveData(e,t,r,i){const{iScale:o,vScale:a}=e,l=o.axis,d=a.axis,c=o.getLabels(),u=o===a,f=new Array(i);let p,g,m;for(p=0,g=i;p<g;++p)m=p+r,f[p]={[l]:u||o.parse(c[m],m),[d]:a.parse(t[m],m)};return f}parseArrayData(e,t,r,i){const{xScale:o,yScale:a}=e,l=new Array(i);let d,c,u,f;for(d=0,c=i;d<c;++d)u=d+r,f=t[u],l[d]={x:o.parse(f[0],u),y:a.parse(f[1],u)};return l}parseObjectData(e,t,r,i){const{xScale:o,yScale:a}=e,{xAxisKey:l="x",yAxisKey:d="y"}=this._parsing,c=new Array(i);let u,f,p,g;for(u=0,f=i;u<f;++u)p=u+r,g=t[p],c[u]={x:o.parse(g0(g,l),p),y:a.parse(g0(g,d),p)};return c}getParsed(e){return this._cachedMeta._parsed[e]}getDataElement(e){return this._cachedMeta.data[e]}applyStack(e,t,r){const i=this.chart,o=this._cachedMeta,a=t[e.axis],l={keys:pU(i,!0),values:t._stacks[e.axis]._visualValues};return RO(l,a,o.index,{mode:r})}updateRangeFromParsed(e,t,r,i){const o=r[t.axis];let a=o===null?NaN:o;const l=i&&r._stacks[t.axis];i&&l&&(i.values=l,a=RO(i,o,this._cachedMeta.index)),e.min=Math.min(e.min,a),e.max=Math.max(e.max,a)}getMinMax(e,t){const r=this._cachedMeta,i=r._parsed,o=r._sorted&&e===r.iScale,a=i.length,l=this._getOtherScale(e),d=qte(t,r,this.chart),c={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:u,max:f}=Nte(l);let p,g;function m(){g=i[p];const y=g[l.axis];return!sl(g[e.axis])||u>y||f<y}for(p=0;p<a&&!(!m()&&(this.updateRangeFromParsed(c,e,g,d),o));++p);if(o){for(p=a-1;p>=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<o;++i)a=t[i][e.axis],sl(a)&&r.push(a);return r}getMaxOverflow(){return!1}getLabelAndValue(e){const t=this._cachedMeta,r=t.iScale,i=t.vScale,o=this.getParsed(e);return{label:r?""+r.getLabelForValue(o[r.axis]):"",value:i?""+i.getLabelForValue(o[i.axis]):""}}_update(e){const t=this._cachedMeta;this.update(e||"default"),t._clip=zte(In(this.options.clip,Mte(t.xScale,t.yScale,this.getMaxOverflow())))}update(e){}draw(){const e=this._ctx,t=this.chart,r=this._cachedMeta,i=r.data||[],o=t.chartArea,a=[],l=this._drawStart||0,d=this._drawCount||i.length-l,c=this.options.drawActiveElementsOnTop;let u;for(r.dataset&&r.dataset.draw(e,o,l,d),u=l;u<l+d;++u){const f=i[u];f.hidden||(f.active&&c?a.push(f):f.draw(e,o))}for(u=0;u<a.length;++u)a[u].draw(e,o)}getStyle(e,t){const r=t?"active":"default";return e===void 0&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(r):this.resolveDataElementOptions(e||0,r)}getContext(e,t,r){const i=this.getDataset();let o;if(e>=0&&e<this._cachedMeta.data.length){const a=this._cachedMeta.data[e];o=a.$context||(a.$context=Hte(this.getContext(),e,a)),o.parsed=this.getParsed(e),o.raw=i.data[e],o.index=o.dataIndex=e}else o=this.$context||(this.$context=Ute(this.chart.getContext(),this.index)),o.dataset=i,o.index=o.datasetIndex=this.index;return o.active=!!t,o.mode=r,o}resolveDatasetElementOptions(e){return this._resolveElementOptions(this.datasetElementType.id,e)}resolveDataElementOptions(e,t){return this._resolveElementOptions(this.dataElementType.id,t,e)}_resolveElementOptions(e,t="default",r){const i=t==="active",o=this._cachedDataOpts,a=e+"-"+t,l=o[a],d=this.enableOptionSharing&&ol(r);if(l)return MO(l,d);const c=this.chart.config,u=c.datasetElementScopeKeys(this._type,e),f=i?[`${e}Hover`,"hover",e,""]:[e,""],p=c.getOptionScopes(this.getDataset(),u),g=Object.keys(hs.elements[e]),m=()=>this.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<i&&this._removeElements(o,i-o)}_insertElements(e,t,r=!0){const i=this._cachedMeta,o=i.data,a=e+t;let l;const d=c=>{for(c.length+=t,l=c.length-1;l>=a;l--)c[l]=c[l-t]};for(d(o),l=e;l<a;++l)o[l]=new this.dataElementType;this._parsing&&d(i._parsed),this.parse(e,t),r&&this.updateElements(o,e,t,"reset")}updateElements(e,t,r,i){}_removeElements(e,t){const r=this._cachedMeta;if(this._parsing){const i=r._parsed.splice(e,t);r._stacked&&Tw(r,i)}r.data.splice(e,t)}_sync(e){if(this._parsing)this._syncList.push(e);else{const[t,r,i]=e;this[t](r,i)}this.chart._dataChanges.push([this.index,...e])}_onDataPush(){const e=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-e,e])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(e,t){t&&this._sync(["_removeElements",e,t]);const r=arguments.length-2;r&&this._sync(["_insertElements",e,r])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}ve(l0,"defaults",{}),ve(l0,"datasetElementType",null),ve(l0,"dataElementType",null);function Vte(n,e){if(!n._cache.$bar){const t=n.getMatchingVisibleMetas(e);let r=[];for(let i=0,o=t.length;i<o;i++)r=r.concat(t[i].controller.getAllParsedValues(n));n._cache.$bar=J9(r.sort((i,o)=>i-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;i<o;++i)a=e.getPixelForValue(t[i]),d();for(l=void 0,i=0,o=e.ticks.length;i<o;++i)a=e.getPixelForTick(i),d();return r}function Kte(n,e,t,r){const i=t.barThickness;let o,a;return Ur(i)?(o=e.min*t.categoryPercentage,a=t.barPercentage):(o=i*r,a=1),{chunk:o/r,ratio:a,start:e.pixels[n]-o/2}}function Xte(n,e,t,r){const i=e.pixels,o=i[n];let a=n>0?i[n-1]:null,l=n<i.length-1?i[n+1]:null;const d=t.categoryPercentage;a===null&&(a=o-(l===null?e.end-e.start:l-o)),l===null&&(l=o+o-a);const c=o-(o-Math.min(a,l))/2*d;return{chunk:Math.abs(l-a)/2*d/r,ratio:t.barPercentage,start:c}}function Yte(n,e,t,r){const i=t.parse(n[0],r),o=t.parse(n[1],r),a=Math.min(i,o),l=Math.max(i,o);let d=a,c=l;Math.abs(a)>Math.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<u;++c)p=e[c],f={},f[i.axis]=l||i.parse(a[c],c),d.push(gU(p,f,o,c));return d}function hP(n){return n&&n.barStart!==void 0&&n.barEnd!==void 0}function Qte(n,e,t){return n!==0?zu(n):(e.isHorizontal()?1:-1)*(e.min>=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.base<n.y,t="bottom",r="top"),e?(i="end",o="start"):(i="start",o="end"),{start:t,end:r,reverse:e,top:i,bottom:o}}function Zte(n,e,t,r){let i=e.borderSkipped;const o={};if(!i){n.borderSkipped=o;return}if(i===!0){n.borderSkipped={top:!0,right:!0,bottom:!0,left:!0};return}const{start:a,end:l,reverse:d,top:c,bottom:u}=$te(n);i==="middle"&&t&&(n.enableBorderRadius=!0,(t._top||0)===r?i=c:(t._bottom||0)===r?i=u:(o[OO(u,a,l,d)]=!0,i=c)),o[OO(i,a,l,d)]=!0,n.borderSkipped=o}function OO(n,e,t,r){return r?(n=Jte(n,e,t),n=LO(n,t,e)):n=LO(n,e,t),n}function Jte(n,e,t){return n===e?t:n===t?e:n}function LO(n,e,t){return n==="start"?e:n==="end"?t:n}function ene(n,{inflateAmount:e},t){n.inflateAmount=e==="auto"?t===1?.33:0:e}class f5 extends l0{parsePrimitiveData(e,t,r,i){return zO(e,t,r,i)}parseArrayData(e,t,r,i){return zO(e,t,r,i)}parseObjectData(e,t,r,i){const{iScale:o,vScale:a}=e,{xAxisKey:l="x",yAxisKey:d="y"}=this._parsing,c=o.axis==="x"?l:d,u=a.axis==="x"?l:d,f=[];let p,g,m,y;for(p=r,g=r+i;p<g;++p)y=t[p],m={},m[o.axis]=o.parse(g0(y,c),p),f.push(gU(g0(y,u),m,a,p));return f}updateRangeFromParsed(e,t,r,i){super.updateRangeFromParsed(e,t,r,i);const o=r._custom;o&&t===this._cachedMeta.vScale&&(e.min=Math.min(e.min,o.min),e.max=Math.max(e.max,o.max))}getMaxOverflow(){return 0}getLabelAndValue(e){const t=this._cachedMeta,{iScale:r,vScale:i}=t,o=this.getParsed(e),a=o._custom,l=hP(a)?"["+a.start+", "+a.end+"]":""+i.getLabelForValue(o[i.axis]);return{label:""+r.getLabelForValue(o[r.axis]),value:l}}initialize(){this.enableOptionSharing=!0,super.initialize();const e=this._cachedMeta;e.stack=this.getDataset().stack}update(e){const t=this._cachedMeta;this.updateElements(t.data,0,t.data.length,e)}updateElements(e,t,r,i){const o=i==="reset",{index:a,_cachedMeta:{vScale:l}}=this,d=l.getBasePixel(),c=l.isHorizontal(),u=this._getRuler(),{sharedOptions:f,includeOptions:p}=this._getSharedOptions(t,i);for(let g=t;g<t+r;g++){const m=this.getParsed(g),y=o||Ur(m[l.axis])?{base:d,head:d}:this._calculateBarValuePixels(g),v=this._calculateBarIndexPixels(g,u),x=(m._stacks||{})[l.axis],w={horizontal:c,base:y.base,enableBorderRadius:!x||hP(m._custom)||a===x._top||a===x._bottom,x:c?y.head:v.center,y:c?v.center:y.head,height:c?v.size:Math.abs(y.size),width:c?Math.abs(y.size):v.size};p&&(w.options=f||this.resolveDataElementOptions(g,e[g].active?"active":i));const S=w.options||e[g].options;Zte(w,S,x,a),ene(w,S,u.ratio),this.updateElement(e[g],g,w,i)}}_getStacks(e,t){const{iScale:r}=this._cachedMeta,i=r.getMatchingVisibleMetas(this._type).filter(u=>u.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;o<a;++o)i.push(r.getPixelForValue(this.getParsed(o)[r.axis],o));const l=e.barThickness;return{min:l||Gte(t),pixels:i,start:r._startPixel,end:r._endPixel,stackCount:this._getStackCount(),scale:r,grouped:e.grouped,ratio:l?1:e.categoryPercentage*e.barPercentage}}_calculateBarValuePixels(e){const{_cachedMeta:{vScale:t,_stacked:r,index:i},options:{base:o,minBarLength:a}}=this,l=o||0,d=this.getParsed(e),c=d._custom,u=hP(c);let f=d[t.axis],p=0,g=r?this.applyStack(t,d,r):f,m,y;g!==f&&(p=g-f,g=f),u&&(f=c.barStart,g=c.barEnd-c.barStart,f!==0&&zu(f)!==zu(c.barEnd)&&(p=0),p+=f);const v=!Ur(o)&&!u?o:p;let x=t.getPixelForValue(v);if(this.chart.getDataVisibility(e)?m=t.getPixelForValue(p+g):m=x,y=m-x,Math.abs(y)<a){y=Qte(y,t,l)*a,f===l&&(x-=y/2);const w=t.getPixelForDecimal(0),S=t.getPixelForDecimal(1),_=Math.min(w,S),b=Math.max(w,S);x=Math.max(Math.min(x,b),_),m=x+y,r&&!u&&(d._stacks[t.axis]._visualValues[i]=t.getValueForPixel(m)-t.getValueForPixel(x))}if(x===t.getPixelForValue(l)){const w=zu(y)*t.getLineWidthForValue(l)/2;x+=w,y-=w}return{size:y,base:x,head:m,center:m+y/2}}_calculateBarIndexPixels(e,t){const r=t.scale,i=this.options,o=i.skipNull,a=In(i.maxBarThickness,1/0);let l,d;const c=this._getAxisCount();if(t.grouped){const u=o?this._getStackCount(e):t.stackCount,f=i.barThickness==="flex"?Xte(e,t,i,u*c):Kte(e,t,i,u*c),p=this.chart.options.indexAxis==="x"?this.getDataset().xAxisID:this.getDataset().yAxisID,g=this._getAxis().indexOf(In(p,this.getFirstScaleIdForIndexAxis())),m=this._getStackIndex(this.index,this._cachedMeta.stack,o?e:void 0)+g;l=f.start+f.chunk*m+f.chunk/2,d=Math.min(a,f.chunk*f.ratio)}else l=r.getPixelForValue(this.getParsed(e)[r.axis],e),d=Math.min(a,t.min*t.ratio);return{base:l-d/2,head:l+d/2,center:l,size:d}}draw(){const e=this._cachedMeta,t=e.vScale,r=e.data,i=r.length;let o=0;for(;o<i;++o)this.getParsed(o)[t.axis]!==null&&!r[o].hidden&&r[o].draw(this._ctx)}}ve(f5,"id","bar"),ve(f5,"defaults",{datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}}),ve(f5,"overrides",{scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}});function tne(n,e,t){let r=1,i=1,o=0,a=0;if(e<Eo){const l=n,d=l+e,c=Math.cos(l),u=Math.sin(l),f=Math.cos(d),p=Math.sin(d),g=(S,_,b)=>KA(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;a<l;++a)i._parsed[a]=o(a)}}_getRotation(){return fo(this.options.rotation-90)}_getCircumference(){return fo(this.options.circumference)}_getRotationExtents(){let e=Eo,t=-Eo;for(let r=0;r<this.chart.data.datasets.length;++r)if(this.chart.isDatasetVisible(r)&&this.chart.getDatasetMeta(r).type===this._type){const i=this.chart.getDatasetMeta(r).controller,o=i._getRotation(),a=i._getCircumference();e=Math.min(e,o),t=Math.max(t,o+a)}return{rotation:e,circumference:t-e}}update(e){const t=this.chart,{chartArea:r}=t,i=this._cachedMeta,o=i.data,a=this.getMaxBorderWidth()+this.getMaxOffset(o)+this.options.spacing,l=Math.max((Math.min(r.width,r.height)-a)/2,0),d=Math.min(lee(this.options.cutout,l),1),c=this._getRingWeight(this.index),{circumference:u,rotation:f}=this._getRotationExtents(),{ratioX:p,ratioY:g,offsetX:m,offsetY:y}=tne(f,u,d),v=(r.width-a)/p,x=(r.height-a)/g,w=Math.max(Math.min(v,x)/2,0),S=X9(this.options.radius,w),_=Math.max(S*d,0),b=(S-_)/this._getVisibleDatasetWeightTotal();this.offsetX=m*S,this.offsetY=y*S,i.total=this.calculateTotal(),this.outerRadius=S-b*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-b*c,0),this.updateElements(o,0,o.length,e)}_circumference(e,t){const r=this.options,i=this._cachedMeta,o=this._getCircumference();return t&&r.animation.animateRotate||!this.chart.getDataVisibility(e)||i._parsed[e]===null||i.data[e].hidden?0:this.calculateCircumference(i._parsed[e]*o/Eo)}updateElements(e,t,r,i){const o=i==="reset",a=this.chart,l=a.chartArea,c=a.options.animation,u=(l.left+l.right)/2,f=(l.top+l.bottom)/2,p=o&&c.animateScale,g=p?0:this.innerRadius,m=p?0:this.outerRadius,{sharedOptions:y,includeOptions:v}=this._getSharedOptions(t,i);let x=this._getRotation(),w;for(w=0;w<t;++w)x+=this._circumference(w,o);for(w=t;w<t+r;++w){const S=this._circumference(w,o),_=e[w],b={x:u+this.offsetX,y:f+this.offsetY,startAngle:x,endAngle:x+S,circumference:S,outerRadius:m,innerRadius:g};v&&(b.options=y||this.resolveDataElementOptions(w,_.active?"active":i)),x+=S,this.updateElement(_,w,b,i)}}calculateTotal(){const e=this._cachedMeta,t=e.data;let r=0,i;for(i=0;i<t.length;i++){const o=e._parsed[i];o!==null&&!isNaN(o)&&this.chart.getDataVisibility(i)&&!t[i].hidden&&(r+=Math.abs(o))}return r}calculateCircumference(e){const t=this._cachedMeta.total;return t>0&&!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;i<o;++i)if(r.isDatasetVisible(i)){a=r.getDatasetMeta(i),e=a.data,l=a.controller;break}}if(!e)return 0;for(i=0,o=e.length;i<o;++i)d=l.resolveDataElementOptions(i),d.borderAlign!=="inner"&&(t=Math.max(t,d.borderWidth||0,d.hoverBorderWidth||0));return t}getMaxOffset(e){let t=0;for(let r=0,i=e.length;r<i;++r){const o=this.resolveDataElementOptions(r);t=Math.max(t,o.offset||0,o.hoverOffset||0)}return t}_getRingWeightOffset(e){let t=0;for(let r=0;r<e;++r)this.chart.isDatasetVisible(r)&&(t+=this._getRingWeight(r));return t}_getRingWeight(e){return Math.max(In(this.chart.data.datasets[e].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}ve(eS,"id","doughnut"),ve(eS,"defaults",{datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"}),ve(eS,"descriptors",{_scriptable:e=>e!=="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<S;++b){const C=e[b],T=x?C:{};if(b<t||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;++l){const{index:c,data:u}=o[l],{lo:f,hi:p}=rne(o[l],e,a,i);for(let g=f;g<=p;++g){const m=u[g];m.skip||r(m,c,g)}}}function ine(n){const e=n.indexOf("x")!==-1,t=n.indexOf("y")!==-1;return function(r,i){const o=e?Math.abs(r.x-i.x):0,a=t?Math.abs(r.y-i.y):0;return Math.sqrt(Math.pow(o,2)+Math.pow(a,2))}}function fP(n,e,t,r,i){const o=[];return!i&&!n.isPointInArea(e)||kF(n,t,e,function(l,d,c){!i&&!Dj(l,n.chartArea,0)||l.inRange(e.x,e.y,r)&&o.push({element:l,datasetIndex:d,index:c})},!0),o}function sne(n,e,t,r){let i=[];function o(a,l,d){const{startAngle:c,endAngle:u}=a.getProps(["startAngle","endAngle"],r),{angle:f}=hB(a,{x:e.x,y:e.y});KA(f,c,u)&&i.push({element:a,datasetIndex:l,index:d})}return kF(n,t,e,o),i}function one(n,e,t,r,i,o){let a=[];const l=ine(t);let d=Number.POSITIVE_INFINITY;function c(u,f,p){const g=u.inRange(e.x,e.y,i);if(r&&!g)return;const m=u.getCenterPoint(i);if(!(!!o||n.isPointInArea(m))&&!g)return;const v=l(e,m);v<d?(a=[{element:u,datasetIndex:f,index:p}],d=v):v===d&&a.push({element:u,datasetIndex:f,index:p})}return kF(n,t,e,c),a}function pP(n,e,t,r,i,o){return!o&&!n.isPointInArea(e)?[]:t==="r"&&!r?sne(n,e,t,i):one(n,e,t,r,i,o)}function NO(n,e,t,r,i){const o=[],a=t==="x"?"inXRange":"inYRange";let l=!1;return kF(n,t,e,(d,c,u)=>{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;u<c.length;++u)l.push({element:c[u],datasetIndex:d,index:u})}return l},point(n,e,t,r){const i=om(e,n),o=t.axis||"xy",a=t.includeInvisible||!1;return fP(n,i,o,r,a)},nearest(n,e,t,r){const i=om(e,n),o=t.axis||"xy",a=t.includeInvisible||!1;return pP(n,i,o,t.intersect,r,a)},x(n,e,t,r){const i=om(e,n);return NO(n,i,"x",t.intersect,r)},y(n,e,t,r){const i=om(e,n);return NO(n,i,"y",t.intersect,r)}}};const mU=["left","top","right","bottom"];function Fw(n,e){return n.filter(t=>t.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;t<r;++t)i=n[t],{position:o,options:{stack:a,stackWeight:l=1}}=i,e.push({index:t,box:i,pos:o,horizontal:i.isHorizontal(),weight:i.weight,stack:a&&o+a,stackWeight:l});return e}function dne(n){const e={};for(const t of n){const{stack:r,pos:i,stackWeight:o}=t;if(!r||!mU.includes(i))continue;const a=e[r]||(e[r]={count:0,placed:0,weight:0,size:0});a.count++,a.weight+=o}return e}function cne(n,e){const t=dne(n),{vBoxMaxWidth:r,hBoxMaxHeight:i}=e;let o,a,l;for(o=0,a=n.length;o<a;++o){l=n[o];const{fullSize:d}=l.box,c=t[l.stack],u=c&&l.stackWeight/c.weight;l.horizontal?(l.width=u?u*r:d&&e.availableWidth,l.height=i):(l.width=r,l.height=u?u*i:d&&e.availableHeight)}return t}function une(n){const e=lne(n),t=Dw(e.filter(c=>c.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<a;++o){l=n[o],d=l.box,d.update(l.width||e.w,l.height||e.h,pne(l.horizontal,e));const{same:f,other:p}=hne(e,t,l,r);c|=f&&i.length,u=u||p,d.fullSize||i.push(l)}return c&&tS(i,e,t,r)||u}function w2(n,e,t,r,i){n.top=t,n.left=e,n.right=e+r,n.bottom=t+i,n.width=r,n.height=i}function HO(n,e,t,r){const i=t.padding;let{x:o,y:a}=e;for(const l of n){const d=l.box,c=r[l.stack]||{placed:0,weight:1},u=l.stackWeight/c.weight||1;if(l.horizontal){const f=e.w*u,p=c.size||d.height;ol(c.start)&&(a=c.start),d.fullSize?w2(d,i.left,a,t.outerWidth-i.right-i.left,p):w2(d,e.left+c.placed,a,f,p),c.start=a,c.placed+=f,a=d.bottom}else{const f=e.h*u,p=c.size||d.width;ol(c.start)&&(o=c.start),d.fullSize?w2(d,o,i.top,p,t.outerHeight-i.bottom-i.top):w2(d,o,e.top+c.placed,p,f),c.start=o,c.placed+=f,o=d.right}}e.x=o,e.y=a}var Ed={addBox(n,e){n.boxes||(n.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},n.boxes.push(e)},removeBox(n,e){const t=n.boxes?n.boxes.indexOf(e):-1;t!==-1&&n.boxes.splice(t,1)},configure(n,e,t){e.fullSize=t.fullSize,e.position=t.position,e.weight=t.weight},update(n,e,t,r){if(!n)return;const i=sa(n.options.layout.padding),o=Math.max(e-i.width,0),a=Math.max(t-i.height,0),l=une(n.boxes),d=l.vertical,c=l.horizontal;Yr(n.boxes,y=>{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<i.clientWidth&&t()},window),a=new ResizeObserver(l=>{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;f<p;f++)S2(e,c,u,o[f],o[f+1]);return S2(e,c,u,d,Ur(g)?e.length:d+g),c}return S2(e,c,u),c}function Dne(n){const e=n.options.offset,t=n._tickSize(),r=n._length/t+(e?0:1),i=n._maxLength/t;return Math.floor(Math.min(r,i))}function Ene(n,e,t){const r=Bne(n),i=e.length/t;if(!r)return Math.max(i,1);const o=gee(r);for(let a=0,l=o.length-1;a<l;a++){const d=o[a];if(d>i)return d}return Math.max(i,1)}function Pne(n){const e=[];let t,r;for(t=0,r=n.length;t<r;t++)n[t].major&&e.push(t);return e}function Rne(n,e,t,r){let i=0,o=t[0],a;for(r=Math.ceil(r),a=0;a<n.length;a++)a===o&&(e.push(n[a]),i++,o=t[i*r])}function S2(n,e,t,r,i){const o=In(r,0),a=Math.min(In(i,n.length),n.length);let l=0,d,c,u;for(t=Math.ceil(t),i&&(d=i-r,t=d/Math.floor(d/t)),u=o;u<0;)l++,u=Math.round(o+l*t);for(c=Math.max(o,0);c<a;c++)c===u&&(e.push(n[c]),l++,u=Math.round(o+l*t))}function Bne(n){const e=n.length;let t,r;if(e<2)return!1;for(r=n[0],t=1;t<e;++t)if(n[t]-n[t-1]!==r)return!1;return r}const Ine=n=>n==="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(;o<i;o+=r)t.push(n[Math.floor(o)]);return t}function Mne(n,e,t){const r=n.ticks.length,i=Math.min(e,r-1),o=n._startPixel,a=n._endPixel,l=1e-6;let d=n.getPixelForTick(i),c;if(!(t&&(r===1?c=Math.max(d-o,a-d):e===0?c=(n.getPixelForTick(1)-d)/2:c=(d-n.getPixelForTick(i-1))/2,d+=i<e?c:-c,d<o-l||d>a+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;o<i;++o)delete t.data[r[o]];r.splice(0,i)}})}function Ew(n){return n.drawTicks?n.tickLength:0}function YO(n,e){if(!n.display)return 0;const t=Us(n.font,e),r=sa(n.padding);return(ki(n.text)?n.text.length:1)*t.lineHeight+r.height}function One(n,e){return P0(n,{scale:e,type:"scale"})}function Lne(n,e,t){return P0(n,{tick:t,index:e,type:"tick"})}function Nne(n,e,t){let r=E6(n);return(t&&e!=="right"||!t&&e==="right")&&(r=Ine(r)),r}function Wne(n,e,t,r){const{top:i,left:o,bottom:a,right:l,chart:d}=n,{chartArea:c,scales:u}=d;let f=0,p,g,m;const y=a-i,v=l-o;if(n.isHorizontal()){if(g=ta(r,o,l),Yn(t)){const x=Object.keys(t)[0],w=t[x];m=u[x].getPixelForValue(w)+y-e}else t==="center"?m=(c.bottom+c.top)/2+y-e:m=GO(n,t,e);p=l-o}else{if(Yn(t)){const x=Object.keys(t)[0],w=t[x];g=u[x].getPixelForValue(w)-v+e}else t==="center"?g=(c.left+c.right)/2-v+e:g=GO(n,t,e);m=ta(r,a,i),f=t==="left"?-Po:Po}return{titleX:g,titleY:m,maxWidth:p,rotation:f}}class m1 extends Oo{constructor(e){super(),this.id=e.id,this.type=e.type,this.options=void 0,this.ctx=e.ctx,this.chart=e.chart,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._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(e){this.options=e.setContext(this.getContext()),this.axis=e.axis,this._userMin=this.parse(e.min),this._userMax=this.parse(e.max),this._suggestedMin=this.parse(e.suggestedMin),this._suggestedMax=this.parse(e.suggestedMax)}parse(e,t){return e}getUserBounds(){let{_userMin:e,_userMax:t,_suggestedMin:r,_suggestedMax:i}=this;return e=Hc(e,Number.POSITIVE_INFINITY),t=Hc(t,Number.NEGATIVE_INFINITY),r=Hc(r,Number.POSITIVE_INFINITY),i=Hc(i,Number.NEGATIVE_INFINITY),{min:Hc(e,r),max:Hc(t,i),minDefined:sl(e),maxDefined:sl(t)}}getMinMax(e){let{min:t,max:r,minDefined:i,maxDefined:o}=this.getUserBounds(),a;if(i&&o)return{min:t,max:r};const l=this.getMatchingVisibleMetas();for(let d=0,c=l.length;d<c;++d)a=l[d].controller.getMinMax(this,e),i||(t=Math.min(t,a.min)),o||(r=Math.max(r,a.max));return t=o&&t>r?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<this.ticks.length;this._convertTicksToLabels(d?XO(this.ticks,l):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),a.display&&(a.autoSkip||a.source==="auto")&&(this.ticks=Fne(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),d&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let e=this.options.reverse,t,r;this.isHorizontal()?(t=this.left,r=this.right):(t=this.top,r=this.bottom,e=!e),this._startPixel=t,this._endPixel=r,this._reversePixels=e,this._length=r-t,this._alignToPixels=this.options.alignToPixels}afterUpdate(){li(this.options.afterUpdate,[this])}beforeSetDimensions(){li(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){li(this.options.afterSetDimensions,[this])}_callHooks(e){this.chart.notifyPlugins(e,this.getContext()),li(this.options[e],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){li(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(e){const t=this.options.ticks;let r,i,o;for(r=0,i=e.length;r<i;r++)o=e[r],o.label=li(t.callback,[o.value,r,e],this)}afterTickToLabelConversion(){li(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){li(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const e=this.options,t=e.ticks,r=KO(this.ticks.length,e.ticks.maxTicksLimit),i=t.minRotation||0,o=t.maxRotation;let a=i,l,d,c;if(!this._isVisible()||!t.display||i>=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<r;t++)Ur(e[t].label)&&(e.splice(t,1),r--,t--);this.afterTickToLabelConversion()}_getLabelSizes(){let e=this._labelSizes;if(!e){const t=this.options.ticks.sampleSize;let r=this.ticks;t<r.length&&(r=XO(r,t)),this._labelSizes=e=this._computeLabelSizes(r,r.length,this.options.ticks.maxTicksLimit)}return e}_computeLabelSizes(e,t,r){const{ctx:i,_longestTextCache:o}=this,a=[],l=[],d=Math.floor(t/KO(t,r));let c=0,u=0,f,p,g,m,y,v,x,w,S,_,b;for(f=0;f<t;f+=d){if(m=e[f].label,y=this._resolveTickFontOptions(f),i.font=v=y.string,x=o[v]=o[v]||{data:{},gc:[]},w=y.lineHeight,S=_=0,!Ur(m)&&!ki(m))S=SO(i,x.data,x.gc,S,m),_=w;else if(ki(m))for(p=0,g=m.length;p<g;++p)b=m[p],!Ur(b)&&!ki(b)&&(S=SO(i,x.data,x.gc,S,b),_+=w);a.push(S),l.push(_),c=Math.max(S,c),u=Math.max(_,u)}zne(o,t);const C=a.indexOf(c),T=l.indexOf(u),F=A=>({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&&e<t.length){const r=t[e];return r.$context||(r.$context=Lne(this.getContext(),e,r))}return this.$context||(this.$context=One(this.chart.getContext(),this))}_tickSize(){const e=this.options.ticks,t=fo(this.labelRotation),r=Math.abs(Math.cos(t)),i=Math.abs(Math.sin(t)),o=this._getLabelSizes(),a=e.autoSkipPadding||0,l=o?o.widest.width+a:0,d=o?o.highest.height+a:0;return this.isHorizontal()?d*r>l*i?l/r:d/i:d*i<l*r?d/r:l/i}_isVisible(){const e=this.options.display;return e!=="auto"?!!e:this.getMatchingVisibleMetas().length>0}_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;S<f;S+=U){const M=this.getContext(S),I=o.setContext(M),H=l.setContext(M),z=I.lineWidth,G=I.color,te=H.dash||[],re=H.dashOffset,me=I.tickWidth,J=I.tickColor,ne=I.tickBorderDash||[],ye=I.tickBorderDashOffset;_=Mne(this,S,d),_!==void 0&&(b=tm(r,_,z),c?C=F=D=L=b:T=A=P=W=b,g.push({tx1:C,ty1:T,tx2:F,ty2:A,x1:D,y1:P,x2:L,y2:W,width:z,color:G,borderDash:te,borderDashOffset:re,tickWidth:me,tickColor:J,tickBorderDash:ne,tickBorderDashOffset:ye}))}return this._ticksLength=f,this._borderValue=w,g}_computeLabelItems(e){const t=this.axis,r=this.options,{position:i,ticks:o}=r,a=this.isHorizontal(),l=this.ticks,{align:d,crossAlign:c,padding:u,mirror:f}=o,p=Ew(r.grid),g=p+u,m=f?-u:g,y=-fo(this.labelRotation),v=[];let x,w,S,_,b,C,T,F,A,D,P,L,W="middle";if(i==="top")C=this.bottom-m,T=this._getXAxisLabelAlignment();else if(i==="bottom")C=this.top+m,T=this._getXAxisLabelAlignment();else if(i==="left"){const U=this._getYAxisLabelAlignment(p);T=U.textAlign,b=U.x}else if(i==="right"){const U=this._getYAxisLabelAlignment(p);T=U.textAlign,b=U.x}else if(t==="x"){if(i==="center")C=(e.top+e.bottom)/2+g;else if(Yn(i)){const U=Object.keys(i)[0],M=i[U];C=this.chart.scales[U].getPixelForValue(M)+g}T=this._getXAxisLabelAlignment()}else if(t==="y"){if(i==="center")b=(e.left+e.right)/2-g;else if(Yn(i)){const U=Object.keys(i)[0],M=i[U];b=this.chart.scales[U].getPixelForValue(M)}T=this._getYAxisLabelAlignment(p).textAlign}t==="y"&&(d==="start"?W="top":d==="end"&&(W="bottom"));const O=this._getLabelSizes();for(x=0,w=l.length;x<w;++x){S=l[x],_=S.label;const U=o.setContext(this.getContext(x));F=this.getPixelForTick(x)+o.labelOffset,A=this._resolveTickFontOptions(x),D=A.lineHeight,P=ki(_)?_.length:1;const M=P/2,I=U.color,H=U.textStrokeColor,z=U.textStrokeWidth;let G=T;a?(b=F,T==="inner"&&(x===w-1?G=this.options.reverse?"left":"right":x===0?G=this.options.reverse?"right":"left":G="center"),i==="top"?c==="near"||y!==0?L=-P*D+D/2:c==="center"?L=-O.highest.height/2-M*D+D:L=-O.highest.height+D/2:c==="near"||y!==0?L=D/2:c==="center"?L=O.highest.height/2-M*D:L=O.highest.height-P*D,f&&(L*=-1),y!==0&&!U.showLabelBackdrop&&(b+=D/2*Math.sin(y))):(C=F,L=(1-P)*D/2);let te;if(U.showLabelBackdrop){const re=sa(U.backdropPadding),me=O.heights[x],J=O.widths[x];let ne=L-re.top,ye=0-re.left;switch(W){case"middle":ne-=me/2;break;case"bottom":ne-=me;break}switch(T){case"center":ye-=J/2;break;case"right":ye-=J;break;case"inner":x===w-1?ye-=J:x>0&&(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<a;++o){const d=i[o];t.drawOnChartArea&&l({x:d.x1,y:d.y1},{x:d.x2,y:d.y2},d),t.drawTicks&&l({x:d.tx1,y:d.ty1},{x:d.tx2,y:d.ty2},{color:d.tickColor,width:d.tickWidth,borderDash:d.tickBorderDash,borderDashOffset:d.tickBorderDashOffset})}}drawBorder(){const{chart:e,ctx:t,options:{border:r,grid:i}}=this,o=r.setContext(this.getContext()),a=r.display?o.width:0;if(!a)return;const l=i.setContext(this.getContext(0)).lineWidth,d=this._borderValue;let c,u,f,p;this.isHorizontal()?(c=tm(e,this.left,a)-a/2,u=tm(e,this.right,l)+l/2,f=p=d):(f=tm(e,this.top,a)-a/2,p=tm(e,this.bottom,l)+l/2,c=u=d),t.save(),t.lineWidth=o.width,t.strokeStyle=o.color,t.beginPath(),t.moveTo(c,f),t.lineTo(u,p),t.stroke(),t.restore()}drawLabels(e){if(!this.options.ticks.display)return;const r=this.ctx,i=this._computeLabelArea();i&&wF(r,i);const o=this.getLabelItems(e);for(const a of o){const l=a.options,d=a.font,c=a.label,u=a.textOffset;Ej(r,c,0,u,d,l)}i&&SF(r)}drawTitle(){const{ctx:e,options:{position:t,title:r,reverse:i}}=this;if(!r.display)return;const o=Us(r.font),a=sa(r.padding),l=r.align;let d=o.lineHeight/2;t==="bottom"||t==="center"||Yn(t)?(d+=a.bottom,ki(r.text)&&(d+=o.lineHeight*(r.text.length-1))):d+=a.top;const{titleX:c,titleY:u,maxWidth:f,rotation:p}=Wne(this,d,t,l);Ej(e,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:p,textAlign:Nne(l,t,i),textBaseline:"middle",translation:[c,u]})}draw(e){this._isVisible()&&(this.drawBackground(),this.drawGrid(e),this.drawBorder(),this.drawTitle(),this.drawLabels(e))}_layers(){const e=this.options,t=e.ticks&&e.ticks.z||0,r=In(e.grid&&e.grid.z,-1),i=In(e.border&&e.border.z,0);return!this._isVisible()||this.draw!==m1.prototype.draw?[{z:t,draw: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<a;++o){const l=t[o];l[r]===this.id&&(!e||l.type===e)&&i.push(l)}return i}_resolveTickFontOptions(e){const t=this.options.ticks.setContext(this.getContext(e));return Us(t.font)}_maxDigits(){const e=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/e}}class j2{constructor(e,t,r){this.type=e,this.scope=t,this.override=r,this.items=Object.create(null)}isForType(e){return Object.prototype.isPrototypeOf.call(this.type.prototype,e.prototype)}register(e){const t=Object.getPrototypeOf(e);let r;qne(t)&&(r=this.register(t));const i=this.items,o=e.id,a=this.scope+"."+o;if(!o)throw new Error("class does not have id: "+e);return o in i||(i[o]=e,Une(e,a,r),this.override&&hs.override(e.id,e.overrides)),a}get(e){return this.items[e]}unregister(e){const t=this.items,r=e.id,i=this.scope;r in t&&delete t[r],i&&r in hs[i]&&(delete hs[i][r],this.override&&delete y0[r])}}function Une(n,e,t){const r=Fj(Object.create(null),[t?hs.get(t):{},hs.get(e),n.defaults]);hs.set(e,r),n.defaultRoutes&&Hne(e,n.defaultRoutes),n.descriptors&&hs.describe(e,n.descriptors)}function Hne(n,e){Object.keys(e).forEach(t=>{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;t<this._typedRegistries.length;t++){const r=this._typedRegistries[t];if(r.isForType(e))return r}return this.plugins}_get(e,t,r){const i=t.get(e);if(i===void 0)throw new Error('"'+e+'" is not a registered '+r+".");return i}}var Jc=new Vne;class Gne{constructor(){this._init=void 0}notify(e,t,r,i){if(t==="beforeInit"&&(this._init=this._createDescriptors(e,!0),this._notify(this._init,e,"install")),this._init===void 0)return;const o=i?this._descriptors(e).filter(i):this._descriptors(e),a=this._notify(o,e,t,r);return t==="afterDestroy"&&(this._notify(o,e,"stop"),this._notify(this._init,e,"uninstall"),this._init=void 0),a}_notify(e,t,r,i){i=i||{};for(const o of e){const a=o.plugin,l=a[r],d=[t,i,o.options];if(li(l,d,a)===!1&&i.cancelable)return!1}return!0}invalidate(){Ur(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(e){if(this._cache)return this._cache;const t=this._cache=this._createDescriptors(e);return this._notifyStateChanges(e),t}_createDescriptors(e,t){const r=e&&e.config,i=In(r.options&&r.options.plugins,{}),o=Kne(r);return i===!1&&!t?[]:Yne(e,o,i,t)}_notifyStateChanges(e){const t=this._oldCache||[],r=this._cache,i=(o,a)=>o.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;o<r.length;o++)t.push(Jc.getPlugin(r[o]));const i=n.plugins||[];for(let o=0;o<i.length;o++){const a=i[o];t.indexOf(a)===-1&&(t.push(a),e[a.id]=!0)}return{plugins:t,localIds:e}}function Xne(n,e){return!e&&n===!1?null:n===!0?{}:n}function Yne(n,{plugins:e,localIds:t},r,i){const o=[],a=n.getContext();for(const l of e){const d=l.id,c=Xne(r[d],i);c!==null&&o.push({plugin:l,options:Qne(n.config,{plugin:l,local:t[d]},c,a)})}return o}function Qne(n,{plugin:e,local:t},r,i){const o=n.pluginScopeKeys(e),a=n.getOptionScopes(r,o);return t&&e.defaults&&a.push(e.defaults),n.createResolver(a,i,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function gB(n,e){const t=hs.datasets[n]||{};return((e.datasets||{})[n]||{}).indexAxis||e.indexAxis||t.indexAxis||"x"}function $ne(n,e){let t=n;return n==="_index_"?t=e:n==="_value_"&&(t=e==="x"?"y":"x"),t}function Zne(n,e){return n===e?"_index_":"_value_"}function QO(n){if(n==="x"||n==="y"||n==="r")return n}function Jne(n){if(n==="top"||n==="bottom")return"x";if(n==="left"||n==="right")return"y"}function mB(n,...e){if(QO(n))return n;for(const t of e){const r=t.axis||Jne(t.position)||n.length>1&&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;i<r;++i)this._destroyDatasetMeta(i);e.splice(t,r-t)}this._sortedMetasets=e.slice(0).sort(tL("order","index"))}_removeUnreferencedMetasets(){const{_metasets:e,data:{datasets:t}}=this;e.length>t.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<i;r++){const o=t[r];let a=this.getDatasetMeta(r);const l=o.type||this.config.type;if(a.type&&a.type!==l&&(this._destroyDatasetMeta(r),a=this.getDatasetMeta(r)),a.type=l,a.indexAxis=o.indexAxis||gB(l,this.options),a.order=o.order||0,a.index=r,a.label=""+o.label,a.visible=this.isDatasetVisible(r),a.controller)a.controller.updateIndex(r),a.controller.linkScales();else{const d=Jc.getController(l),{datasetElementType:c,dataElementType:u}=hs.datasets[l];Object.assign(d,{dataElementType:Jc.getElement(u),datasetElementType:c&&Jc.getElement(c)}),a.controller=new d(this,r),e.push(a.controller)}}return this._updateMetasets(),e}_resetElements(){Yr(this.data.datasets,(e,t)=>{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<u;c++){const{controller:f}=this.getDatasetMeta(c),p=!i&&o.indexOf(f)===-1;f.buildOrUpdateElements(p),a=Math.max(+f.getMaxOverflow(),a)}a=this._minPadding=r.layout.autoPadding?a:0,this._updateLayout(a),i||Yr(o,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;o<t;o++)if(!pO(i,r(o)))return;return Array.from(i).map(o=>o.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<r;++t)this.getDatasetMeta(t).controller.configure();for(let t=0,r=this.data.datasets.length;t<r;++t)this._updateDataset(t,il(e)?e({datasetIndex:t}):e);this.notifyPlugins("afterDatasetsUpdate",{mode:e})}}_updateDataset(e,t){const r=this.getDatasetMeta(e),i={meta:r,index:e,mode:t,cancelable:!0};this.notifyPlugins("beforeDatasetUpdate",i)!==!1&&(r.controller._update(t),i.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",i))}render(){this.notifyPlugins("beforeRender",{cancelable:!0})!==!1&&(ch.has(this)?this.attached&&!ch.running(this)&&ch.start(this):(this.draw(),nL({chart:this})))}draw(){let e;if(this._resizeBeforeDraw){const{width:r,height:i}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(r,i)}if(this.clear(),this.width<=0||this.height<=0||this.notifyPlugins("beforeDraw",{cancelable:!0})===!1)return;const t=this._layers;for(e=0;e<t.length&&t[e].z<=0;++e)t[e].draw(this.chartArea);for(this._drawDatasets();e<t.length;++e)t[e].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(e){const t=this._sortedMetasets,r=[];let i,o;for(i=0,o=t.length;i<o;++i){const a=t[i];(!e||a.visible)&&r.push(a)}return r}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0})===!1)return;const e=this.getSortedVisibleDatasetMetas();for(let t=e.length-1;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;++e)this._destroyDatasetMeta(e)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:e,ctx:t}=this;this._stop(),this.config.clearCache(),e&&(this.unbindEvents(),jO(e,t),this.platform.releaseContext(t),this.canvas=null,this.ctx=null),delete m5[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...e){return this.canvas.toDataURL(...e)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const e=this._listeners,t=this.platform,r=(o,a)=>{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<d;++l){a=e[l];const c=a&&this.getDatasetMeta(a.datasetIndex).controller;c&&c[i+"HoverStyle"](a.element,a.datasetIndex,a.index)}}getActiveElements(){return this._active||[]}setActiveElements(e){const t=this._active||[],r=e.map(({datasetIndex:o,index:a})=>{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=i<a&&o<a||i>l&&o>l;return{count:r,start:d,loop:e.loop,ilen:c<d&&!u?r+c-d:c-d}}function fre(n,e,t,r){const{points:i,options:o}=e,{count:a,start:l,loop:d,ilen:c}=CU(i,t,r),u=hre(o);let{move:f=!0,reverse:p}=r||{},g,m,y;for(g=0;g<=c;++g)m=i[(l+(p?c-g:g))%a],!m.skip&&(f?(n.moveTo(m.x,m.y),f=!1):u(n,y,m,p,o.stepped),y=m);return d&&(m=i[(l+(p?c:0))%a],u(n,y,m,p,o.stepped)),!!d}function pre(n,e,t,r){const i=e.points,{count:o,start:a,ilen:l}=CU(i,t,r),{move:d=!0,reverse:c}=r||{};let u=0,f=0,p,g,m,y,v,x;const w=_=>(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?(b<y?y=b:b>v&&(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;c<u;++c){const{start:f,end:p}=a[c],g=o[f],m=o[p];if(g===m){l.push(g);continue}const y=Math.abs((i-g[t])/(m[t]-g[t])),v=d(g,m,y,r.stepped);v[t]=e[t],l.push(v)}return l.length===1?l[0]:l}pathSegment(e,t,r){return yB(this)(e,this,t,r)}path(e,t,r){const i=this.segments,o=yB(this);let a=this._loop;t=t||0,r=r||this.points.length-t;for(const l of i)a&=o(e,this,l,{start:t,end:t+r-1});return!!a}draw(e,t,r,i){const o=this.options||{};(this.points||[]).length&&o.borderWidth&&(e.save(),bre(e,this,r,i),e.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}ve(qx,"id","line"),ve(qx,"defaults",{borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0}),ve(qx,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"}),ve(qx,"descriptors",{_scriptable:!0,_indexable:e=>e!=="borderDash"&&e!=="fill"});function sL(n,e,t,r){const i=n.options,{[t]:o}=n.getProps([t],r);return Math.abs(e-o)<i.radius+i.hitRadius}class GS extends Oo{constructor(t){super();ve(this,"parsed");ve(this,"skip");ve(this,"stop");this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,r,i){const o=this.options,{x:a,y:l}=this.getProps(["x","y"],i);return Math.pow(t-a,2)+Math.pow(r-l,2)<Math.pow(o.hitRadius+o.radius,2)}inXRange(t,r){return sL(this,t,"x",r)}inYRange(t,r){return sL(this,t,"y",r)}getCenterPoint(t){const{x:r,y:i}=this.getProps(["x","y"],t);return{x:r,y:i}}size(t){t=t||this.options||{};let r=t.radius||0;r=Math.max(r,r&&t.hoverRadius||0);const i=r&&t.borderWidth||0;return(r+i)*2}draw(t,r){const i=this.options;this.skip||i.radius<.1||!Dj(this,r,this.size(i)/2)||(t.strokeStyle=i.borderColor,t.lineWidth=i.borderWidth,t.fillStyle=i.backgroundColor,pB(t,i,this.x,this.y))}getRange(){const t=this.options||{};return t.radius+t.hitRadius}}ve(GS,"id","point"),ve(GS,"defaults",{borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0}),ve(GS,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});function AU(n,e){const{x:t,y:r,base:i,width:o,height:a}=n.getProps(["x","y","base","width","height"],e);let l,d,c,u,f;return n.horizontal?(f=a/2,l=Math.min(t,i),d=Math.max(t,i),c=r-f,u=r+f):(f=o/2,l=t-f,d=t+f,c=Math.min(r,i),u=Math.max(r,i)),{left:l,top:c,right:d,bottom:u}}function pg(n,e,t,r){return n?0:Wl(e,t,r)}function vre(n,e,t){const r=n.options.borderWidth,i=n.borderSkipped,o=sU(r);return{t:pg(i.top,o.top,0,t),r:pg(i.right,o.right,0,e),b:pg(i.bottom,o.bottom,0,t),l:pg(i.left,o.left,0,e)}}function wre(n,e,t){const{enableBorderRadius:r}=n.getProps(["enableBorderRadius"]),i=n.options.borderRadius,o=o0(i),a=Math.min(e,t),l=n.borderSkipped,d=r||Yn(i);return{topLeft:pg(!d||l.top||l.left,o.topLeft,0,a),topRight:pg(!d||l.top||l.right,o.topRight,0,a),bottomLeft:pg(!d||l.bottom||l.left,o.bottomLeft,0,a),bottomRight:pg(!d||l.bottom||l.right,o.bottomRight,0,a)}}function Sre(n){const e=AU(n),t=e.right-e.left,r=e.bottom-e.top,i=vre(n,t/2,r/2),o=wre(n,t/2,r/2);return{outer:{x:e.left,y:e.top,w:t,h:r,radius:o},inner:{x:e.left+i.l,y:e.top+i.t,w:t-i.l-i.r,h:r-i.t-i.b,radius:{topLeft:Math.max(0,o.topLeft-Math.max(i.t,i.l)),topRight:Math.max(0,o.topRight-Math.max(i.t,i.r)),bottomLeft:Math.max(0,o.bottomLeft-Math.max(i.b,i.l)),bottomRight:Math.max(0,o.bottomRight-Math.max(i.b,i.r))}}}}function mP(n,e,t,r){const i=e===null,o=t===null,l=n&&!(i&&o)&&AU(n,r);return l&&(i||bm(e,l.left,l.right))&&(o||bm(t,l.top,l.bottom))}function jre(n){return n.topLeft||n.topRight||n.bottomLeft||n.bottomRight}function kre(n,e){n.rect(e.x,e.y,e.w,e.h)}function yP(n,e,t={}){const r=n.x!==t.x?-e:0,i=n.y!==t.y?-e:0,o=(n.x+n.w!==t.x+t.w?e:0)-r,a=(n.y+n.h!==t.y+t.h?e:0)-i;return{x:n.x+r,y:n.y+i,w:n.w+o,h:n.h+a,radius:n.radius}}class y5 extends Oo{constructor(e){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,e&&Object.assign(this,e)}draw(e){const{inflateAmount:t,options:{borderColor:r,backgroundColor:i}}=this,{inner:o,outer:a}=Sre(this),l=jre(a.radius)?Pj:kre;e.save(),(a.w!==o.w||a.h!==o.h)&&(e.beginPath(),l(e,yP(a,t,o)),e.clip(),l(e,yP(o,-t,a)),e.fillStyle=r,e.fill("evenodd")),e.beginPath(),l(e,yP(o,t)),e.fillStyle=i,e.fill(),e.restore()}inRange(e,t,r){return mP(this,e,t,r)}inXRange(e,t){return mP(this,e,null,t)}inYRange(e,t){return mP(this,null,e,t)}getCenterPoint(e){const{x:t,y:r,base:i,horizontal:o}=this.getProps(["x","y","base","horizontal"],e);return{x:o?(t+i)/2:t,y:o?r:(r+i)/2}}getRange(e){return e==="x"?this.width/2:this.height/2}}ve(y5,"id","bar"),ve(y5,"defaults",{borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0}),ve(y5,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});const oL=(n,e)=>{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;r<o.length;++r)if(i=o[r],bm(e,i.left,i.left+i.width)&&bm(t,i.top,i.top+i.height))return this.legendItems[r]}return null}handleEvent(e){const t=this.options;if(!Fre(e.type,t))return;const r=this._getLegendItemAt(e.x,e.y);if(e.type==="mousemove"||e.type==="mouseout"){const i=this._hoveredItem,o=_re(i,r);i&&!o&&li(t.onLeave,[e,i,this],this),this._hoveredItem=r,r&&!o&&li(t.onHover,[e,r,this],this)}else r&&li(t.onClick,[e,r,this],this)}}function Cre(n,e,t,r,i){const o=Are(r,n,e,t),a=Tre(i,r,e.lineHeight);return{itemWidth:o,itemHeight:a}}function Are(n,e,t,r){let i=n.text;return i&&typeof i!="string"&&(i=i.reduce((o,a)=>o.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;e<t;++e){const l=n[e].element;if(l&&l.hasValue()){const d=l.tooltipPosition();r.add(d.x),i+=d.y,++o}}return o===0||r.size===0?!1:{x:[...r].reduce((l,d)=>l+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<a;++o){const d=n[o].element;if(d&&d.hasValue()){const c=d.getCenterPoint(),u=r1(e,c);u<i&&(i=u,l=d)}}if(l){const d=l.tooltipPosition();t=d.x,r=d.y}return{x:t,y:r}}};function Qc(n,e){return e&&(ki(e)?Array.prototype.push.apply(n,e):n.push(e)),n}function uh(n){return(typeof n=="string"||n instanceof String)&&n.indexOf(`
`)>-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 t<r/2?"top":t>n.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<r)return t[e.dataIndex]}return""},afterTitle:ih,beforeBody:ih,beforeLabel:ih,label(n){if(this&&this.options&&this.options.mode==="dataset")return n.label+": "+n.formattedValue||n.formattedValue;let e=n.dataset.label||"";e&&(e+=": ");const t=n.formattedValue;return Ur(t)||(e+=t),e},labelColor(n){const t=n.chart.getDatasetMeta(n.datasetIndex).controller.getStyle(n.dataIndex);return{borderColor:t.borderColor,backgroundColor:t.backgroundColor,borderWidth:t.borderWidth,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(n){const t=n.chart.getDatasetMeta(n.datasetIndex).controller.getStyle(n.dataIndex);return{pointStyle:t.pointStyle,rotation:t.rotation}},afterLabel:ih,afterBody:ih,beforeFooter:ih,footer:ih,afterFooter:ih};function za(n,e,t,r){const i=n[e].call(t,r);return typeof i>"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;d<c;++d)l.push(Ere(this.chart,t[d]));return e.filter&&(l=l.filter((u,f,p)=>e.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;d<o;++d)t.fillText(i[d],c.x(e.x),e.y+a.lineHeight/2),e.y+=a.lineHeight+l,d+1===o&&(e.y+=r.titleMarginBottom-l)}}_drawColorBox(e,t,r,i,o){const a=this.labelColors[r],l=this.labelPointStyles[r],{boxHeight:d,boxWidth:c}=o,u=Us(o.bodyFont),f=_2(this,"left",o),p=i.x(f),g=d<u.lineHeight?(u.lineHeight-d)/2:0,m=t.y+g;if(o.usePointStyle){const y={radius:Math.min(c,d)/2,pointStyle:l.pointStyle,rotation:l.rotation,borderWidth:1},v=i.leftForLtr(p,c)+c/2,x=m+d/2;e.strokeStyle=o.multiKeyBackground,e.fillStyle=o.multiKeyBackground,pB(e,y,v,x),e.strokeStyle=a.borderColor,e.fillStyle=a.backgroundColor,pB(e,y,v,x)}else{e.lineWidth=Yn(a.borderWidth)?Math.max(...Object.values(a.borderWidth)):a.borderWidth||1,e.strokeStyle=a.borderColor,e.setLineDash(a.borderDash||[]),e.lineDashOffset=a.borderDashOffset||0;const y=i.leftForLtr(p,c),v=i.leftForLtr(i.xPlus(p,1),c-2),x=o0(a.borderRadius);Object.values(x).some(w=>w!==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;_<C;++_){for(x=i[_],w=this.labelTextColors[_],t.fillStyle=w,Yr(x.before,y),S=x.lines,l&&S.length&&(this._drawColorBox(t,e,_,m,r),p=Math.max(f.lineHeight,d)),b=0,T=S.length;b<T;++b)y(S[b]),p=f.lineHeight;Yr(x.after,y)}g=0,p=f.lineHeight,Yr(this.afterBody,y),e.y-=o}drawFooter(e,t,r){const i=this.footer,o=i.length;let a,l;if(o){const d=ib(r.rtl,this.x,this.width);for(e.x=_2(this,r.footerAlign,r),e.y+=r.footerMarginTop,t.textAlign=d.textAlign(r.footerAlign),t.textBaseline="middle",a=Us(r.footerFont),t.fillStyle=r.footerColor,t.font=a.string,l=0;l<o;++l)t.fillText(i[l],d.x(e.x),e.y+a.lineHeight/2),e.y+=a.lineHeight+r.footerSpacing}}drawBackground(e,t,r,i){const{xAlign:o,yAlign:a}=this,{x:l,y:d}=e,{width:c,height:u}=r,{topLeft:f,topRight:p,bottomLeft:g,bottomRight:m}=o0(i.cornerRadius);t.fillStyle=i.backgroundColor,t.strokeStyle=i.borderColor,t.lineWidth=i.borderWidth,t.beginPath(),t.moveTo(l+f,d),a==="top"&&this.drawCaret(e,t,r,i),t.lineTo(l+c-p,d),t.quadraticCurveTo(l+c,d,l+c,d+p),a==="center"&&o==="right"&&this.drawCaret(e,t,r,i),t.lineTo(l+c,d+u-m),t.quadraticCurveTo(l+c,d+u,l+c-m,d+u),a==="bottom"&&this.drawCaret(e,t,r,i),t.lineTo(l+g,d+u),t.quadraticCurveTo(l,d+u,l,d+u-g),a==="center"&&o==="left"&&this.drawCaret(e,t,r,i),t.lineTo(l,d+f),t.quadraticCurveTo(l,d,l+f,d),t.closePath(),t.fill(),i.borderWidth>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&&n<e.length?e[n]:n}class Bj extends m1{constructor(e){super(e),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(e){const t=this._addedLabels;if(t.length){const r=this.getLabels();for(const{index:i,label:o}of t)r[i]===o&&r.splice(i,1);this._addedLabels=[]}super.init(e)}parse(e,t){if(Ur(e))return null;const r=this.getLabels();return t=isFinite(t)&&r[t]===e?t:Lre(r,e,In(t,e),this._addedLabels),Nre(t,r.length-1)}determineDataLimits(){const{minDefined:e,maxDefined:t}=this.getUserBounds();let{min:r,max:i}=this.getMinMax(!0);this.options.bounds==="ticks"&&(e||(r=0),t||(i=this.getLabels().length-1)),this.min=r,this.max=i}buildTicks(){const e=this.min,t=this.max,r=this.options.offset,i=[];let o=this.getLabels();o=e===0&&t===o.length-1?o:o.slice(e,t+1),this._valueRange=Math.max(o.length-(r?0:1),1),this._startValue=this.min-(r?.5:0);for(let a=e;a<=t;a++)i.push({value:a});return i}getLabelForValue(e){return fL.call(this,e)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(e){return typeof e!="number"&&(e=this.parse(e)),e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getPixelForTick(e){const t=this.ticks;return e<0||e>t.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}),T<a&&P++,HS(Math.round((T+P*b)*C)/C,a,pL(a,_,n))&&P++):T<a&&P++);P<A;++P){const L=Math.round((T+P*b)*C)/C;if(w&&L>l)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<i-1;++o){const a=_F[Za[o]],l=a.steps?a.steps:Number.MAX_SAFE_INTEGER;if(a.common&&Math.ceil((t-e)/(l*a.size))<=r)return Za[o]}return Za[i-1]}function Hre(n,e,t,r,i){for(let o=Za.length-1;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<t;++e)if(_F[Za[e]].common)return Za[e]}function xL(n,e,t){if(!t)n[e]=!0;else if(t.length){const{lo:r,hi:i}=D6(t,e),o=t[r]>=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<o;++a)l=e[a],i[l]=a,r.push({value:l,major:!1});return o===0||!t?r:Vre(n,r,i,t)}class QA extends m1{constructor(e){super(e),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(e,t={}){const r=e.time||(e.time={}),i=this._adapter=new nne._date(e.adapters.date);i.init(t),US(r.displayFormats,i.formats()),this._parseOpts={parser:r.parser,round:r.round,isoWeekday:r.isoWeekday},super.init(e),this._normalized=t.normalized}parse(e,t){return e===void 0?null:mL(this,e)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const e=this.options,t=this._adapter,r=e.time.unit||"day";let{min:i,max:o,minDefined:a,maxDefined:l}=this.getUserBounds();function d(c){!a&&!isNaN(c.min)&&(i=Math.min(i,c.min)),!l&&!isNaN(c.max)&&(o=Math.max(o,c.max))}(!a||!l)&&(d(this._getLabelBounds()),(e.bounds!=="ticks"||e.ticks.source!=="labels")&&d(this.getMinMax(!1))),i=sl(i)&&!isNaN(i)?i:+t.startOf(Date.now(),r),o=sl(o)&&!isNaN(o)?o:+t.endOf(Date.now(),r)+1,this.min=Math.min(i,o-1),this.max=Math.max(i+1,o)}_getLabelBounds(){const e=this.getLabelTimestamps();let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return e.length&&(t=e[0],r=e[e.length-1]),{min:t,max:r}}buildTicks(){const e=this.options,t=e.time,r=e.ticks,i=r.source==="labels"?this.getLabelTimestamps():this._generate();e.bounds==="ticks"&&i.length&&(this.min=this._userMin||i[0],this.max=this._userMax||i[i.length-1]);const o=this.min,a=this.max,l=See(i,o,a);return this._unit=t.unit||(r.autoSkip?yL(t.minUnit,this.min,this.max,this._getLabelCapacity(o)):Hre(this,l.length,t.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:qre(this._unit),this.initOffsets(i),e.reverse&&l.reverse(),bL(this,l,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(e=>+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<r;p=+e.add(p,l,a),g++)xL(u,p,m);return(p===r||i.bounds==="ticks"||g===1)&&xL(u,p,m),Object.keys(u).sort(gL).map(y=>+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;t<r;++t)i=e[t],i.label=this._tickFormatFunction(i.value,t,e)}getDecimalForValue(e){return e===null?NaN:(e-this.min)/(this.max-this.min)}getPixelForValue(e){const t=this._offsets,r=this.getDecimalForValue(e);return this.getPixelForDecimal((t.start+r)*t.factor)}getValueForPixel(e){const t=this._offsets,r=this.getDecimalForPixel(e)/t.factor-t.end;return this.min+r*(this.max-this.min)}_getLabelSize(e){const t=this.options.ticks,r=this.ctx.measureText(e).width,i=fo(this.isHorizontal()?t.maxRotation:t.minRotation),o=Math.cos(i),a=Math.sin(i),l=this._resolveTickFontOptions(0).size;return{w:r*o+l*a,h:r*a+l*o}}_getLabelCapacity(e){const t=this.options.time,r=t.displayFormats,i=r[t.unit]||r.millisecond,o=this._tickFormatFunction(e,0,bL(this,[e],this._majorUnit),i),a=this._getLabelSize(o),l=Math.floor(this.isHorizontal()?this.width/a.w:this.height/a.h)-1;return l>0?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<r;++t)e=e.concat(i[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(e)}getLabelTimestamps(){const e=this._cache.labels||[];let t,r;if(e.length)return e;const i=this.getLabels();for(t=0,r=i.length;t<r;++t)e.push(mL(this,i[t]));return this._cache.labels=this._normalized?e:this.normalize(e)}normalize(e){return J9(e.sort(gL))}}ve(QA,"id","time"),ve(QA,"defaults",{bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}});function C2(n,e,t){let r=0,i=n.length-1,o,a,l,d;t?(e>=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<l;++a)c=e[a],c>=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;a<l;++a)u=i[a+1],d=i[a-1],c=i[a],Math.round((u+d)/2)!==c&&o.push({time:c,pos:a/(l-1)});return o}_generate(){const e=this.min,t=this.max;let r=super.getDataTimestamps();return(!r.includes(e)||!r.length)&&r.splice(0,0,e),(!r.includes(t)||r.length===1)&&r.push(t),r.sort((i,o)=>i-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 d<r?(i=[o],r=d):d===r&&i.push(o),i},[]).sort((i,o)=>i._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)<parseInt(l,10))break;if(eie(l,a)){if(r)throw new Error(`${n} v${t} is not supported. v${e} or newer is required.`);return!1}}return!0}const LU=n=>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;l<i;l++){const d=t[Math.min(l,t.length-1)];n.font=d.string;const c=e[l];o=Math.max(o,n.measureText(c).width+r),a+=d.lineHeight}return n.restore(),{width:o,height:a}}function fie(n,{x:e,y:t},r,i){n.beginPath();let o=0;r.forEach(function(a,l){const d=i[Math.min(l,i.length-1)],c=d.lineHeight;n.font=d.string,n.strokeText(a,e,t+c/2+o),o+=c}),n.stroke()}function pie(n,{x:e,y:t},r,{fonts:i,colors:o}){let a=0;r.forEach(function(l,d){const c=o[Math.min(d,o.length-1)],u=i[Math.min(d,i.length-1)],f=u.lineHeight;n.beginPath(),n.font=u.string,n.fillStyle=c,n.fillText(l,e,t+f/2+a),a+=f,n.fill()})}function gie(n,e){const t=m0(n)?n:e;return m0(t)?CF(t,0,1):1}const QU=["left","bottom","top","right"];function mie(n,e){const{pointX:t,pointY:r,options:i}=e,o=i.callout,a=o&&o.display&&wie(e,o);if(!a||jie(e,o,a))return;if(n.save(),n.beginPath(),!Cf(n,o))return n.restore();const{separatorStart:d,separatorEnd:c}=yie(e,a),{sideStart:u,sideEnd:f}=bie(e,a,d);(o.margin>0||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<t.controller.innerRadius)&&i.options.circumference>=90?r:t},void 0)}function Hie(n,e,t){if(!e.autoHide)return!0;for(let r=0;r<t.length;r++)if(!t[r].hidden&&n.getDataVisibility(r))return!0}function qie({chartArea:n},e,t){const{left:r,top:i,right:o,bottom:a}=n,{innerRadius:l,offsetX:d,offsetY:c}=t.controller,u=(r+o)/2+d,f=(i+a)/2+c,p={left:Math.max(u-l,r),right:Math.min(u+l,o),top:Math.max(f-l,i),bottom:Math.min(f+l,a)},g={x:(p.left+p.right)/2,y:(p.top+p.bottom)/2},m=e.spacing+e.borderWidth/2,y=l-m,v=g.y>f,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!(n<l&&t<l||n>o&&t>o||e<i&&r<i||e>a&&r>a)}function IL({x:n,y:e},t,{top:r,right:i,bottom:o,left:a}){return n<a&&(e=DL(a,{x:n,y:e},t),n=a),n>i&&(e=DL(i,{x:n,y:e},t),n=i),e<r&&(n=vB(r,{x:n,y:e},t),e=r),e>o&&(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:o<Or/-2?o+Or:o}function nse(n,e,t,r){const{width:i,height:o,padding:a}=t,{xAdjust:l,yAdjust:d}=e,c={x:n.x,y:n.y},u={x:n.x2,y:n.y2},f=e.rotation==="auto"?tse(n):fo(e.rotation),p=rse(i,o,f),g=ise(n,e,{labelSize:p,padding:a},r),m=n.cp?wB(c,n.cp,u,g):Y6(c,u,g),y={size:p.w,min:r.left,max:r.right,padding:a.left},v={size:p.h,min:r.top,max:r.bottom,padding:a.top},x=zL(m.x,y)+l,w=zL(m.y,v)+d;return{x:x-i/2,y:w-o/2,x2:x+i/2,y2:w+o/2,centerX:x,centerY:w,pointX:m.x,pointY:m.y,width:i,height:o,rotation:$9(f)}}function rse(n,e,t){const r=Math.cos(t),i=Math.sin(t);return{w:Math.abs(n*r)+Math.abs(e*i),h:Math.abs(n*i)+Math.abs(e*r)}}function ise(n,e,t,r){let i;const o=sse(n,r);return e.position==="start"?i=ML({w:n.x2-n.x,h:n.y2-n.y},t,e,o):e.position==="end"?i=1-ML({w:n.x-n.x2,h:n.y-n.y2},t,e,o):i=V6(1,e.position),i}function ML(n,e,t,r){const{labelSize:i,padding:o}=e,a=n.w*r.dx,l=n.h*r.dy,d=a>0&&(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;c<i;c++,d+=l){const u=dse(r,t,d);u.initProperties=y1(e,r,t),a.push(u)}return r.elements=a,r}}PF.id="polygonAnnotation";PF.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderShadowColor:"transparent",borderWidth:1,display:!0,hitTolerance:0,init:void 0,point:{radius:0},radius:10,rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,sides:3,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};PF.defaultRoutes={borderColor:"color",backgroundColor:"color"};function dse({centerX:n,centerY:e},{radius:t,borderWidth:r,hitTolerance:i},o){const a=(r+i)/2,l=Math.sin(o),d=Math.cos(o),c={x:n+l*t,y:e-d*t};return{type:"point",optionScope:"point",properties:{x:c.x,y:c.y,centerX:c.x,centerY:c.y,bX:n+l*(t+a),bY:e-d*(t+a)}}}function cse(n,e,t,r){let i=!1,o=n[n.length-1].getProps(["bX","bY"],r);for(const a of n){const l=a.getProps(["bX","bY"],r);l.bY>t!=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;l<o.length;l++){const d=o[l],c=iH(a,l,d.type),u=d.setContext(yse(n,c,a,d)),f=c.resolveElementProperties(n,u);f.skip=pse(f),"elements"in f&&(mse(c,f.elements,u,i),delete f.elements),ol(c.x)||Object.assign(c,f),Object.assign(c,f.initProperties),f.options=sH(u),i.update(c,f)}}function pse(n){return isNaN(n.x)||isNaN(n.y)}function gse(n,e,t){return t==="reset"||t==="none"||t==="resize"?use:new L6(n,e)}function mse(n,e,t,r){const i=n.elements||(n.elements=[]);i.length=e.length;for(let o=0;o<e.length;o++){const a=e[o],l=a.properties,d=iH(i,o,a.type,a.initProperties),c=t[a.optionScope].override(a);l.options=sH(c),r.update(d,l)}}function iH(n,e,t,r){const i=Fg[Q6(t)];let o=n[e];return(!o||!(o instanceof i))&&(o=n[e]=new i,Object.assign(o,r)),o}function sH(n){const e=Fg[Q6(n.type)],t={};t.id=n.id,t.type=n.type,t.drawTime=n.drawTime,Object.assign(t,_B(n,e.defaults),_B(n,e.defaultRoutes));for(const r of hse)t[r]=n[r];return t}function _B(n,e){const t={};for(const r of Object.keys(e)){const i=e[r],o=n[r];kB(r)&&ki(o)?t[r]=o.map(a=>NL(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(r<t){const i=t-r;n.splice(r,0,...new Array(i))}else r>t&&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;r<i;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},wn.apply(this,arguments)};function Ese(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t}function Pn(n,e,t,r){function i(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function l(u){try{c(r.next(u))}catch(f){a(f)}}function d(u){try{c(r.throw(u))}catch(f){a(f)}}function c(u){u.done?o(u.value):i(u.value).then(l,d)}c((r=r.apply(n,[])).next())})}function Rn(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(c){return function(u){return d([c,u])}}function d(c){if(r)throw new TypeError("Generator is already executing.");for(;t;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,i=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){t.label=c[1];break}if(c[0]===6&&t.label<o[1]){t.label=o[1],o=c;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(c);break}o[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(n,t)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function fr(){for(var n=0,e=0,t=arguments.length;e<t;e++)n+=arguments[e].length;for(var r=Array(n),i=0,e=0;e<t;e++)for(var o=arguments[e],a=0,l=o.length;a<l;a++,i++)r[i]=o[a];return r}var Vx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",iS=new Uint8Array(256);for(var A2=0;A2<Vx.length;A2++)iS[Vx.charCodeAt(A2)]=A2;var Pse=function(n){for(var e="",t=n.length,r=0;r<t;r+=3)e+=Vx[n[r]>>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<t;r+=4)o=iS[n.charCodeAt(r)],a=iS[n.charCodeAt(r+1)],l=iS[n.charCodeAt(r+2)],d=iS[n.charCodeAt(r+3)],c[i++]=o<<2|a>>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<o;i++)r+=t;return r+n},Ro=function(n,e,t){for(var r=n.length,i=0;i<r;i++)e[t++]=n.charCodeAt(i);return r},zse=function(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},J_=function(n){return n.replace(/\t|\u0085|\u2028|\u2029/g," ").replace(/[\b\v]/g,"")},Ose=["\\n","\\f","\\r","\\u000B"],lH=function(n){return/^[\n\f\r\u000B]$/.test(n)},dH=function(n){return n.split(/[\n\f\r\u000B]/)},cH=function(n){return n.replace(/[\n\f\r\u000B]/g," ")},uH=function(n,e){var t=n.charCodeAt(e),r,i=e+1,o=1;return t>=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;t<r;){var i=uH(n,t),o=i[0],a=i[1];e.push(o),t+=a}return e},Nse=function(n){for(var e=Ose.join("|"),t=["$"],r=0,i=n.length;r<i;r++){var o=n[r];if(lH(o))throw new TypeError("`wordBreak` must not include "+e);t.push(o===""?".":zse(o))}var a=t.join("|");return new RegExp("("+e+")|((.*?)("+a+"))","gm")},Wse=function(n,e,t,r){for(var i=Nse(e),o=J_(n).match(i),a="",l=0,d=[],c=function(){a!==""&&d.push(a),a="",l=0},u=0,f=o.length;u<f;u++){var p=o[u];if(lH(p))c();else{var g=r(p);l+g>t&&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<n.length;){var o=n.substring(r).match(e);if(!o)return{match:i,pos:r};i=o,r+=((t=o.index)!==null&&t!==void 0?t:0)+o[0].length}return{match:i,pos:r}},JA=function(n){return n[n.length-1]},AB=function(n){if(n instanceof Uint8Array)return n;for(var e=n.length,t=new Uint8Array(e),r=0;r<e;r++)t[r]=n.charCodeAt(r);return t},Hse=function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];for(var t=n.length,r=[],i=0;i<t;i++){var o=n[i];r[i]=o instanceof Uint8Array?o:AB(o)}for(var a=0,i=0;i<t;i++)a+=n[i].length;for(var l=new Uint8Array(a),d=0,c=0;c<t;c++)for(var u=r[c],f=0,p=u.length;f<p;f++)l[d++]=u[f];return l},qse=function(n){for(var e=0,t=0,r=n.length;t<r;t++)e+=n[t].length;for(var i=new Uint8Array(e),o=0,t=0,r=n.length;t<r;t++){var a=n[t];i.set(a,o),o+=a.length}return i},fH=function(n){for(var e="",t=0,r=n.length;t<r;t++)e+=gf(n[t]);return e},Vse=function(n,e){return n.id-e.id},Gse=function(n,e){for(var t=[],r=0,i=n.length;r<i;r++){var o=n[r],a=n[r-1];(r===0||e(o)!==e(a))&&t.push(o)}return t},ux=function(n){for(var e=n.length,t=0,r=Math.floor(e/2);t<r;t++){var i=t,o=e-t-1,a=n[t];n[i]=n[o],n[o]=a}return n},Kse=function(n){for(var e=0,t=0,r=n.length;t<r;t++)e+=n[t];return e},Xse=function(n,e){for(var t=new Array(e-n),r=0,i=t.length;r<i;r++)t[r]=n+r;return t},Yse=function(n,e){for(var t=new Array(e.length),r=0,i=e.length;r<i;r++)t[r]=n[e[r]];return t},Qse=function(n){return n instanceof Uint8Array||n instanceof ArrayBuffer||typeof n=="string"},Iw=function(n){if(typeof n=="string")return Bse(n);if(n instanceof ArrayBuffer)return new Uint8Array(n);if(n instanceof Uint8Array)return n;throw new TypeError("`input` must be one of `string | ArrayBuffer | Uint8Array`")},a1=function(){return new Promise(function(n){setTimeout(function(){return n()},0)})},$se=function(n,e){e===void 0&&(e=!0);var t=[];e&&t.push(65279);for(var r=0,i=n.length;r<i;){var o=n.codePointAt(r);if(o<65536)t.push(o),r+=1;else if(o<1114112)t.push(pH(o),gH(o)),r+=2;else throw new Error("Invalid code point: 0x"+RF(o))}return new Uint16Array(t)},Zse=function(n){return n>=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="<22>".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<n.length&&i.push(Mw),String.fromCodePoint.apply(String,i)},eoe=function(n){return n>=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<d;u++)o[c+u]=a[l+u]},flattenChunks:function(o){var a,l,d,c,u,f;for(d=0,a=0,l=o.length;a<l;a++)d+=o[a].length;for(f=new Uint8Array(d),c=0,a=0,l=o.length;a<l;a++)u=o[a],f.set(u,c),c+=u.length;return f}},i={arraySet:function(o,a,l,d,c){for(var u=0;u<d;u++)o[c+u]=a[l+u]},flattenChunks:function(o){return[].concat.apply([],o)}};n.setTyped=function(o){o?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,r)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,i))},n.setTyped(e)})(Rf);var tC={},Hu={},v1={},roe=Rf,ioe=4,VL=0,GL=1,soe=2;function w1(n){for(var e=n.length;--e>=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<<n.bi_valid&65535,Lj(n,n.bi_buf),n.bi_buf=e>>bP-n.bi_valid,n.bi_valid+=t-bP):(n.bi_buf|=e<<n.bi_valid&65535,n.bi_valid+=t)}function Eu(n,e,t){el(n,t[e*2],t[e*2+1])}function DH(n,e){var t=0;do t|=n&1,n>>>=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;c<wH;c++)u=n.heap[c],p=t[t[u*2+1]*2+1]+1,p>d&&(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<J6-1;r++)for(n3[r]=t,n=0;n<1<<TB[r];n++)Oj[t++]=r;for(Oj[t-1]=r,i=0,r=0;r<16;r++)for(eT[r]=i,n=0;n<1<<v5[r];n++)zj[i++]=r;for(i>>=7;r<sb;r++)for(eT[r]=i<<7,n=0;n<1<<v5[r]-7;n++)zj[256+i++]=r;for(e=0;e<=Sm;e++)o[e]=0;for(n=0;n<=143;)wh[n*2+1]=8,n++,o[8]++;for(;n<=255;)wh[n*2+1]=9,n++,o[9]++;for(;n<=279;)wh[n*2+1]=7,n++,o[7]++;for(;n<=287;)wh[n*2+1]=8,n++,o[8]++;for(EH(wh,Mj+1,o),n=0;n<sb;n++)KS[n*2+1]=5,KS[n*2]=DH(n,5);CH=new vP(wh,TB,nC+1,Mj,Sm),AH=new vP(KS,v5,0,sb,Sm),TH=new vP(new Array(0),uoe,0,e3,coe)}function PH(n){var e;for(e=0;e<Mj;e++)n.dyn_ltree[e*2]=0;for(e=0;e<sb;e++)n.dyn_dtree[e*2]=0;for(e=0;e<e3;e++)n.bl_tree[e*2]=0;n.dyn_ltree[t3*2]=1,n.opt_len=n.static_len=0,n.last_lit=n.matches=0}function RH(n){n.bi_valid>8?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]<n[o]||n[i]===n[o]&&r[e]<=r[t]}function SP(n,e,t){for(var r=n.heap[t],i=t<<1;i<=n.heap_len&&(i<n.heap_len&&KL(e,n.heap[i+1],n.heap[i],n.depth)&&i++,!KL(e,r,n.heap[i],n.depth));)n.heap[t]=n.heap[i],t=i,i<<=1;n.heap[t]=r}function XL(n,e,t){var r,i,o=0,a,l;if(n.last_lit!==0)do r=n.pending_buf[n.d_buf+o*2]<<8|n.pending_buf[n.d_buf+o*2+1],i=n.pending_buf[n.l_buf+o],o++,r===0?Eu(n,i,e):(a=Oj[i],Eu(n,a+nC+1,e),l=TB[a],l!==0&&(i-=n3[a],el(n,i,l)),r--,a=FH(r),Eu(n,a,t),l=v5[a],l!==0&&(r-=eT[a],el(n,r,l)));while(o<n.last_lit);Eu(n,t3,e)}function FB(n,e){var t=e.dyn_tree,r=e.stat_desc.static_tree,i=e.stat_desc.has_stree,o=e.stat_desc.elems,a,l,d=-1,c;for(n.heap_len=0,n.heap_max=wH,a=0;a<o;a++)t[a*2]!==0?(n.heap[++n.heap_len]=d=a,n.depth[a]=0):t[a*2+1]=0;for(;n.heap_len<2;)c=n.heap[++n.heap_len]=d<2?++d:0,t[c*2]=1,n.depth[c]=0,n.opt_len--,i&&(n.static_len-=r[c*2+1]);for(e.max_code=d,a=n.heap_len>>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<d&&o===a)&&(l<c?n.bl_tree[o*2]+=l:o!==0?(o!==i&&n.bl_tree[o*2]++,n.bl_tree[SH*2]++):l<=10?n.bl_tree[jH*2]++:n.bl_tree[kH*2]++,l=0,i=o,a===0?(d=138,c=3):o===a?(d=6,c=3):(d=7,c=4))}function QL(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),r=0;r<=t;r++)if(o=a,a=e[(r+1)*2+1],!(++l<d&&o===a)){if(l<c)do Eu(n,o,n.bl_tree);while(--l!==0);else o!==0?(o!==i&&(Eu(n,o,n.bl_tree),l--),Eu(n,SH,n.bl_tree),el(n,l-3,2)):l<=10?(Eu(n,jH,n.bl_tree),el(n,l-3,3)):(Eu(n,kH,n.bl_tree),el(n,l-11,7));l=0,i=o,a===0?(d=138,c=3):o===a?(d=6,c=3):(d=7,c=4)}}function yoe(n){var e;for(YL(n,n.dyn_ltree,n.l_desc.max_code),YL(n,n.dyn_dtree,n.d_desc.max_code),FB(n,n.bl_desc),e=e3-1;e>=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<r;i++)el(n,n.bl_tree[_H[i]*2+1],3);QL(n,n.dyn_ltree,e-1),QL(n,n.dyn_dtree,t-1)}function boe(n){var e=4093624447,t;for(t=0;t<=31;t++,e>>>=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;t<nC;t++)if(n.dyn_ltree[t*2]!==0)return GL;return VL}var $L=!1;function voe(n){$L||(goe(),$L=!0),n.l_desc=new wP(n.dyn_ltree,CH),n.d_desc=new wP(n.dyn_dtree,AH),n.bl_desc=new wP(n.bl_tree,TH),n.bi_buf=0,n.bi_valid=0,PH(n)}function BH(n,e,t,r){el(n,(ooe<<1)+(r?1:0),3),moe(n,e,t)}function woe(n){el(n,vH<<1,3),Eu(n,t3,wh),foe(n)}function Soe(n,e,t,r){var i,o,a=0;n.level>0?(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<o;a++)n=n>>>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]&&r<p);if(o=gg-(p-r),r=p-gg,o>a){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.hash_shift^n.window[a+1])&n.hash_mask;n.insert&&(n.ins_h=(n.ins_h<<n.hash_shift^n.window[a+hr-1])&n.hash_mask,n.prev[a&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=a,a++,n.insert--,!(n.lookahead+n.insert<hr)););}while(n.lookahead<Dc&&n.strm.avail_in!==0)}function Qoe(n,e){var t=65535;for(t>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<Dc){if(v0(n),n.lookahead<Dc&&e===I0)return Ns;if(n.lookahead===0)break}if(t=0,n.lookahead>=hr&&(n.ins_h=(n.ins_h<<n.hash_shift^n.window[n.strstart+hr-1])&n.hash_mask,t=n.prev[n.strstart&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=n.strstart),t!==0&&n.strstart-t<=n.w_size-Dc&&(n.match_length=OH(n,t)),n.match_length>=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<<n.hash_shift^n.window[n.strstart+hr-1])&n.hash_mask,t=n.prev[n.strstart&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=n.strstart;while(--n.match_length!==0);n.strstart++}else n.strstart+=n.match_length,n.match_length=0,n.ins_h=n.window[n.strstart],n.ins_h=(n.ins_h<<n.hash_shift^n.window[n.strstart+1])&n.hash_mask;else r=Id._tr_tally(n,0,n.window[n.strstart]),n.lookahead--,n.strstart++;if(r&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=n.strstart<hr-1?n.strstart:hr-1,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 fx(n,e){for(var t,r,i;;){if(n.lookahead<Dc){if(v0(n),n.lookahead<Dc&&e===I0)return Ns;if(n.lookahead===0)break}if(t=0,n.lookahead>=hr&&(n.ins_h=(n.ins_h<<n.hash_shift^n.window[n.strstart+hr-1])&n.hash_mask,t=n.prev[n.strstart&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=n.strstart),n.prev_length=n.match_length,n.prev_match=n.match_start,n.match_length=hr-1,t!==0&&n.prev_length<n.max_lazy_match&&n.strstart-t<=n.w_size-Dc&&(n.match_length=OH(n,t),n.match_length<=5&&(n.strategy===Roe||n.match_length===hr&&n.strstart-n.match_start>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<<n.hash_shift^n.window[n.strstart+hr-1])&n.hash_mask,t=n.prev[n.strstart&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=n.strstart);while(--n.prev_length!==0);if(n.match_available=0,n.match_length=hr-1,n.strstart++,r&&(Bo(n,!1),n.strm.avail_out===0))return Ns}else if(n.match_available){if(r=Id._tr_tally(n,0,n.window[n.strstart-1]),r&&Bo(n,!1),n.strstart++,n.lookahead--,n.strm.avail_out===0)return Ns}else n.match_available=1,n.strstart++,n.lookahead--}return n.match_available&&(r=Id._tr_tally(n,0,n.window[n.strstart-1]),n.match_available=0),n.insert=n.strstart<hr-1?n.strstart:hr-1,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 $oe(n,e){for(var t,r,i,o,a=n.window;;){if(n.lookahead<=gg){if(v0(n),n.lookahead<=gg&&e===I0)return Ns;if(n.lookahead===0)break}if(n.match_length=0,n.lookahead>=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]&&i<o);n.match_length=gg-(o-i),n.match_length>n.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<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=i+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+hr-1)/hr),l.window=new ja.Buf8(l.w_size*2),l.head=new ja.Buf16(l.hash_size),l.prev=new ja.Buf16(l.w_size),l.lit_bufsize=1<<i+6,l.pending_buf_size=l.lit_bufsize*4,l.pending_buf=new ja.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=o,l.method=t,NH(n)}function nae(n,e){return WH(n,e,BF,Loe,Noe,Moe)}function rae(n,e){var t,r,i,o;if(!n||!n.state||e>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.gzindex<r.gzhead.name.length?o=r.gzhead.name.charCodeAt(r.gzindex++)&255:o=0,Tr(r,o)}while(o!==0);r.gzhead.hcrc&&r.pending>i&&(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.gzindex<r.gzhead.comment.length?o=r.gzhead.comment.charCodeAt(r.gzindex++)&255:o=0,Tr(r,o)}while(o!==0);r.gzhead.hcrc&&r.pending>i&&(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<<r.hash_shift^r.window[i+hr-1])&r.hash_mask,r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++;while(--o);r.strstart=i,r.lookahead=hr-1,v0(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=hr-1,r.match_available=0,n.next_in=d,n.input=c,n.avail_in=l,r.wrap=a,Pu}Hu.deflateInit=nae;Hu.deflateInit2=WH;Hu.deflateReset=NH;Hu.deflateResetKeep=LH;Hu.deflateSetHeader=tae;Hu.deflate=rae;Hu.deflateEnd=iae;Hu.deflateSetDictionary=sae;Hu.deflateInfo="pako deflate (from Nodeca project)";var M0={},MF=Rf,UH=!0,HH=!0;try{String.fromCharCode.apply(null,[0])}catch{UH=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{HH=!1}var Nj=new MF.Buf8(256);for(var qf=0;qf<256;qf++)Nj[qf]=qf>=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<a;i++)t=n.charCodeAt(i),(t&64512)===55296&&i+1<a&&(r=n.charCodeAt(i+1),(r&64512)===56320&&(t=65536+(t-55296<<10)+(r-56320),i++)),l+=t<128?1:t<2048?2:t<65536?3:4;for(e=new MF.Buf8(l),o=0,i=0;o<l;i++)t=n.charCodeAt(i),(t&64512)===55296&&i+1<a&&(r=n.charCodeAt(i+1),(r&64512)===56320&&(t=65536+(t-55296<<10)+(r-56320),i++)),t<128?e[o++]=t:t<2048?(e[o++]=192|t>>>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;r<e;r++)t+=String.fromCharCode(n[r]);return t}M0.buf2binstring=function(n){return qH(n,n.length)};M0.binstring2buf=function(n){for(var e=new MF.Buf8(n.length),t=0,r=e.length;t<r;t++)e[t]=n.charCodeAt(t);return e};M0.buf2string=function(n,e){var t,r,i,o,a=e||n.length,l=new Array(a*2);for(r=0,t=0;t<a;){if(i=n[t++],i<128){l[r++]=i;continue}if(o=Nj[i],o>4){l[r++]=65533,t+=o-1;continue}for(i&=o===2?31:o===3?15:7;o>1&&t<a;)i=i<<6|n[t++]&63,o--;if(o>1){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<<r.lenbits)-1,S=(1<<r.distbits)-1;e:do{y<15&&(m+=D[i++]<<y,y+=8,m+=D[i++]<<y,y+=8),_=v[m&w];t:for(;;){if(b=_>>>24,m>>>=b,y-=b,b=_>>>16&255,b===0)P[a++]=_&65535;else if(b&16){C=_&65535,b&=15,b&&(y<b&&(m+=D[i++]<<y,y+=8),C+=m&(1<<b)-1,m>>>=b,y-=b),y<15&&(m+=D[i++]<<y,y+=8,m+=D[i++]<<y,y+=8),_=x[m&S];n:for(;;){if(b=_>>>24,m>>>=b,y-=b,b=_>>>16&255,b&16){if(T=_&65535,b&=15,y<b&&(m+=D[i++]<<y,y+=8,y<b&&(m+=D[i++]<<y,y+=8)),T+=m&(1<<b)-1,T>c){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,b<C){C-=b;do P[a++]=g[F++];while(--b);F=a-T,A=P}}else if(p<b){if(F+=u+p-b,b-=p,b<C){C-=b;do P[a++]=g[F++];while(--b);if(F=0,p<C){b=p,C-=b;do P[a++]=g[F++];while(--b);F=a-T,A=P}}}else if(F+=p-b,b<C){C-=b;do P[a++]=g[F++];while(--b);F=a-T,A=P}for(;C>2;)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<<b)-1)];continue n}break}}else if(b&64)if(b&32){r.mode=pae;break e}else{e.msg="invalid literal/length code",r.mode=F2;break e}else{_=v[(_&65535)+(m&(1<<b)-1)];continue t}break}}while(i<o&&a<d);C=y>>3,i-=C,y-=C<<3,m&=(1<<y)-1,e.next_in=i,e.next_out=a,e.avail_in=i<o?5+(o-i):5-(i-o),e.avail_out=a<d?257+(d-a):257-(a-d),r.hold=m,r.bits=y},r4=Rf,px=15,i4=852,s4=592,o4=0,CP=1,a4=2,mae=[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,0,0],yae=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],xae=[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,0,0],bae=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64],vae=function(e,t,r,i,o,a,l,d){var c=d.bits,u=0,f=0,p=0,g=0,m=0,y=0,v=0,x=0,w=0,S=0,_,b,C,T,F,A=null,D=0,P,L=new r4.Buf16(px+1),W=new r4.Buf16(px+1),O=null,U=0,M,I,H;for(u=0;u<=px;u++)L[u]=0;for(f=0;f<i;f++)L[t[r+f]]++;for(m=c,g=px;g>=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;p<g&&L[p]===0;p++);for(m<p&&(m=p),x=1,u=1;u<=px;u++)if(x<<=1,x-=L[u],x<0)return-1;if(x>0&&(e===o4||g!==1))return-1;for(W[1]=0,u=1;u<px;u++)W[u+1]=W[u]+L[u];for(f=0;f<i;f++)t[r+f]!==0&&(l[W[t[r+f]]++]=f);if(e===o4?(A=O=l,P=19):e===CP?(A=mae,D-=257,O=yae,U-=257,P=256):(A=xae,O=bae,P=-1),S=0,f=0,u=p,F=a,y=m,v=0,C=-1,w=1<<m,T=w-1,e===CP&&w>i4||e===a4&&w>s4)return 1;for(;;){M=u-v,l[f]<P?(I=0,H=l[f]):l[f]>P?(I=O[U+l[f]],H=A[D+l[f]]):(I=96,H=0),_=1<<u-v,b=1<<y,p=b;do b-=_,o[F+(S>>v)+b]=M<<24|I<<16|H|0;while(b!==0);for(_=1<<u-1;S&_;)_>>=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<<y;y+v<g&&(x-=L[y+v],!(x<=0));)y++,x<<=1;if(w+=1<<y,e===CP&&w>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.wbits,o.wnext=0,o.whave=0,o.window=new Ul.Buf8(o.wsize)),r>=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<o.wsize&&(o.whave+=i))),0}function Iae(n,e){var t,r,i,o,a,l,d,c,u,f,p,g,m,y,v=0,x,w,S,_,b,C,T,F,A=new Ul.Buf8(4),D,P,L=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!n||!n.state||!n.output||!n.input&&n.avail_in!==0)return Nd;t=n.state,t.mode===sh&&(t.mode=AP),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,f=l,p=d,F=S0;e:for(;;)switch(t.mode){case $H:if(t.wrap===0){t.mode=AP;break}for(;u<16;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(t.wrap&2&&c===35615){t.check=0,A[0]=c&255,A[1]=c>>>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<<T,n.adler=t.check=1,t.mode=c&512?x4:sh,c=0,u=0;break;case c4:for(;u<16;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(t.flags=c,(t.flags&255)!==d4){n.msg="unknown compression method",t.mode=Di;break}if(t.flags&57344){n.msg="unknown header flags set",t.mode=Di;break}t.head&&(t.head.text=c>>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++]<<u,u+=8}t.head&&(t.head.time=c),t.flags&512&&(A[0]=c&255,A[1]=c>>>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++]<<u,u+=8}t.head&&(t.head.xflags=c&255,t.head.os=c>>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++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),t.flags&512&&(A[0]=c&255,A[1]=c>>>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<l);if(t.flags&512&&(t.check=Vc(t.check,r,g,o)),l-=g,o+=g,T)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=m4;case m4:if(t.flags&4096){if(l===0)break e;g=0;do T=r[o+g++],t.head&&T&&t.length<65536&&(t.head.comment+=String.fromCharCode(T));while(T&&g<l);if(t.flags&512&&(t.check=Vc(t.check,r,g,o)),l-=g,o+=g,T)break e}else t.head&&(t.head.comment=null);t.mode=y4;case y4:if(t.flags&512){for(;u<16;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(c!==(t.check&65535)){n.msg="header crc mismatch",t.mode=Di;break}c=0,u=0}t.head&&(t.head.hcrc=t.flags>>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,u+=8}n.adler=t.check=E4(c),c=0,u=0,t.mode=tT;case tT:if(t.havedict===0)return n.next_out=a,n.avail_out=d,n.next_in=o,n.avail_in=l,t.hold=c,t.bits=u,_ae;n.adler=t.check=1,t.mode=sh;case sh:if(e===jae||e===D2)break e;case AP:if(t.last){c>>>=u&7,u-=u&7,t.mode=FP;break}for(;u<3;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}switch(t.last=c&1,c>>>=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++]<<u,u+=8}if((c&65535)!==(c>>>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++]<<u,u+=8}if(t.nlen=(c&31)+257,c>>>=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<t.ncode;){for(;u<3;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}t.lens[L[t.have++]]=c&7,c>>>=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<t.nlen+t.ndist;){for(;v=t.lencode[c&(1<<t.lenbits)-1],x=v>>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(S<16)c>>>=x,u-=x,t.lens[t.have++]=S;else{if(S===16){for(P=x+2;u<P;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(c>>>=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<P;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}c>>>=x,u-=x,T=0,g=3+(c&7),c>>>=3,u-=3}else{for(P=x+7;u<P;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}c>>>=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<<t.lenbits)-1],x=v>>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(w&&!(w&240)){for(_=x,b=w,C=S;v=t.lencode[C+((c&(1<<_+b)-1)>>_)],x=v>>>24,w=v>>>16&255,S=v&65535,!(_+x<=u);){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}c>>>=_,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<P;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}t.length+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=_4;case _4:for(;v=t.distcode[c&(1<<t.distbits)-1],x=v>>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(!(w&240)){for(_=x,b=w,C=S;v=t.distcode[C+((c&(1<<_+b)-1)>>_)],x=v>>>24,w=v>>>16&255,S=v&65535,!(_+x<=u);){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}c>>>=_,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<P;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}t.offset+=c&(1<<t.extra)-1,c>>>=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++]<<u,u+=8}if(p-=d,n.total_out+=p,t.total+=p,p&&(n.adler=t.check=t.flags?Vc(t.check,i,p,a-p):BB(t.check,i,p,a-p)),p=d,(t.flags?c:E4(c))!==t.check){n.msg="incorrect data check",t.mode=Di;break}c=0,u=0}t.mode=F4;case F4:if(t.wrap&&t.flags){for(;u<32;){if(l===0)break e;l--,c+=r[o++]<<u,u+=8}if(c!==(t.total&4294967295)){n.msg="incorrect length check",t.mode=Di;break}c=0,u=0}t.mode=D4;case D4:F=kae;break e;case Di:F=YH;break e;case ZH:return QH;case Aae:default:return Nd}return n.next_out=a,n.avail_out=d,n.next_in=o,n.avail_in=l,t.hold=c,t.bits=u,(t.wsize||p!==n.avail_out&&t.mode<Di&&(t.mode<FP||e!==l4))&&rq(n,n.output,n.next_out,p-n.avail_out),f-=n.avail_in,p-=n.avail_out,n.total_in+=f,n.total_out+=p,t.total+=p,t.wrap&&p&&(n.adler=t.check=t.flags?Vc(t.check,i,p,n.next_out-p):BB(t.check,i,p,n.next_out-p)),n.data_type=t.bits+(t.last?64:0)+(t.mode===sh?128:0)+(t.mode===E2||t.mode===TP?256:0),(f===0&&p===0||e===l4)&&F===S0&&(F=Cae),F}function Mae(n){if(!n||!n.state)return Nd;var e=n.state;return e.window&&(e.window=null),n.state=null,S0}function zae(n,e){var t;return!n||!n.state||(t=n.state,!(t.wrap&2))?Nd:(t.head=e,e.done=!1,S0)}function Oae(n,e){var t=e.length,r,i,o;return!n||!n.state||(r=n.state,r.wrap!==0&&r.mode!==tT)?Nd:r.mode===tT&&(i=1,i=BB(i,e,t,0),i!==r.check)?YH:(o=rq(n,e,t,t),o?(r.mode=ZH,QH):(r.havedict=1,S0))}Rc.inflateReset=eq;Rc.inflateReset2=tq;Rc.inflateResetKeep=JH;Rc.inflateInit=Rae;Rc.inflateInit2=nq;Rc.inflate=Iae;Rc.inflateEnd=Mae;Rc.inflateGetHeader=zae;Rc.inflateSetDictionary=Oae;Rc.inflateInfo="pako inflate (from Nodeca project)";var iq={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};function Lae(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var Nae=Lae,ab=Rc,$S=Rf,k5=M0,ms=iq,IB=r3,Wae=VH,Uae=Nae,sq=Object.prototype.toString;function j0(n){if(!(this instanceof j0))return new j0(n);this.options=$S.assign({chunkSize:16384,windowBits:0,to:""},n||{});var e=this.options;e.raw&&e.windowBits>=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<R4.length;R2++)oS[R4.charCodeAt(R2)]=R2;var Yae=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<t;r+=4)o=oS[n.charCodeAt(r)],a=oS[n.charCodeAt(r+1)],l=oS[n.charCodeAt(r+2)],d=oS[n.charCodeAt(r+3)],c[i++]=o<<2|a>>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;t<n.length;t++)e+=String.fromCharCode(n[t]);return e},aq=function(n){return Qae(zF.inflate(Yae(n)))},$ae=function(n,e,t){for(var r="",i=0,o=e-n.length;i<o;i++)r+=t;return r+n};const Zae="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",Jae="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",ele="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",tle="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",nle="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",rle="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",ile="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",sle="eJyNnVtzG8mxrf+KAk/nRGh8eBWleZPnItsaj0ZXWNvhB5BsUdgE0TLAFgjt2P/9AI2uzJUrV7X8olB/q4CuyspaVX0p8H8mP7V3d83yfvLj5MPfu/Xspnl0enH05Nmjs6dHz84mjye/tsv732d3za7AX5rF1+Z+fjXb426xUHh2N19shTBt5jef92f5e3M97+525K/3s8X86vnyZrEre7Q7Xv86f2iu/5jfX32e/Hi/6prHk58+z1azq/tm9bbZf/aXh/tmed1cv2nvZsuhbn/+c/sw+fGfPxw/efL4h5OT88fHR0dHj5+dHv/r8eT9rvBqMV82f7Tr+f28XU5+/GEng/Du8/zqdtms15Mfz3f8Q7Na98UmR0cnf9p90e4kv7e7Juyb81P7Zbvat+LR/7n6v4+Onz09f7z/96L/99n+32dH/b8Xj55ft5fNo7fb9X1zt3701+VVu/rSrmb3zfWfHj16vlg8erP/nvWjN826WX3dUQvVo/n60ezR/Wp23dzNVreP2k+Pfpsv2/vtl+aHXaHFo+cvHs2W1/+vXT2a775g3V2u59fz2WrerP+0q+wvu1Ndz5c3b68+N30f9DV5e7/7yGx1XdRdwZ9mX/4ydMnF8dPHk3+Uo/OT08eT5+urfaBXg/hzY8c/nBxdPJ68vb/+y3QnPun/+2H336dPD7319+Z+Nb/ahfOf/zOZ/mPy48nFTvh9V5H1l9kuiv/7mHDzcLWY3Rk/PT8/8H937S5alwtTzs+fHJRld3e576abZdau28VitjL+dNctPf/SrK72SV6EJ08uDsLsbietd9Hxmp2cQA36/vbanZ4O3zdbNctF86km0cdKNWbr/Teub73iT8+GTy26dQ7O1W5szvIpPm+/fG6WufiuKfP2OvP1Yrb+nIP1rVm1mbbLJsP7jSh5/3nViLKf2m4l6PyrKLuePwjYfG1E3zYhpp4O86VIq6t20YoIrZu7eZSsBxZ7E0i0+Xc3W2R8s2p2g1k0899ds+6NpijHR8dDRs9E+j3P6M+GLkom/pTRz/mDvzg6Pj6gX/2DJQIv8nf9Jcfpr96yvV3u0d/yGV/m9v/mY69k69/zGX/P9XqVv/6PXOp1/q43+YNvcyTe5Q++zx/8YOjZ2dDT01zqHxl9zGf8rxzVy91cdtvcB99wcafFgcqfi6Zy9sRM5Wo+v5qvrrq73B/d3rXXu+kHxkgwuFAZ+9gso8ucElfCgMW4zQ36lEvdZPQ5V3me0X/net3mUouclyJawnWE730Rwz6b9CrXSzi8iH2XP/g1Z+8ml3rIaJvRN6jqmedXTISTJ0clK1eV8jEbzRn7bLyfL66bHJLDXH/dbkScw/TsU8F9v0zz5DguI+7Tfl2IRmuf2arJ49OiXc0FXzeVb7nqVrt5/MoDePzsGIbNet6vW1MTy7JFD6ubbr5T7tp7vXTYy/0Xf0em0Jee/TQXTCygdis5uR64nt3cqDntwHEtRiuOfd81qwbG/umFLYZmN6vZFz/b6XnJrN0FRAMZF1ypb+blbD0S4XF1pRcL1gFR7y8ZDrFZLOZf1vO1kHZtvf/cdmGxaG5f5v2Q3N5zq9lXUdnZVXcv8MHLPy2ah6xVRtbd7GrVihNfrhp14uv2fnYVRpxL811PYgDc0HAcemV3l3O7NbdYpHbLm9mqu1vMOnGa9ma3zrwVXzdbhcWT9ctdyFkXnvuyZ3fdOnz56vrTbqEXVoa+QomTrC9AIvczvIIzPDm3M9ztnK5b4CnsamMmprzr/aBfr8UEtogntpRqI7cVSdvksrvxubsi3uW9mGL+mrrUnSBmoE//MW98apKd6l8Xe89XR7kGZbq4nn+dQ0L7R2LNfMEsBodXO37IV3rqQzZFUgxssu4vvmiYQFPzV/r5wlBxXO+IGY0H/0ylhzr6gF8FpJP4NcPOI+Ai5KQ4sWroRXHwq3LTQ5yKXMfXhTEPvJU6Lr+rCvjwqOVoNFVf6cvm2KVU7duisUI4k1VChsxk89fsiTYU5/HsZxdDnRftt2Z5IzL3TTyFX8WNJmc3OkiE6MOrNpGsKm294rb69U+OnJ3m3ed2JVr1is7uYai4wVviZ2USo7DZaOKMtYjpya2/w7Hu+lXOStSXUtCiWONkq8UE77rF/fzLYivqRQ30JA8NPLsolyaz1f18trief/qU+2pbt4bf43k8YceS5ZfRNBuZdbJk6VQZnsuaDdYy5vcYIJ8M6Yvw/ttuxYA34ewSaNXeNku8EDJzXDU383Vc+voQjZ0N03EeF+Yc3W5Uh+sRD3ZlDbmqRKalyPi4rKTUf9EIP3tW1q79ra54I8zi/Mv95wx/SgZoZq586/R4aON9Zd5oqrNjbRZ8Xls+jGRlDLBfL9PQsFsRXClzhVqP1Kae2jS6rg3KPI7t3KPLEp4xy7qgWdyLGz73waTdEzftiCPW43vXiZZQzC1Ucp3pY4FC71eqcYXztNyw6H18l8CrXSKv8/e9Tfn67FnJV72ifTk6//4WO84vJeyxjjLFZAtuGTFMzmvT2W+x2haHXdQ+zxYwNZRBvr80oVvd1hdjLr+MyyZPte90YGUoNLUG3UQzxQYN3ap6VffdW7lAtAyWNT8rPXi9swn10KONXQRWqC2ti+XPzs3Or+dXymh/jl8EC7Ox5e7vsX+8upV+ezOe10p1b60soZ9XTTpeDlgPUJ3NiEcWlL/Upnt2CrtFLBtqC7K4ErBvGx0KlSrcj55p0d7s+3vZinC3dTPtslSG8u6rKiP5ZvyKFmZyj3klfZdyHrebO8u8aHbPr43xX7r948h/PZ68bFbLP2bz1f4h8j8nz/cPqyePfzg9+tfj4ejgHgEd6hnRYOoIX8Sjg6sEhA1D4VU8ylXAqTdw66pAD+M/oOA8QRlCFtjh7lBAh4GD6HU4erc7Oj7xwxK0wEL7QXm/Ozz3oxIAQCEAwCEAQEsAAFEAQLEAABuGdmC9oyD5sDu6sKNp0D7uG3jkh6VJyKDugLsQ1i4nQ1dJhk4mQ5eToasmQyeSobNYABti4eTr7ujMjjbhaBuPSosAQc0HOhTC0WmIQmKcxqlzHqxFeSEQDVvjcuwW9ZVAlVrKoWxi7kKTqB+N6840mXvUBBrjxmmgF/46IxzyxnjcuyAHf5HBAQyRDRhXXmBiNgSTyBWMa2swmf3BBDYJE6JTFAx2UdA0l0LjMMbuYYKwkKJ1ucPYTIyP5aSwFZMqOVkxGJNrOZmsxoToNwWD6RS0yWgrEHmQ8WxEgx+gERmicBonI3LORlSUFwKRERmXRlTUVwJVaimNyMTc6SZRpxvXnW4yd7oJZETGyYgKf50RGpExNiIXpBEVGYzIEBmRcWVEJmYjMomMyLg2IpPZiExgIzIhGlHBYEQFTXMpNCJjbEQmCCMqWpc7jI3I+FhOCiMyqZKTFSMyuZaTyYhMiEZUMBhRQZuMtgKRERnPRoShQTeKnAIbRfIlEtmcgvyixsmmoii9KhR5VeNjDZHWFUvkXIk6JUwUddbEMpw6USVPiyIZWxBfVzhaXBTY50iVZhfKgONFTrYXReV9sUQ2wKiTC0ZRW2Esw34YVTbFqEZnDBrYY+DTSnk0yiiwW0ZVWGYo0FVSgc0zit8dGsJGoz42NCqGGsuMDo1krVGN/ho0MNnANxW+rXHy3Chm43WCtouUOgQlstwgseGC+EJTMluUpNVCgVea1qsuTRb1nEeoUhahpHMIS3AGoUbWihIZK0ivJUVTRcyWGjRpqFAC7BQpmSlKykpRz0aKKtkoStpEsQRbKGpsoKhF+wQFzBPoVJZF40TMtomaME2QO9nNbJgofSfJhVmiWk/yilFiiZEkTyaJWrRIUMAggW4k3WpK1ohSNsah9eiKhijkxskPnbMZFuWFQGSDxqUHFvWVQJVaSuszMaeESZQPxnUymMyZYAJ5nXEyusJfZ4QWZ4z9zQVpbkUGZzNEtmZceZqJ2dBMIjczrq3MZPYxE9jETIgOVjDYV0HTXAqNyxi7lgnCsorW5Q5jszI+lpPCpkyq5GTFoEyu5WSyJhOiLxUMplTQJqOtQORFxrMRlbqiEzmjgLpAXgQCm5FJLxQjO3JB+pHJrxSrVVZakqu5/12jBHBBZ4DrnAKukC+5QMZkwmvB0JocsjeBIs3JdHAnZ2RPLih/cjUblGvkUC5oi3KdPcoVNilXoksZB5syNhXl0KgcslO5IqzKxE50IZuVC6PpKuzKtVq6VgzL9Wq6JstyJXqWcTAtYxvBtoqRb7mQjatUDI3LGQXXBTIuENi4THqhGBmXC9K4TH6lWK2y0rhczZngGmWCCzoTXOdMcIWMywUyLhNeC4bG5ZCNCxRpXKaDcTkj43JBGZer2bhcI+NyQRuX62xcrrBxuRKNyzgYl7GpKIfG5ZCNyxVhXCZ2ogvZuFwYTVdhXK7V0rViXK5X0zUZlyvRuIyDcRnbCLZVjIzLhWxcq+GHPrwKhVBgCybLMsyGNQgvMiGzKlha1SC+ykRXT5pU0XKfF4V6vGDd30Xl3i6crKlgMqYBv04ETakgtiTj0pAGFeyoEDKjgpUVFS0bUVHIhgrWJlRUtqDC2YAKj/YzUDCfgUxTGTSegth2ChemM0hd6h42nIJHEk+YTVF04lWMpqiVxEsmU3i0mIGCwQxkk8g2E7KWgrOxDOmOzmKIQmicvMU5m0tRXghE9mJc+ktRXwlUqaW0GBNzV5tEfW1cd7bJ3NsmkM8YJ6Mp/HVGaDXG2GtckGZTZHAbQ2Q3xpXfmJgNxyRyHOPackxmzzGBTceE6DoFg+0UNM2l0HiMsfOYIKynaF3uMDYf42M5KezHpEpOVgzI5FpOJgsyIXpQwWBCBW0y2gpEPmQ8GdGfh9w89iPvDEMhfsBD9xgtUQNEAQPFYgXMwgRsiJCTw+96Pf7hxMjw010F/QSFTo1YoQGVV+KoZMFcfBj+XLzgVLxYc/qACfSRn3fouXVPfxQ7s0fFxQGFPgKeurynpY8AWU8As54ANvQEkGKpjtwLfh5swLW9Azzzo9I6QFBlpyWA/rUWuQGVToDwGaIYGqdAGlfRNDGH1CSKq3EOrgkcYRNimA1TrAv/kMMwzaUg9IYo/sZzJ3Du0/lSd/T7CGN3FMTdUTh3R+GyO4oouqNI3B2Fp+4oQuqOIlB3FMzdMfAPOQzTXAq7oyDujsJFdwwSd8eAqTt+HXriqR+VUwEq8QcUQg8cKgS0BByQxRqYhRnYEGEgJbiOZrag6I/iCqpHpQWAxHqq52kp1dO4iuoRrZB6RoujnoV1UU9KCxyV3jp25CuM/iguYnoUV/4HlJc0PU+rmQO1bX8Bx/VNj2jt0jNatuxZG49yndtKBVtZwTbXpJWLrF4RdWzjcr9HcaX/K44JiP5qPy7P7cicyVGJPqKw2D8IfxtG2GH18TccYYBKfgIKkQIOkQJaIgXI4gHM+gzYkJ9ASogczeJRbsEst2BWacFMtmCWWzATLZiJFsxSC2a5BXGl9be8xNqjLnyky83sKm3qZJu63Ca+SABFtLYTre1Ca19ODtfh534U7a9Hwut6nryup9HreiQvFnuFXLBnZdQBipb3cvC3Mz+Kc/9L9DdEecZ/Sf6GFPwNcJz+XwZ/A0aT/svB3+Ao17mtVLCVFWxzTdjfQBF1NH8DFNceLyd4Tfxyki6HX6asBp5c+eUkXf++FFkNCrnyy0m+4H054WvdPdmGbNnmrN7m7A0GjOOCBPoyUtVooSLfPTWNIVL1cKJCPLJIpkFGKo23qEJ6kEAZTSoNSFZF6lORPAq4QB6xVIKGDKk8RkjmIR3ltiqMhkWOeSryvYazE5CqTYEKjbedrYJUco2ogoGQQF5CqrIVKpIdhgqQ2ZCqfYcKsQWRzG5EcjSmKG5rI4ztitRkH79NhhvLx35o95SRxdvJrnyIh/vLygs76u+unvmh3csDhjftHMcffc2S8SfGtxas3zAQgFKf/xb2VB8T4zjU9lST/EEwCEvYcXxGjAMkdxyTVgtV0DleuEuXYsGRU7t0B6nca8HwGePwuSDDh7eOmEH48N5RaWm6eZQEEb6i1cIXdA5fEbc5Fhw+4yJ8YXCGIEYlhZJkHdBQ6ENVweAGIYQ4KinQUVbhDiWqQc+lUuiTEcpopm6oGuFQYJimQjcY4w5wQYa+yB8Eg3AXhIE2xiE2QQS3aLWwBp0DWsRtjgUH0XgK327JC3cb+qN4EdujeK3eI3Fd2/N0XdvTeF3bI7p67RldvfYsXL32JF6rvxr6/syP4rLzVe5vFz7YjPpq6GOPyz92R0/s6KP1/yvsZkDQdKflNoKf0m4jDKj4NHSDIeoL49QhxlWvmJi7xiTqH+PcSSZwT5kQu8sw9RnO3xQG7r3K7E0q9CPO3acRQY/idH5BiPpWTeYkUS+nx34DD3snob8jp06PIvV8FFX3xxI5B6JOiRBFzoaockpENeZF1Cg50k5uFT1Ok7F93KoIJEzatnwqOKRO2s58oTglUXUzs9IpnYLGOQWbziCjkFI+oUTZhJLKJdRzJqFKeYQSZxFqnEOoxQxChfKHtqzmOHHu1Des5gKQN7Rj8zRRyBnax3mRKeVLZRdnVilXQOFMKVuCIE0MUY4YpwQxrrLDxJwaJlFeGOekMIEzwoSYDoYpF3BjH4WBs6CyrY9U6H/c8nYaEfQ87oK7IER9rvbAkUS9XTB3dbzNgT3OCnU8y9T/LKs04DI5G7gEJQXLnBusc4qwHjOFVUoYkt9VY8rpk2SVRVQIkokUyClSILVIgQxjhRKN5ZxvVILSjlTOPtvDA3nnjDLOBco1F1SWuZrzyzXKLBc4p1zhbHIl5pFzyqCwY48jwllT26/HMmRK2MJ2SgyyI2xru2BGGSE3tbFGWWCc+79cbkL3G6LeN06db1z1vYm5602injfOHW8C97sJsdsNU6/jbQgKA/d55SYEqdDjeAviNCLob7wrcUGIelvdkyCJ+rpg7urySih0tSHqauPU1cZVV5uYu9ok6mrj3NUmcFebELvaMHU1vthNYeCurrzWTSp0Nb7yfBoRdDW+BX1BiLpavQNNEnV1wdTVfwy9PLyS/gf2MLLSu8jii78g4D0xwPbqLzB/wxegv+ILsLzjC6j0ILBZaJm9oQIovkXYI/HkrufpcV1P4zO6HtEzt57RQ8aehfcEexIfuP0B/Xb81FBjmdQfxYdKPSoJiig/vu55euh0oPDEFXB8ft0jeh7dM3rfbc/aeJTr3FYq2MoKtrkm/DgUFFFHe/AJKD4d/wNHxxD91xN8A74/im/A90i8Ad/z9AZ8T+Mb8D2Sb8D3Cr0B3zN6A75n4Q34N5PDWw8nfhRdu0fCmHuePLmn0Y57JN9h6hXy6J6V+AOKDvxmMN9TP4qvNr7JluvCextEb7CXAIlR/oZ6CWgc5W9EL4FC4/9N6CVgYfy/CXPEmzA9vBmmAdc+xhH0hsx/oOUWJfS+IUoB4yoPTMzJYBJlhHGdFiZzbphACWKcsgRvMp8Sonyp3GQmFTLHEKWPcZVDJuZEMomyybhOKZM5r0zg5DIhZli+j25omgPxMZfirFM3zQepPFmF1DNEqWdcpZ6JOfVMotQzrlPPZE49Eyj1jFPq4QP2U0KUepXH66RC6hmi1DOuUs/EnHomUeoZ16lnMqeeCZx6JsTUwxcIKEOmORAfcylOPfX2QJHS+34nUuA0HHnfTxcRKanf99NqJT0r7/tpmVNVv+8nVUxb/UZDRZUpHMpgIkeB0zmqMqljEZHasQAneFQraR4LpWSPckr5KFPipxc9ZJZOa6H8WPtEGhDVtzwOBd5OeB/k20naB/mWn3US5uK8zYtwKp62OCYhfSQ0iz8WRProLr/xWrY/pGvZntG1bM/UtWwv5GvZHtO1bM/4WraHfC3bw3gt2yO6ln03GNmZH8WR9C5ZFvA0Zt6hOQGSo+NdsCFg8d3Rd2g4jmaxETPRA3YN/sRRrQNmugNmogP8Mhy+V8V/luNvF+L+0at2AT78DpIRPkdVaERr7eI8sEpzG93ccH2OvITBq92IKDQqCp+3Xz43fb2889pYpBXNaWtVb3XVW9FTfOmOkqi+XbtjudxhfvHuxVZ0KBq0Ev1De7hAWTd385wZXSzUidN0tbh1Om6diBu/6IySiFunur3Lyb+Jh1s6FI3BV86G8+EG61Iy7bBOAnux3mOdVBGytMs6Ccmf8z7rpFCw0k5rFsCz09UPc+Xe6uqHJfLx2tUPy+zo6eqHOXl74TPR7OTyJpDVGx/tX2X6ptX6N9m/CdXu5YnAOJmLr3rCwOfFEH+NqmWaIUxgG3JhLFRqwnBNzBom0tRhvBbGPIkUJc0kRWhF4TSnmDDaTjW7mFZLido8Y3qtrWnGMaGSGWnuKcJKsVoI0lTkgpyPiiwmpSJ1oniankwY7QI1UZlW64LalGV6rQvy5GVKZdRuBNsqVmu+mtXCBUeY26KSvjPKaZ6Lso57LKOiH0ukPohynv+ingMedQ57VNOMmG7KnEmBZ8eRmzK6iJgp9U0ZrVZmzcpNGS3zDKpvykh1Vg1ZnlOjzDNrVP+DjJKzbCwxnlF5xo3ydxIqzb5RZael+wLR7eRNA/3F9fbkuTnKyZ1J/n7I5WxNJdScHYvwzB3V8U4Rs3jQ81we5Lb6wTyvR/k/iI6c42OJ8YSszvex1HiE8twf5dG8zOuAIK/qynj48sqAZL0+CIXUKiEU6KofzSuGKP8HnStXD7HEeOdWVxKx1HjnilVF1Ec9aVNVtnVlPHR5zfF+WGic+VGcI9/jggKQmCvf08IBaJwV34cFAjC69/0eFgJA4hT3fsKvH72fpDePypMBbGvaIcWcWq13SLGY2592SDHnSOQdUizEmKQdUsQpOpWdReHxCMZJ7yySIkVsZGeRLJFjp3cWSZGjWNlZJNUYT72zSIkU2bFNNvBoCYOrNtkIiQJb3WQj9BxUtclGSBxQuclGaDGYapNNliiQ9R0o5QEcxjDtQGFO0dM7UFjMcUs7UJhzxPIOFBZirNIOFOIUpcrOjfe8PaGuUMBqOzcqsgrfyM6NSgkKZnXnRkXn0FZ2blRUCvTolgVWOexhy0JiFOq8ZSEJKrxyy0LSKKRiy0JSOIxpy0LiFLrKG/7OOVz2xw6eK0bhcoHC5YIKl6s5XK5RuFzgcLnC4XIlhss5hcsECpdxDtfwA+7PM6FQFUyBKliFqWg5SEWhEBXMASqcw1N4DE6hFJoBU2AGSmH5MITkqR+VcACKvyX6IYUBePot0Q/YfED0W6IfQrOBhd8S/YDNdfQitOdF7LkexSsuF17Fo5gKPRL93fPU1z2N/dwjecuqV6j3exZvTvUodu8e+W/E9kdxu0GPSggAhYYAT5sSeloaAsiqC8x6DNjQY0BKCxyVK9szIOU20HlBsZObnJh2jweRTsxGJma4fwM452sj8rUR+Wp3ZBy18Sg3o63UuZV1bnPl+E4KKKLadssEUB5TcG/EOgTvSXjPdaFnu5yNXSX1Opl6XU49vpkAikjKTiRlF5JyOrjeuR/F17Wm6HqAxC6IKbke0LgLYhpcDxjtx5iC6wGJ2x+mE3x1coreBUi8JDkl7wIaX4ecCu8ChV58nKJ3AYqvOE4nuOdnit4FKNr3NHkX8GTCU/QuQGS10+BdwMIEO0XvclSc6qmRvX7qR6VNgOI7m9NkVMDT7wNN2agAx1/amwajAkY/lzdFo/KGtaFAm5uhfgl6SkYFNFdO/xL0NBgVsPhL0FM0KkdmVN4fXSjQ5YaoXzmckiMBzQ3RP2I4DY4ETMQ//kbhnmzDONnm8bxN4/bjYGTDD2V9RCdDZg80gcW7wCDgrV/Adr8XmD+kBOg3bQGWO7WA7Bmks72lPT23I5sqHcWp0jlOlU5tqnTEU6UrPlU6s6nSkU2Vhvply5k1wh8FAosLso/J1LBs/pWyj2hryGj6+xh8DQuW+AOy+Dsrk/sTIMOyzAvRZxrRXH/4hqzS3ka3Nz5bAy7i0Ig4NCoO/MBsz+ZhOM3juOsRbVb+OHglfEcrgtDWGtzqBreiYekZGUg++ADa4zBgoqN9decMV3eeAF0coZ2wl65mJZ22kk5YSXpeBJJymU65TEcugw8tEuOGpMcWSZDNVA8uksYNzo8ukpLaxw8vEmc/xe2Fg1ml7YXMlb2q7YUskdHWtheyzJabthcyJ/MtHB3KGA9JE8iLjcvxaqoYtKbxyDWBfcmEZE6mkFMbjxfRxmnE8jMr/hpVy+TgJrCNuzAWKmXorglXN7EWx+TvJlTjmJy+CGD3hsjzjbPxF6EV35umABNGg6UmA9Nq8ahNC6bX4pXmBxN4kkhPOVkQ00WRcM4wVvNbPXuYOmKraR4xoTKZmF613TytmEK2S48jFeYWqweSSpMBqTySVDKHRT6UVGJqvHgsqSSeeUCDyQcpzT8oqSkI9TwLoUoTEUp6LsISPB2hRjMSSjQpgYQOjJitAjWanVCSRoIFhJegzHaCGjsGaslkUaT5CiWassLz6mAc4km2+L5K1dP0hRrPYEH7TjjVPBZkMZWhPhLuNKGhNhbuNK2BBjMbUprcUOL5DbRWnyPNcqh9L6BqrkN5JGC1GQ+LpAsiFHniQ43nPvX6hNDEDAgqToKIR2YFPRVigXHnTxMiapU5EYuMTQ55ZkQxTg77ncJfLav2R5tw5D+X3h/F+3M9SvfhimXi9xa0yWibP8inMZ7PNVgwnqugTUbb/EE+l/F8rvDOE5ww8E2Fbyvfw+ePYq4EdCVUAehG0q38Bj45SvnU5SUcOG9Bm4y2+YN8OuP5XPYuBZzM2Eawrfgsn8+FfEJ7GwFOaGwj2FZ8lk/oQj4h/M37k0A2iWzTp/hE4m/eDwr+WeuTiDYZbfMH+VTqz1ofpMsdvdxbix3FFxv2ZGHn7I/ihNej+PwfhPjM6nKS3pC4nOCfGLxEBwcknrRdkl8DjU/aLoU7g0JP2i6DFwMLP5x4GTrncoJPFy4x/oBSXa9wOXZeyG3Qb1Vkr9JdiPOAb3NJ/T1pz+Z5wLe5ZOV70i9blG8y4VaV1t92mPIn6y+zq30Izwfaf3H+OyJHWSYtRypeeBv6aqMijrT90UPQtkGj3uaBNlDdaYa5Pjghn8Zv2OQvfciltrkUV1TN0YOkU8Mw17ZwqC3uRKQvfciltrkU11btTCySeuu5VE2+9axErLxeHkT+UCm/rZRPDaotGwZdXbads8ItorXGafqqjTzBgyy7lWW5HZUVSFH9Mi41A6TUDtCwIYA3+iQPuvRWl06NQS23ht91Hmqb3nUmDi3Iyy9DD7nUNpfiGqsV2SClt16HauW3XlmACoslnLMHUW4rynGl5bJu0NLLp0Pl8sunLECtxTrQ2YMotxXluNZybXjQPk0O96NO/SguwnpU7j4BEu9K9Dwt1Xoa35XoEb0R0TN6I6Jn4Y2InsS3PT5BxJ3sxsOiWa/7mx9PC4wfanJD6Y2cA9INzW/kHGh6I6fHuf38Rk7PRPvbeJTrrF6/6bmsYJtrol+/6RVRR3r9pke5Q+gvcn/KS6AnURjoYdW0v77ot1n6kd0fcWQ38QDFLZQHoVxmrwSirzVO3+1cnUDsD5UCnay2O1Sr4sTxb8yJPy+n/7Lc7TASTvwo+sUtjgRE+XLmlkYCUhgJgONVzm0YCcDoWuZ2GAlwlOvcVirYygq2uSY8EkARdWzjVeItjoQB5V3rWqC2VPasV1TR6PqO9UqB3FeV/epa5ejU9qtLua0Ko2GRvV3fjK4LjDarkg61nehapiSpbEQ/qHeT4QaxH0XP6JH4qfKe411gp/Gnynskf6q8V+inyntGP1Xes/BT5XeDDR1WNXdoQ4Cwdj1dhsYuc2OXlcYuZWOXubHLamOXorFL0dhlamy8T7gMTV/mpvNScaDhkfhRRBSEygNxEnM48uNw4jow4mE4CRyi9Cg8YggWXuJTIDhs6hJ/kMKvIh1FRLGr/CYSiTl2+ReRiOvY5d9DYoFjl34OKWKIXfgxpBgIjp264VCk/FsRR0rgOI79UoQsImJa+Z0IqVbiW/mVCC2nWOsfiVAixj3/RIQKZeqD6g9EDAXKrW3oA0MUfeMq7ibmiJtEsTauo2wyx9cEjqwJMab5ccAS7/1TIDiC6t7/QdqtF+hu/57QDfp2OLF/ZBOO/FqpDavoNq+iW7mKLosTrkq6MUocKoU3Rgk95PNsBaKK1h9etvJW45nQuN7pVuNQ03SrUfGHSgW2NU4N+s4TSljfcZvUrcYsQXvoVmOmD/K0W02pHaMPO1u+OXcWMdcfb84N1cSbc4Qe8nm2AlGF649L29Hd/Kxy3UmGJpCyqSoP1aps6wo1j+XcysrG+zbfgmQB2hRuQTJ7ECfbKkZ1H3myXC42+jt65+cRla9hbhsaicddjSTCqVmy/Y3EfZMjCb7TkYSy3ZGw7XmM/DKjK4EqYSiPCjMvj/2SMiTGs4ivc8nrXcNn95mLajSV6jWV6jVjvdTUeyn+sTDSKj3Y1HqwqfXgp4xEh95UMjDeAmP1c0ZzgSrxnI/FbV6P27wSm3ktNvNabP47I1HqdjQGC4EqDV6Mf5H9ZbXI7zISbVxWzrmsJO1ytC7LyvhuBaqcuB3r3bbeu22ld9OfqSO51vltJaxtpYlfBCrTDNnMv3PRlUCVAK0qPbMa7RkRsXXlBOvKCdZVO12Pnlqh0Q90AlXq2o1lS1fPlq6SLXxdxXItW7qaVXR6ItwvNC7ivL/JyN+XN7TNpWyRwRyaT9K3XKNvlQh/q2TDNzEL6b99apiXXXiReRy/YZMRrLnya2ht5TW0tv4a2heo6Ol5If7wy9A2fIRO8EV/9/AttXeHol4Ty+tIh8dt9FWmnrm6aD7dly89/P+H8wtTywf7Vc5RxrbSyVqopvjKlf6YW5jQLK+UFu0hl1hX8MgJ1yMnRGtT6nerM/TFYZithlX8sR/F20IrXLsDEjeJVrRiBxpvDa3COh0Y3fFZweociL0wb2h4Ke4UwGGwnBvZLdoOg3QFyzUg2B7A3hyAQ2uAlMYAKm1xFA9CRzlfhINUz0XtY4PXOdmtqU7sYBkOhm8FMuQbEjwP8CH4Tr5g3M2SPPCwT8HL7b7zzA/CuZx32JwuhaLTXdapLutSl9HsCULuyy735TBXOviKzduGg6HmQLyKAyx31GAoGqLxaJwGpXE1Mk3Mw9MkGqPGeaCawKPVhDhkDdO49RubmBx8u/M8Yh/GRmJiGBbZYVpKEVNinhimnDBOiQGvGDNR47aIi0x0o+ToNzFaQMHuA4UsM4mOYDjagmPhDSZGg7Db1KmD2SoKz35RFDcHI8o54KEnhaLTUVVGIp54sqJTRftKetzJvJJI0Wbg3j6FZptJdB1xy35Qwt9qIkTWk/5SE3NlPfIPNZFE1pP/TBMLbD3przQRJuuhP9J0yjRYT8FuPUZiPhkW+WRayidTYj4ZpowxThkDuxKYKNMo4iIT3ShpPSZG6ynYraeQZSbRegxH63EsrMfEaD32Mn7qYLYe8beR6BPuLkaU9cA7AxSKTkdVWY94YYAVnSraetLbAswriRStB14VoNBsM4nWI94TKEp4eo0GFAW2oaiyGUVVWlIsIowpFmB7imoyqSgnq4oyGVYU2baCSplKWrSwIIKRRU45GkWVqbFEzteoU9ZGkbMzqpyjQa1yaVmhyKLGx0KhrTAWIUMMIthi4MsaJ4uMIhklicouYxEyzSB+qaRXMtCgChsNOvhl5NJS+VUiGVK21/qLRLrEd1KXDXfsLSJdZjS9kwWrV4ik9rUS4m2NkzXXXh866HlrldhSVd5kGD7C129DobTqJw7foPfWrdPkTRy/obLhci3+lHhS8Hukp5ZP6BEhVfhOHxu0hXM42v/NXCbxbqBjcauviB8Smdr910L2fz7+WSRlpiUMM2RUyo3e4Q7uaRYH5XBf+OswzR/M5ivO7YDKhA4ovoPtHF+8dmpvWzvyt6ed+evizso+Zif26rShkghPrU1Rb3Kb/N16QLpNjWxTfHXecW5qI5raiKa28SjXua1UsJUVbHNN0nvtrog6+hvsjnLs6fd2N2XdeG5H8f2+TVghOorLQufpLcBNWAA68lWfM1/qOSvrOye2qDNUEuqJtckXfRtMKEBxG88mJRTwtL7dcEIBjmvdTUgoYLSq3QwJBUe5zm2lgq2sYJtrkn6GxxVRR//RHUdxQb3BhDoE/2GC2/ceMPiA4va9hxR84Ol52wMHH3DcNPcQgg+Mtu9ti6v6kY1mR+aqjsTOli27qtO4h2UbXdUZbcLZoqs6iRtStji9HhmKBZrcKNqytM226lw2SuxI2gZbdSTayhuOtsVW/SjXWe0n2rKtOs010duFttFWncWNQdtgq4Z8+TJEHx9InBCiNqUHEsxVg9UDCZao6fmBBAvcHfxAgjHFIS1dKRaiKOekcUpM5yOxECnqUs5T0ypxShlrQi1OrUCVBsosNrHeEM5n4zqpTa61hdPbeKVvU6LDK9OQ60gpAihRxqOk4oN6DhGqFCWUOBKocceiFscAKhQq9bsaOVj6AzweUKIhEaTxYImBEdQ8NlCuxzKNENRGYtlqWm+7HC2ojzaQxwxKethgiZE28uBBqZ4UPIS+lfXquR3FNfi3sF4FlNfg33i9ChTXq47j0vxbXK86o6X5t7Je9aNc57ZSwVZWsM01SetVV0Qdfb3qKF4rfMOZiBHVP81EiYvGqZkoSbkf0kzEnFubZyISWoEqDZS9pGYiliqVrXRanolYoO5LM9HAy/0qhaiJxqkPnYumm5ib7lLuQ9MoLMa53SZwHxahFajSQNmHJtYbwn1oXPehybW2cB8apz7EX0GqYWpq0Kg/oyZCEQrkcEQ5923QKWRB47gEkfsZxbaCR4Ig+zwUGG8o933QdP+HImNt5TwIGuTCv/73/wO+9kRf",ole="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",ale="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",lle="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",dle="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",cle="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",ule="eJxtmNtu20YQhl+F4FULyMGeD7pz3AY1ChtG7NpFA18w1NomIlECSRcxgrx7SVk7+wOdG8H5OJydf2Z2d5gf9cV+t0v9VK/r+6vXsXlOlbHe28paq229qj/t++m62aXZ4J/m8PRb1z9/baZxefK63Z6eXN5dVMvTCh83u277xr/6kLrnl2XNq7TpXnczuZyabdee98/b2VzM/x4/dd/T5qab2pd6PQ2vaVVfvDRD005puE3Lu7eH1HbN9hTjx4/77/X6y5lcnUmjVzHIVVDicVX/1W/SsO36dLMfu6nb9/X6TAoBD+5euvZbn8axXtuZ36dhPJrVQqgPQoh5hev91LWLkIv94W1Ygq9+aX+tZAx2tfz64284/sblN/rqfLP/mqrbt3FKu7G67Nv9cNgPzZQ2H6rz7bb6vLgZq89pTMO/M/xfEqturJpqSM/d7GJIm2oamk3aNcO3av80O5xh3yyKmm1193ZIT02bqovTKjP+MAf++7zsZvZ3276kYyWWXB0z99S18/PbafPHQ71W4fjn/fxnFO+ZvkrT0LVzTr78qB/+nk38bHM9exgP8zr1z9U7jt6840YW5uSJKcZOCaBBnKgm5mU8MVNYyMwWFvO7Ukagkmgg6sDWQ5yFFqjzUrLEaQ3BEmiwNsMSaZS0vgWfOkPHWQowNeTUc0kumnxZvsgPxlGai6VTGUqAVCTQ6QkWnc77DKEiLktSUBJKqHIQZ86d8gCpHYoiEzMsb1ubYy8vW50DChB5ZhGqrijD0EqUIeiaEHIfCg5Kpuu0ApiToaGPSY0uaQsyr65L2oKi1yFt1PLaQ3lzfXTgXodGoJYzglndSLDMPg1sTPJpQJHJigw0QrGERqD9YhyTOgONQDUyuF1zaxuokc/BW2ztXCMrGZ9WMW1oQZHIXWNBkSCfRZEL5BMUiZw6CzVSFCfUSGZFNjIldoKDkonTKQiJIGzWmFd3BizJJ9SINoLDriOfUCOZS+zg+KGD1qGiLNMLxtJD1/ns00ON6EzyUCM6vbxhoBKaqbG3DFQCNiL1iHccBPV0DHhQH/JW8EW90dkyFKGywCJU0WkVSvSGeiSUODWFFD0HYdPQVoiRgfPMA+/nnRgiAyNYSjpWNQcNSMrtFCUH4ZIRpSCWocFCSuhCEY6hoUClc0WC52BJlCYYLQdhN+hygRRRlo5BKRRLS6oihSqh+ZzzRGG1Mo4Iz1LoP0qsxDGFzk0JE42ji0jCPejomJKCuwil4m5CiRMEUMVSzVLDUstSx1Juc0oVWMpqY295qVltmtWmWW2a1aZZbZrVplltmtWmWW2G1WZYbYbVZlhthtVmWG2G1WZYbYbVZlhtltVmWW2W1WZZbZbVZlltltVmWW2W1QYjQCh7E2aAQHeGhCFgPoNoy8KNb2wxBhmGKBxoUZXlLGsLI6AsftEDHV0wIURVbANLcTKlGGBIKPOAxCmhePCKUwFzAmpDFRQvjA9R06Hq8TONvshgKDCuRAZTXigUxjxNFfKRo3CLhnIJBMFRvMZpqpNBMlQJzGT5WFQMVQI/AikPMIhEU1aDjqJvQwmjSHB05cC9jbYwc5UtAHNLhDw41ha+lEqF4JaH3gmB61SYcqInxTDmQK8v08vjqv4zDf1N0w3Lf4A8/vwPpfK11w==";var hle={Courier:tle,"Courier-Bold":Zae,"Courier-Oblique":ele,"Courier-BoldOblique":Jae,Helvetica:sle,"Helvetica-Bold":nle,"Helvetica-Oblique":ile,"Helvetica-BoldOblique":rle,"Times-Roman":dle,"Times-Bold":ole,"Times-Italic":lle,"Times-BoldItalic":ale,Symbol:cle,ZapfDingbats:ule},Wj;(function(n){n.Courier="Courier",n.CourierBold="Courier-Bold",n.CourierOblique="Courier-Oblique",n.CourierBoldOblique="Courier-BoldOblique",n.Helvetica="Helvetica",n.HelveticaBold="Helvetica-Bold",n.HelveticaOblique="Helvetica-Oblique",n.HelveticaBoldOblique="Helvetica-BoldOblique",n.TimesRoman="Times-Roman",n.TimesRomanBold="Times-Bold",n.TimesRomanItalic="Times-Italic",n.TimesRomanBoldItalic="Times-BoldItalic",n.Symbol="Symbol",n.ZapfDingbats="ZapfDingbats"})(Wj||(Wj={}));var B4={},fle=function(){function n(){var e=this;this.getWidthOfGlyph=function(t){return e.CharWidths[t]},this.getXAxisKerningForPair=function(t,r){return(e.KernPairXAmounts[t]||{})[r]}}return n.load=function(e){var t=B4[e];if(t)return t;var r=aq(hle[e]),i=Object.assign(new n,JSON.parse(r));return i.CharWidths=i.CharMetrics.reduce(function(o,a){return o[a.N]=a.WX,o},{}),i.KernPairXAmounts=i.KernPairs.reduce(function(o,a){var l=a[0],d=a[1],c=a[2];return o[l]||(o[l]={}),o[l][d]=c,o},{}),B4[e]=i,i},n}();const ple="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";var gle=aq(ple),PP=JSON.parse(gle),RP=function(){function n(e,t){var r=this;this.canEncodeUnicodeCodePoint=function(i){return i in r.unicodeMappings},this.encodeUnicodeCodePoint=function(i){var o=r.unicodeMappings[i];if(!o){var a=String.fromCharCode(i),l="0x"+$ae(i.toString(16),4,"0"),d=r.name+' cannot encode "'+a+'" ('+l+")";throw new Error(d)}return{code:o[0],name:o[1]}},this.name=e,this.supportedCodePoints=Object.keys(t).map(Number).sort(function(i,o){return i-o}),this.unicodeMappings=t}return n}(),B2={Symbol:new RP("Symbol",PP.symbol),ZapfDingbats:new RP("ZapfDingbats",PP.zapfdingbats),WinAnsi:new RP("WinAnsi",PP.win1252)},OF=function(n){return Object.keys(n).map(function(e){return n[e]})},mle=OF(Wj),I4=function(n){return mle.includes(n)},I2=function(n,e){return n.x===e.x&&n.y===e.y&&n.width===e.width&&n.height===e.height},Ms=function(n){return"`"+n+"`"},yle=function(n){return"'"+n+"'"},M4=function(n){var e=typeof n;return e==="string"?yle(n):e==="undefined"?Ms(n):n},xle=function(n,e,t){for(var r=new Array(t.length),i=0,o=t.length;i<o;i++){var a=t[i];r[i]=M4(a)}var l=r.join(" or ");return Ms(e)+" must be one of "+l+", but was actually "+M4(n)},yg=function(n,e,t){Array.isArray(t)||(t=OF(t));for(var r=0,i=t.length;r<i;r++)if(n===t[r])return;throw new TypeError(xle(n,e,t))},ld=function(n,e,t){Array.isArray(t)||(t=OF(t)),yg(n,e,t.concat(void 0))},ble=function(n,e,t){Array.isArray(t)||(t=OF(t));for(var r=0,i=n.length;r<i;r++)yg(n[r],e,t)},vle=function(n){return n===null?"null":n===void 0?"undefined":typeof n=="string"?"string":isNaN(n)?"NaN":typeof n=="number"?"number":typeof n=="boolean"?"boolean":typeof n=="symbol"?"symbol":typeof n=="bigint"?"bigint":n.constructor&&n.constructor.name?n.constructor.name:n.name?n.name:n.constructor?String(n.constructor):String(n)},wle=function(n,e){return e==="null"?n===null:e==="undefined"?n===void 0:e==="string"?typeof n=="string":e==="number"?typeof n=="number"&&!isNaN(n):e==="boolean"?typeof n=="boolean":e==="symbol"?typeof n=="symbol":e==="bigint"?typeof n=="bigint":e===Date?n instanceof Date:e===Array?n instanceof Array:e===Uint8Array?n instanceof Uint8Array:e===ArrayBuffer?n instanceof ArrayBuffer:e===Function?n instanceof Function:n instanceof e[0]},Sle=function(n,e,t){for(var r=new Array(t.length),i=0,o=t.length;i<o;i++){var a=t[i];a==="null"&&(r[i]=Ms("null")),a==="undefined"&&(r[i]=Ms("undefined")),a==="string"?r[i]=Ms("string"):a==="number"?r[i]=Ms("number"):a==="boolean"?r[i]=Ms("boolean"):a==="symbol"?r[i]=Ms("symbol"):a==="bigint"?r[i]=Ms("bigint"):a===Array?r[i]=Ms("Array"):a===Uint8Array?r[i]=Ms("Uint8Array"):a===ArrayBuffer?r[i]=Ms("ArrayBuffer"):r[i]=Ms(a[1])}var l=r.join(" or ");return Ms(e)+" must be of type "+l+", but was actually of type "+Ms(vle(n))},Ie=function(n,e,t){for(var r=0,i=t.length;r<i;r++)if(wle(n,t[r]))return;throw new TypeError(Sle(n,e,t))},mt=function(n,e,t){Ie(n,e,t.concat("undefined"))},lq=function(n,e,t){for(var r=0,i=n.length;r<i;r++)Ie(n[r],e,t)},Hl=function(n,e,t,r){if(Ie(n,e,["number"]),Ie(t,"min",["number"]),Ie(r,"max",["number"]),r=Math.max(t,r),n<t||n>r)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("<22>");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("<22>");Sn[160]=mn("€");Sn[173]=mn("<22>");var cq=function(n){for(var e=new Array(n.length),t=0,r=n.length;t<r;t++)e[t]=Sn[n[t]];return String.fromCodePoint.apply(String,e)},mf=function(){function n(e){this.populate=e,this.value=void 0}return n.prototype.getValue=function(){return this.value},n.prototype.access=function(){return this.value||(this.value=this.populate()),this.value},n.prototype.invalidate=function(){this.value=void 0},n.populatedBy=function(e){return new n(e)},n}(),Pd=function(n){xt(e,n);function e(t,r){var i=this,o="Method "+t+"."+r+"() not implemented";return i=n.call(this,o)||this,i}return e}(Error),o3=function(n){xt(e,n);function e(t){var r=this,i="Cannot construct "+t+" - it has a private constructor";return r=n.call(this,i)||this,r}return e}(Error),nT=function(n){xt(e,n);function e(t,r){var i=this,o=function(d){var c,u;return(c=d==null?void 0:d.name)!==null&&c!==void 0?c:(u=d==null?void 0:d.constructor)===null||u===void 0?void 0:u.name},a=Array.isArray(t)?t.map(o):[o(t)],l="Expected instance of "+a.join(" or ")+", "+("but got instance of "+(r&&o(r)));return i=n.call(this,l)||this,i}return e}(Error),kle=function(n){xt(e,n);function e(t){var r=this,i=t+" stream encoding not supported";return r=n.call(this,i)||this,r}return e}(Error),a3=function(n){xt(e,n);function e(t,r){var i=this,o="Cannot call "+t+"."+r+"() more than once";return i=n.call(this,o)||this,i}return e}(Error);(function(n){xt(e,n);function e(t){var r=this,i="Missing catalog (ref="+t+")";return r=n.call(this,i)||this,r}return e})(Error);var _le=function(n){xt(e,n);function e(){var t=this,r="Can't embed page with missing Contents";return t=n.call(this,r)||this,t}return e}(Error),Cle=function(n){xt(e,n);function e(t){var r,i,o,a=this,l=(o=(i=(r=t==null?void 0:t.contructor)===null||r===void 0?void 0:r.name)!==null&&i!==void 0?i:t==null?void 0:t.name)!==null&&o!==void 0?o:t,d="Unrecognized stream type: "+l;return a=n.call(this,d)||this,a}return e}(Error),Ale=function(n){xt(e,n);function e(){var t=this,r="Found mismatched contexts while embedding pages. All pages in the array passed to `PDFDocument.embedPages()` must be from the same document.";return t=n.call(this,r)||this,t}return e}(Error),Tle=function(n){xt(e,n);function e(t){var r=this,i="Attempted to convert PDFArray with "+t+" elements to rectangle, but must have exactly 4 elements.";return r=n.call(this,i)||this,r}return e}(Error),uq=function(n){xt(e,n);function e(t){var r=this,i='Attempted to convert "'+t+'" to a date, but it does not match the PDF date string format.';return r=n.call(this,i)||this,r}return e}(Error),z4=function(n){xt(e,n);function e(t,r){var i=this,o="Invalid targetIndex specified: targetIndex="+t+" must be less than Count="+r;return i=n.call(this,o)||this,i}return e}(Error),O4=function(n){xt(e,n);function e(t,r){var i=this,o="Failed to "+r+" at targetIndex="+t+" due to corrupt page tree: It is likely that one or more 'Count' entries are invalid";return i=n.call(this,o)||this,i}return e}(Error),rT=function(n){xt(e,n);function e(t,r,i){var o=this,a="index should be at least "+r+" and at most "+i+", but was actually "+t;return o=n.call(this,a)||this,o}return e}(Error),l3=function(n){xt(e,n);function e(){var t=this,r="Attempted to set invalid field value";return t=n.call(this,r)||this,t}return e}(Error),Fle=function(n){xt(e,n);function e(){var t=this,r="Attempted to select multiple values for single-select field";return t=n.call(this,r)||this,t}return e}(Error),Dle=function(n){xt(e,n);function e(t){var r=this,i="No /DA (default appearance) entry found for field: "+t;return r=n.call(this,i)||this,r}return e}(Error),Ele=function(n){xt(e,n);function e(t){var r=this,i="No Tf operator found for DA of field: "+t;return r=n.call(this,i)||this,r}return e}(Error),L4=function(n){xt(e,n);function e(t,r){var i=this,o="Failed to parse number "+("(line:"+t.line+" col:"+t.column+" offset="+t.offset+'): "'+r+'"');return i=n.call(this,o)||this,i}return e}(Error),Gg=function(n){xt(e,n);function e(t,r){var i=this,o="Failed to parse PDF document "+("(line:"+t.line+" col:"+t.column+" offset="+t.offset+"): "+r);return i=n.call(this,o)||this,i}return e}(Error),Ple=function(n){xt(e,n);function e(t,r,i){var o=this,a="Expected next byte to be "+r+" but it was actually "+i;return o=n.call(this,t,a)||this,o}return e}(Gg),Rle=function(n){xt(e,n);function e(t,r){var i=this,o="Failed to parse PDF object starting with the following byte: "+r;return i=n.call(this,t,o)||this,i}return e}(Gg),Ble=function(n){xt(e,n);function e(t){var r=this,i="Failed to parse invalid PDF object";return r=n.call(this,t,i)||this,r}return e}(Gg),Ile=function(n){xt(e,n);function e(t){var r=this,i="Failed to parse PDF stream";return r=n.call(this,t,i)||this,r}return e}(Gg),Mle=function(n){xt(e,n);function e(t){var r=this,i="Failed to parse PDF literal string due to unbalanced parenthesis";return r=n.call(this,t,i)||this,r}return e}(Gg),zle=function(n){xt(e,n);function e(t){var r=this,i="Parser stalled";return r=n.call(this,t,i)||this,r}return e}(Gg),Ole=function(n){xt(e,n);function e(t){var r=this,i="No PDF header found";return r=n.call(this,t,i)||this,r}return e}(Gg),Lle=function(n){xt(e,n);function e(t,r){var i=this,o="Did not find expected keyword '"+fH(r)+"'";return i=n.call(this,t,o)||this,i}return e}(Gg),MB;(function(n){n[n.Null=0]="Null",n[n.Backspace=8]="Backspace",n[n.Tab=9]="Tab",n[n.Newline=10]="Newline",n[n.FormFeed=12]="FormFeed",n[n.CarriageReturn=13]="CarriageReturn",n[n.Space=32]="Space",n[n.ExclamationPoint=33]="ExclamationPoint",n[n.Hash=35]="Hash",n[n.Percent=37]="Percent",n[n.LeftParen=40]="LeftParen",n[n.RightParen=41]="RightParen",n[n.Plus=43]="Plus",n[n.Minus=45]="Minus",n[n.Dash=45]="Dash",n[n.Period=46]="Period",n[n.ForwardSlash=47]="ForwardSlash",n[n.Zero=48]="Zero",n[n.One=49]="One",n[n.Two=50]="Two",n[n.Three=51]="Three",n[n.Four=52]="Four",n[n.Five=53]="Five",n[n.Six=54]="Six",n[n.Seven=55]="Seven",n[n.Eight=56]="Eight",n[n.Nine=57]="Nine",n[n.LessThan=60]="LessThan",n[n.GreaterThan=62]="GreaterThan",n[n.A=65]="A",n[n.D=68]="D",n[n.E=69]="E",n[n.F=70]="F",n[n.O=79]="O",n[n.P=80]="P",n[n.R=82]="R",n[n.LeftSquareBracket=91]="LeftSquareBracket",n[n.BackSlash=92]="BackSlash",n[n.RightSquareBracket=93]="RightSquareBracket",n[n.a=97]="a",n[n.b=98]="b",n[n.d=100]="d",n[n.e=101]="e",n[n.f=102]="f",n[n.i=105]="i",n[n.j=106]="j",n[n.l=108]="l",n[n.m=109]="m",n[n.n=110]="n",n[n.o=111]="o",n[n.r=114]="r",n[n.s=115]="s",n[n.t=116]="t",n[n.u=117]="u",n[n.x=120]="x",n[n.LeftCurly=123]="LeftCurly",n[n.RightCurly=125]="RightCurly",n[n.Tilde=126]="Tilde"})(MB||(MB={}));const le=MB;var NF=function(){function n(e,t){this.major=String(e),this.minor=String(t)}return n.prototype.toString=function(){var e=gf(129);return"%PDF-"+this.major+"."+this.minor+`
%`+e+e+e+e},n.prototype.sizeInBytes=function(){return 12+this.major.length+this.minor.length},n.prototype.copyBytesInto=function(e,t){var r=t;return e[t++]=le.Percent,e[t++]=le.P,e[t++]=le.D,e[t++]=le.F,e[t++]=le.Dash,t+=Ro(this.major,e,t),e[t++]=le.Period,t+=Ro(this.minor,e,t),e[t++]=le.Newline,e[t++]=le.Percent,e[t++]=129,e[t++]=129,e[t++]=129,e[t++]=129,t-r},n.forVersion=function(e,t){return new n(e,t)},n}(),Ca=function(){function n(){}return n.prototype.clone=function(e){throw new Pd(this.constructor.name,"clone")},n.prototype.toString=function(){throw new Pd(this.constructor.name,"toString")},n.prototype.sizeInBytes=function(){throw new Pd(this.constructor.name,"sizeInBytes")},n.prototype.copyBytesInto=function(e,t){throw new Pd(this.constructor.name,"copyBytesInto")},n}(),fn=function(n){xt(e,n);function e(t){var r=n.call(this)||this;return r.numberValue=t,r.stringValue=noe(t),r}return e.prototype.asNumber=function(){return this.numberValue},e.prototype.value=function(){return this.numberValue},e.prototype.clone=function(){return e.of(this.numberValue)},e.prototype.toString=function(){return this.stringValue},e.prototype.sizeInBytes=function(){return this.stringValue.length},e.prototype.copyBytesInto=function(t,r){return r+=Ro(this.stringValue,t,r),this.stringValue.length},e.of=function(t){return new e(t)},e}(Ca),Sr=function(n){xt(e,n);function e(t){var r=n.call(this)||this;return r.array=[],r.context=t,r}return e.prototype.size=function(){return this.array.length},e.prototype.push=function(t){this.array.push(t)},e.prototype.insert=function(t,r){this.array.splice(t,0,r)},e.prototype.indexOf=function(t){var r=this.array.indexOf(t);return r===-1?void 0:r},e.prototype.remove=function(t){this.array.splice(t,1)},e.prototype.set=function(t,r){this.array[t]=r},e.prototype.get=function(t){return this.array[t]},e.prototype.lookupMaybe=function(t){for(var r,i=[],o=1;o<arguments.length;o++)i[o-1]=arguments[o];return(r=this.context).lookupMaybe.apply(r,fr([this.get(t)],i))},e.prototype.lookup=function(t){for(var r,i=[],o=1;o<arguments.length;o++)i[o-1]=arguments[o];return(r=this.context).lookup.apply(r,fr([this.get(t)],i))},e.prototype.asRectangle=function(){if(this.size()!==4)throw new Tle(this.size());var t=this.lookup(0,fn).asNumber(),r=this.lookup(1,fn).asNumber(),i=this.lookup(2,fn).asNumber(),o=this.lookup(3,fn).asNumber(),a=t,l=r,d=i-t,c=o-r;return{x:a,y:l,width:d,height:c}},e.prototype.asArray=function(){return this.array.slice()},e.prototype.clone=function(t){for(var r=e.withContext(t||this.context),i=0,o=this.size();i<o;i++)r.push(this.array[i]);return r},e.prototype.toString=function(){for(var t="[ ",r=0,i=this.size();r<i;r++)t+=this.get(r).toString(),t+=" ";return t+="]",t},e.prototype.sizeInBytes=function(){for(var t=3,r=0,i=this.size();r<i;r++)t+=this.get(r).sizeInBytes()+1;return t},e.prototype.copyBytesInto=function(t,r){var i=r;t[r++]=le.LeftSquareBracket,t[r++]=le.Space;for(var o=0,a=this.size();o<a;o++)r+=this.get(o).copyBytesInto(t,r),t[r++]=le.Space;return t[r++]=le.RightSquareBracket,r-i},e.prototype.scalePDFNumbers=function(t,r){for(var i=0,o=this.size();i<o;i++){var a=this.lookup(i);if(a instanceof fn){var l=i%2===0?t:r;this.set(i,fn.of(a.asNumber()*l))}}},e.withContext=function(t){return new e(t)},e}(Ca),BP={},Uj=function(n){xt(e,n);function e(t,r){var i=this;if(t!==BP)throw new o3("PDFBool");return i=n.call(this)||this,i.value=r,i}return e.prototype.asBoolean=function(){return this.value},e.prototype.clone=function(){return this},e.prototype.toString=function(){return String(this.value)},e.prototype.sizeInBytes=function(){return this.value?4:5},e.prototype.copyBytesInto=function(t,r){return this.value?(t[r++]=le.t,t[r++]=le.r,t[r++]=le.u,t[r++]=le.e,4):(t[r++]=le.f,t[r++]=le.a,t[r++]=le.l,t[r++]=le.s,t[r++]=le.e,5)},e.True=new e(BP,!0),e.False=new e(BP,!1),e}(Ca),qd=new Uint8Array(256);qd[le.LeftParen]=1;qd[le.RightParen]=1;qd[le.LessThan]=1;qd[le.GreaterThan]=1;qd[le.LeftSquareBracket]=1;qd[le.RightSquareBracket]=1;qd[le.LeftCurly]=1;qd[le.RightCurly]=1;qd[le.ForwardSlash]=1;qd[le.Percent]=1;var Bf=new Uint8Array(256);Bf[le.Null]=1;Bf[le.Tab]=1;Bf[le.Newline]=1;Bf[le.FormFeed]=1;Bf[le.CarriageReturn]=1;Bf[le.Space]=1;var d3=new Uint8Array(256);for(var Ow=0,Nle=256;Ow<Nle;Ow++)d3[Ow]=Bf[Ow]||qd[Ow]?1:0;d3[le.Hash]=1;var Wle=function(n){return n.replace(/#([\dABCDEF]{2})/g,function(e,t){return Mse(t)})},Ule=function(n){return n>=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<l;a++){var d=r[a],c=mn(d);o+=Ule(c)?d:"#"+RF(c)}return i.encodedName=o,i}return e.prototype.asBytes=function(){for(var t=[],r="",i=!1,o=function(f){f!==void 0&&t.push(f),i=!1},a=1,l=this.encodedName.length;a<l;a++){var d=this.encodedName[a],c=mn(d),u=this.encodedName[a+1];i?c>=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;o<arguments.length;o++)i[o-1]=arguments[o];var a=i.includes(Ya),l=(r=this.context).lookupMaybe.apply(r,fr([this.get(t,a)],i));if(!(l===Ya&&!a))return l},e.prototype.lookup=function(t){for(var r,i=[],o=1;o<arguments.length;o++)i[o-1]=arguments[o];var a=i.includes(Ya),l=(r=this.context).lookup.apply(r,fr([this.get(t,a)],i));if(!(l===Ya&&!a))return l},e.prototype.delete=function(t){return this.dict.delete(t)},e.prototype.asMap=function(){return new Map(this.dict)},e.prototype.uniqueKey=function(t){t===void 0&&(t="");for(var r=this.keys(),i=se.of(this.context.addRandomSuffix(t,10));r.includes(i);)i=se.of(this.context.addRandomSuffix(t,10));return i},e.prototype.clone=function(t){for(var r=e.withContext(t||this.context),i=this.entries(),o=0,a=i.length;o<a;o++){var l=i[o],d=l[0],c=l[1];r.set(d,c)}return r},e.prototype.toString=function(){for(var t=`<<
`,r=this.entries(),i=0,o=r.length;i<o;i++){var a=r[i],l=a[0],d=a[1];t+=l.toString()+" "+d.toString()+`
`}return t+=">>",t},e.prototype.sizeInBytes=function(){for(var t=5,r=this.entries(),i=0,o=r.length;i<o;i++){var a=r[i],l=a[0],d=a[1];t+=l.sizeInBytes()+d.sizeInBytes()+2}return t},e.prototype.copyBytesInto=function(t,r){var i=r;t[r++]=le.LessThan,t[r++]=le.LessThan,t[r++]=le.Newline;for(var o=this.entries(),a=0,l=o.length;a<l;a++){var d=o[a],c=d[0],u=d[1];r+=c.copyBytesInto(t,r),t[r++]=le.Space,r+=u.copyBytesInto(t,r),t[r++]=le.Newline}return t[r++]=le.GreaterThan,t[r++]=le.GreaterThan,r-i},e.withContext=function(t){return new e(new Map,t)},e.fromMapWithContext=function(t,r){return new e(t,r)},e}(Ca),Gl=function(n){xt(e,n);function e(t){var r=n.call(this)||this;return r.dict=t,r}return e.prototype.clone=function(t){throw new Pd(this.constructor.name,"clone")},e.prototype.getContentsString=function(){throw new Pd(this.constructor.name,"getContentsString")},e.prototype.getContents=function(){throw new Pd(this.constructor.name,"getContents")},e.prototype.getContentsSize=function(){throw new Pd(this.constructor.name,"getContentsSize")},e.prototype.updateDict=function(){var t=this.getContentsSize();this.dict.set(se.Length,fn.of(t))},e.prototype.sizeInBytes=function(){return this.updateDict(),this.dict.sizeInBytes()+this.getContentsSize()+18},e.prototype.toString=function(){this.updateDict();var t=this.dict.toString();return t+=`
stream
`,t+=this.getContentsString(),t+=`
endstream`,t},e.prototype.copyBytesInto=function(t,r){this.updateDict();var i=r;r+=this.dict.copyBytesInto(t,r),t[r++]=le.Newline,t[r++]=le.s,t[r++]=le.t,t[r++]=le.r,t[r++]=le.e,t[r++]=le.a,t[r++]=le.m,t[r++]=le.Newline;for(var o=this.getContents(),a=0,l=o.length;a<l;a++)t[r++]=o[a];return t[r++]=le.Newline,t[r++]=le.e,t[r++]=le.n,t[r++]=le.d,t[r++]=le.s,t[r++]=le.t,t[r++]=le.r,t[r++]=le.e,t[r++]=le.a,t[r++]=le.m,r-i},e}(Ca),Hj=function(n){xt(e,n);function e(t,r){var i=n.call(this,t)||this;return i.contents=r,i}return e.prototype.asUint8Array=function(){return this.contents.slice()},e.prototype.clone=function(t){return e.of(this.dict.clone(t),this.contents.slice())},e.prototype.getContentsString=function(){return fH(this.contents)},e.prototype.getContents=function(){return this.contents},e.prototype.getContentsSize=function(){return this.contents.length},e.of=function(t,r){return new e(t,r)},e}(Gl),U4={},H4=new Map,Mr=function(n){xt(e,n);function e(t,r,i){var o=this;if(t!==U4)throw new o3("PDFRef");return o=n.call(this)||this,o.objectNumber=r,o.generationNumber=i,o.tag=r+" "+i+" R",o}return e.prototype.clone=function(){return this},e.prototype.toString=function(){return this.tag},e.prototype.sizeInBytes=function(){return this.tag.length},e.prototype.copyBytesInto=function(t,r){return r+=Ro(this.tag,t,r),this.tag.length},e.of=function(t,r){r===void 0&&(r=0);var i=t+" "+r+" R",o=H4.get(i);return o||(o=new e(U4,t,r),H4.set(i,o)),o},e}(Ca),or=function(){function n(e,t){this.name=e,this.args=t||[]}return n.prototype.clone=function(e){for(var t=new Array(this.args.length),r=0,i=t.length;r<i;r++){var o=this.args[r];t[r]=o instanceof Ca?o.clone(e):o}return n.of(this.name,t)},n.prototype.toString=function(){for(var e="",t=0,r=this.args.length;t<r;t++)e+=String(this.args[t])+" ";return e+=this.name,e},n.prototype.sizeInBytes=function(){for(var e=0,t=0,r=this.args.length;t<r;t++){var i=this.args[t];e+=(i instanceof Ca?i.sizeInBytes():i.length)+1}return e+=this.name.length,e},n.prototype.copyBytesInto=function(e,t){for(var r=t,i=0,o=this.args.length;i<o;i++){var a=this.args[i];a instanceof Ca?t+=a.copyBytesInto(e,t):t+=Ro(a,e,t),e[t++]=le.Space}return t+=Ro(this.name,e,t),t-r},n.of=function(e,t){return new n(e,t)},n}(),zB;(function(n){n.NonStrokingColor="sc",n.NonStrokingColorN="scn",n.NonStrokingColorRgb="rg",n.NonStrokingColorGray="g",n.NonStrokingColorCmyk="k",n.NonStrokingColorspace="cs",n.StrokingColor="SC",n.StrokingColorN="SCN",n.StrokingColorRgb="RG",n.StrokingColorGray="G",n.StrokingColorCmyk="K",n.StrokingColorspace="CS",n.BeginMarkedContentSequence="BDC",n.BeginMarkedContent="BMC",n.EndMarkedContent="EMC",n.MarkedContentPointWithProps="DP",n.MarkedContentPoint="MP",n.DrawObject="Do",n.ConcatTransformationMatrix="cm",n.PopGraphicsState="Q",n.PushGraphicsState="q",n.SetFlatness="i",n.SetGraphicsStateParams="gs",n.SetLineCapStyle="J",n.SetLineDashPattern="d",n.SetLineJoinStyle="j",n.SetLineMiterLimit="M",n.SetLineWidth="w",n.SetTextMatrix="Tm",n.SetRenderingIntent="ri",n.AppendRectangle="re",n.BeginInlineImage="BI",n.BeginInlineImageData="ID",n.EndInlineImage="EI",n.ClipEvenOdd="W*",n.ClipNonZero="W",n.CloseAndStroke="s",n.CloseFillEvenOddAndStroke="b*",n.CloseFillNonZeroAndStroke="b",n.ClosePath="h",n.AppendBezierCurve="c",n.CurveToReplicateFinalPoint="y",n.CurveToReplicateInitialPoint="v",n.EndPath="n",n.FillEvenOddAndStroke="B*",n.FillEvenOdd="f*",n.FillNonZeroAndStroke="B",n.FillNonZero="f",n.LegacyFillNonZero="F",n.LineTo="l",n.MoveTo="m",n.ShadingFill="sh",n.StrokePath="S",n.BeginText="BT",n.EndText="ET",n.MoveText="Td",n.MoveTextSetLeading="TD",n.NextLine="T*",n.SetCharacterSpacing="Tc",n.SetFontAndSize="Tf",n.SetTextHorizontalScaling="Tz",n.SetTextLineHeight="TL",n.SetTextRenderingMode="Tr",n.SetTextRise="Ts",n.SetWordSpacing="Tw",n.ShowText="Tj",n.ShowTextAdjusted="TJ",n.ShowTextLine="'",n.ShowTextLineAndSpace='"',n.Type3D0="d0",n.Type3D1="d1",n.BeginCompatibilitySection="BX",n.EndCompatibilitySection="EX"})(zB||(zB={}));const pr=zB;var c3=function(n){xt(e,n);function e(t,r){var i=n.call(this,t)||this;return i.computeContents=function(){var o=i.getUnencodedContents();return i.encode?zF.deflate(o):o},i.encode=r,r&&t.set(se.of("Filter"),se.of("FlateDecode")),i.contentsCache=mf.populatedBy(i.computeContents),i}return e.prototype.getContents=function(){return this.contentsCache.access()},e.prototype.getContentsSize=function(){return this.contentsCache.access().length},e.prototype.getUnencodedContents=function(){throw new Pd(this.constructor.name,"getUnencodedContents")},e}(Gl),ZS=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!0);var o=n.call(this,t,i)||this;return o.operators=r,o}return e.prototype.push=function(){for(var t,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];(t=this.operators).push.apply(t,r)},e.prototype.clone=function(t){for(var r=new Array(this.operators.length),i=0,o=this.operators.length;i<o;i++)r[i]=this.operators[i].clone(t);var a=this,l=a.dict,d=a.encode;return e.of(l.clone(t),r,d)},e.prototype.getContentsString=function(){for(var t="",r=0,i=this.operators.length;r<i;r++)t+=this.operators[r]+`
`;return t},e.prototype.getUnencodedContents=function(){for(var t=new Uint8Array(this.getUnencodedContentsSize()),r=0,i=0,o=this.operators.length;i<o;i++)r+=this.operators[i].copyBytesInto(t,r),t[r++]=le.Newline;return t},e.prototype.getUnencodedContentsSize=function(){for(var t=0,r=0,i=this.operators.length;r<i;r++)t+=this.operators[r].sizeInBytes()+1;return t},e.of=function(t,r,i){return i===void 0&&(i=!0),new e(t,r,i)},e}(c3),qle=function(){function n(e){this.seed=e}return n.prototype.nextInt=function(){var e=Math.sin(this.seed++)*1e4;return e-Math.floor(e)},n.withSeed=function(e){return new n(e)},n}(),Vle=function(n,e){var t=n[0],r=e[0];return t.objectNumber-r.objectNumber},OB=function(){function n(){this.largestObjectNumber=0,this.header=NF.forVersion(1,7),this.trailerInfo={},this.indirectObjects=new Map,this.rng=qle.withSeed(1)}return n.prototype.assign=function(e,t){this.indirectObjects.set(e,t),e.objectNumber>this.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;r<arguments.length;r++)t[r-1]=arguments[r];var i=t.includes(Ya),o=e instanceof Mr?this.indirectObjects.get(e):e;if(!(!o||o===Ya&&!i)){for(var a=0,l=t.length;a<l;a++){var d=t[a];if(d===Ya){if(o===Ya)return o}else if(o instanceof d)return o}throw new nT(t,o)}},n.prototype.lookup=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var i=e instanceof Mr?this.indirectObjects.get(e):e;if(t.length===0)return i;for(var o=0,a=t.length;o<a;o++){var l=t[o];if(l===Ya){if(i===Ya)return i}else if(i instanceof l)return i}throw new nT(t,i)},n.prototype.getObjectRef=function(e){for(var t=Array.from(this.indirectObjects.entries()),r=0,i=t.length;r<i;r++){var o=t[r],a=o[0],l=o[1];if(l===e)return a}},n.prototype.enumerateIndirectObjects=function(){return Array.from(this.indirectObjects.entries()).sort(Vle)},n.prototype.obj=function(e){if(e instanceof Ca)return e;if(e==null)return Ya;if(typeof e=="string")return se.of(e);if(typeof e=="number")return fn.of(e);if(typeof e=="boolean")return e?Uj.True:Uj.False;if(Array.isArray(e)){for(var t=Sr.withContext(this),r=0,i=e.length;r<i;r++)t.push(this.obj(e[r]));return t}else{for(var o=_n.withContext(this),a=Object.keys(e),r=0,i=a.length;r<i;r++){var l=a[r],d=e[l];d!==void 0&&o.set(se.of(l),this.obj(d))}return o}},n.prototype.stream=function(e,t){return t===void 0&&(t={}),Hj.of(this.obj(t),AB(e))},n.prototype.flateStream=function(e,t){return t===void 0&&(t={}),this.stream(zF.deflate(AB(e)),wn(wn({},t),{Filter:"FlateDecode"}))},n.prototype.contentStream=function(e,t){return t===void 0&&(t={}),ZS.of(this.obj(t),e)},n.prototype.formXObject=function(e,t){return t===void 0&&(t={}),this.contentStream(e,wn(wn({BBox:this.obj([0,0,0,0]),Matrix:this.obj([1,0,0,1,0,0])},t),{Type:"XObject",Subtype:"Form"}))},n.prototype.getPushGraphicsStateContentStream=function(){if(this.pushGraphicsStateContentStreamRef)return this.pushGraphicsStateContentStreamRef;var e=this.obj({}),t=or.of(pr.PushGraphicsState),r=ZS.of(e,[t]);return this.pushGraphicsStateContentStreamRef=this.register(r),this.pushGraphicsStateContentStreamRef},n.prototype.getPopGraphicsStateContentStream=function(){if(this.popGraphicsStateContentStreamRef)return this.popGraphicsStateContentStreamRef;var e=this.obj({}),t=or.of(pr.PopGraphicsState),r=ZS.of(e,[t]);return this.popGraphicsStateContentStreamRef=this.register(r),this.popGraphicsStateContentStreamRef},n.prototype.addRandomSuffix=function(e,t){return t===void 0&&(t=4),e+"-"+Math.floor(this.rng.nextInt()*Math.pow(10,t))},n.create=function(){return new n},n}(),yf=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!0);var o=n.call(this,t,r)||this;return o.normalized=!1,o.autoNormalizeCTM=i,o}return e.prototype.clone=function(t){for(var r=e.fromMapWithContext(new Map,t||this.context,this.autoNormalizeCTM),i=this.entries(),o=0,a=i.length;o<a;o++){var l=i[o],d=l[0],c=l[1];r.set(d,c)}return r},e.prototype.Parent=function(){return this.lookupMaybe(se.Parent,_n)},e.prototype.Contents=function(){return this.lookup(se.of("Contents"))},e.prototype.Annots=function(){return this.lookupMaybe(se.Annots,Sr)},e.prototype.BleedBox=function(){return this.lookupMaybe(se.BleedBox,Sr)},e.prototype.TrimBox=function(){return this.lookupMaybe(se.TrimBox,Sr)},e.prototype.ArtBox=function(){return this.lookupMaybe(se.ArtBox,Sr)},e.prototype.Resources=function(){var t=this.getInheritableAttribute(se.Resources);return this.context.lookupMaybe(t,_n)},e.prototype.MediaBox=function(){var t=this.getInheritableAttribute(se.MediaBox);return this.context.lookup(t,Sr)},e.prototype.CropBox=function(){var t=this.getInheritableAttribute(se.CropBox);return this.context.lookupMaybe(t,Sr)},e.prototype.Rotate=function(){var t=this.getInheritableAttribute(se.Rotate);return this.context.lookupMaybe(t,fn)},e.prototype.getInheritableAttribute=function(t){var r;return this.ascend(function(i){r||(r=i.get(t))}),r},e.prototype.setParent=function(t){this.set(se.Parent,t)},e.prototype.addContentStream=function(t){var r=this.normalizedEntries().Contents||this.context.obj([]);this.set(se.Contents,r),r.push(t)},e.prototype.wrapContentStreams=function(t,r){var i=this.Contents();return i instanceof Sr?(i.insert(0,t),i.push(r),!0):!1},e.prototype.addAnnot=function(t){var r=this.normalizedEntries().Annots;r.push(t)},e.prototype.removeAnnot=function(t){var r=this.normalizedEntries().Annots,i=r.indexOf(t);i!==void 0&&r.remove(i)},e.prototype.setFontDictionary=function(t,r){var i=this.normalizedEntries().Font;i.set(t,r)},e.prototype.newFontDictionaryKey=function(t){var r=this.normalizedEntries().Font;return r.uniqueKey(t)},e.prototype.newFontDictionary=function(t,r){var i=this.newFontDictionaryKey(t);return this.setFontDictionary(i,r),i},e.prototype.setXObject=function(t,r){var i=this.normalizedEntries().XObject;i.set(t,r)},e.prototype.newXObjectKey=function(t){var r=this.normalizedEntries().XObject;return r.uniqueKey(t)},e.prototype.newXObject=function(t,r){var i=this.newXObjectKey(t);return this.setXObject(i,r),i},e.prototype.setExtGState=function(t,r){var i=this.normalizedEntries().ExtGState;i.set(t,r)},e.prototype.newExtGStateKey=function(t){var r=this.normalizedEntries().ExtGState;return r.uniqueKey(t)},e.prototype.newExtGState=function(t,r){var i=this.newExtGStateKey(t);return this.setExtGState(i,r),i},e.prototype.ascend=function(t){t(this);var r=this.Parent();r&&r.ascend(t)},e.prototype.normalize=function(){if(!this.normalized){var t=this.context,r=this.get(se.Contents),i=this.context.lookup(r);i instanceof Gl&&this.set(se.Contents,t.obj([r])),this.autoNormalizeCTM&&this.wrapContentStreams(this.context.getPushGraphicsStateContentStream(),this.context.getPopGraphicsStateContentStream());var o=this.getInheritableAttribute(se.Resources),a=t.lookupMaybe(o,_n)||t.obj({});this.set(se.Resources,a);var l=a.lookupMaybe(se.Font,_n)||t.obj({});a.set(se.Font,l);var d=a.lookupMaybe(se.XObject,_n)||t.obj({});a.set(se.XObject,d);var c=a.lookupMaybe(se.ExtGState,_n)||t.obj({});a.set(se.ExtGState,c);var u=this.Annots()||t.obj([]);this.set(se.Annots,u),this.normalized=!0}},e.prototype.normalizedEntries=function(){this.normalize();var t=this.Annots(),r=this.Resources(),i=this.Contents();return{Annots:t,Resources:r,Contents:i,Font:r.lookup(se.Font,_n),XObject:r.lookup(se.XObject,_n),ExtGState:r.lookup(se.ExtGState,_n)}},e.InheritableEntries=["Resources","MediaBox","CropBox","Rotate"],e.withContextAndParent=function(t,r){var i=new Map;return i.set(se.Type,se.Page),i.set(se.Parent,r),i.set(se.Resources,t.obj({})),i.set(se.MediaBox,t.obj([0,0,612,792])),new e(i,t,!1)},e.fromMapWithContext=function(t,r,i){return i===void 0&&(i=!0),new e(t,r,i)},e}(_n),q4=function(){function n(e,t){var r=this;this.traversedObjects=new Map,this.copy=function(i){return i instanceof yf?r.copyPDFPage(i):i instanceof _n?r.copyPDFDict(i):i instanceof Sr?r.copyPDFArray(i):i instanceof Gl?r.copyPDFStream(i):i instanceof Mr?r.copyPDFIndirectObject(i):i.clone()},this.copyPDFPage=function(i){for(var o=i.clone(),a=yf.InheritableEntries,l=0,d=a.length;l<d;l++){var c=se.of(a[l]),u=o.getInheritableAttribute(c);!o.get(c)&&u&&o.set(c,u)}return o.delete(se.of("Parent")),r.copyPDFDict(o)},this.copyPDFDict=function(i){if(r.traversedObjects.has(i))return r.traversedObjects.get(i);var o=i.clone(r.dest);r.traversedObjects.set(i,o);for(var a=i.entries(),l=0,d=a.length;l<d;l++){var c=a[l],u=c[0],f=c[1];o.set(u,r.copy(f))}return o},this.copyPDFArray=function(i){if(r.traversedObjects.has(i))return r.traversedObjects.get(i);var o=i.clone(r.dest);r.traversedObjects.set(i,o);for(var a=0,l=i.size();a<l;a++){var d=i.get(a);o.set(a,r.copy(d))}return o},this.copyPDFStream=function(i){if(r.traversedObjects.has(i))return r.traversedObjects.get(i);var o=i.clone(r.dest);r.traversedObjects.set(i,o);for(var a=i.dict.entries(),l=0,d=a.length;l<d;l++){var c=a[l],u=c[0],f=c[1];o.dict.set(u,r.copy(f))}return o},this.copyPDFIndirectObject=function(i){var o=r.traversedObjects.has(i);if(!o){var a=r.dest.nextRef();r.traversedObjects.set(i,a);var l=r.src.lookup(i);if(l){var d=r.copy(l);r.dest.assign(a,d)}}return r.traversedObjects.get(i)},this.src=e,this.dest=t}return n.for=function(e,t){return new n(e,t)},n}(),hq=function(){function n(e){this.subsections=e?[[e]]:[],this.chunkIdx=0,this.chunkLength=e?1:0}return n.prototype.addEntry=function(e,t){this.append({ref:e,offset:t,deleted:!1})},n.prototype.addDeletedEntry=function(e,t){this.append({ref:e,offset:t,deleted:!0})},n.prototype.toString=function(){for(var e=`xref
`,t=0,r=this.subsections.length;t<r;t++){var i=this.subsections[t];e+=i[0].ref.objectNumber+" "+i.length+`
`;for(var o=0,a=i.length;o<a;o++){var l=i[o];e+=_c(String(l.offset),10,"0"),e+=" ",e+=_c(String(l.ref.generationNumber),5,"0"),e+=" ",e+=l.deleted?"f":"n",e+=`
`}}return e},n.prototype.sizeInBytes=function(){for(var e=5,t=0,r=this.subsections.length;t<r;t++){var i=this.subsections[t],o=i.length,a=i[0];e+=2,e+=String(a.ref.objectNumber).length,e+=String(o).length,e+=20*o}return e},n.prototype.copyBytesInto=function(e,t){var r=t;return e[t++]=le.x,e[t++]=le.r,e[t++]=le.e,e[t++]=le.f,e[t++]=le.Newline,t+=this.copySubsectionsIntoBuffer(this.subsections,e,t),t-r},n.prototype.copySubsectionsIntoBuffer=function(e,t,r){for(var i=r,o=e.length,a=0;a<o;a++){var l=this.subsections[a],d=String(l[0].ref.objectNumber);r+=Ro(d,t,r),t[r++]=le.Space;var c=String(l.length);r+=Ro(c,t,r),t[r++]=le.Newline,r+=this.copyEntriesIntoBuffer(l,t,r)}return r-i},n.prototype.copyEntriesIntoBuffer=function(e,t,r){for(var i=e.length,o=0;o<i;o++){var a=e[o],l=_c(String(a.offset),10,"0");r+=Ro(l,t,r),t[r++]=le.Space;var d=_c(String(a.ref.generationNumber),5,"0");r+=Ro(d,t,r),t[r++]=le.Space,t[r++]=a.deleted?le.f:le.n,t[r++]=le.Space,t[r++]=le.Newline}return 20*i},n.prototype.append=function(e){if(this.chunkLength===0){this.subsections.push([e]),this.chunkIdx=0,this.chunkLength=1;return}var t=this.subsections[this.chunkIdx],r=t[this.chunkLength-1];e.ref.objectNumber-r.ref.objectNumber>1?(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;r<i;r++){var o=this.objects[r],a=o[1];t+=a+`
`}return t},e.prototype.getUnencodedContents=function(){for(var t=new Uint8Array(this.getUnencodedContentsSize()),r=Ro(this.offsetsString,t,0),i=0,o=this.objects.length;i<o;i++){var a=this.objects[i],l=a[1];r+=l.copyBytesInto(t,r),t[r++]=le.Newline}return t},e.prototype.getUnencodedContentsSize=function(){return this.offsetsString.length+JA(this.offsets)[1]+JA(this.objects)[1].sizeInBytes()+1},e.prototype.computeOffsetsString=function(){for(var t="",r=0,i=this.offsets.length;r<i;r++){var o=this.offsets[r],a=o[0],l=o[1];t+=a+" "+l+" "}return t},e.prototype.computeObjectOffsets=function(){for(var t=0,r=new Array(this.objects.length),i=0,o=this.objects.length;i<o;i++){var a=this.objects[i],l=a[0],d=a[1];r[i]=[l.objectNumber,t],t+=d.sizeInBytes()+1}return r},e.withContextAndObjects=function(t,r,i){return i===void 0&&(i=!0),new e(t,r,i)},e}(c3),pq=function(){function n(e,t){var r=this;this.parsedObjects=0,this.shouldWaitForTick=function(i){return r.parsedObjects+=i,r.parsedObjects%r.objectsPerTick===0},this.context=e,this.objectsPerTick=t}return n.prototype.serializeToBuffer=function(){return Pn(this,void 0,void 0,function(){var e,t,r,i,o,a,l,d,c,u,f,p,g,m,y,v,x;return Rn(this,function(w){switch(w.label){case 0:return[4,this.computeBufferSize()];case 1:e=w.sent(),t=e.size,r=e.header,i=e.indirectObjects,o=e.xref,a=e.trailerDict,l=e.trailer,d=0,c=new Uint8Array(t),d+=r.copyBytesInto(c,d),c[d++]=le.Newline,c[d++]=le.Newline,u=0,f=i.length,w.label=2;case 2:return u<f?(p=i[u],g=p[0],m=p[1],y=String(g.objectNumber),d+=Ro(y,c,d),c[d++]=le.Space,v=String(g.generationNumber),d+=Ro(v,c,d),c[d++]=le.Space,c[d++]=le.o,c[d++]=le.b,c[d++]=le.j,c[d++]=le.Newline,d+=m.copyBytesInto(c,d),c[d++]=le.Newline,c[d++]=le.e,c[d++]=le.n,c[d++]=le.d,c[d++]=le.o,c[d++]=le.b,c[d++]=le.j,c[d++]=le.Newline,c[d++]=le.Newline,x=m instanceof fq?m.getObjectsCount():1,this.shouldWaitForTick(x)?[4,a1()]:[3,4]):[3,5];case 3:w.sent(),w.label=4;case 4:return u++,[3,2];case 5:return o&&(d+=o.copyBytesInto(c,d),c[d++]=le.Newline),a&&(d+=a.copyBytesInto(c,d),c[d++]=le.Newline,c[d++]=le.Newline),d+=l.copyBytesInto(c,d),[2,c]}})})},n.prototype.computeIndirectObjectSize=function(e){var t=e[0],r=e[1],i=t.sizeInBytes()+3,o=r.sizeInBytes()+9;return i+o},n.prototype.createTrailerDict=function(){return this.context.obj({Size:this.context.largestObjectNumber+1,Root:this.context.trailerInfo.Root,Encrypt:this.context.trailerInfo.Encrypt,Info:this.context.trailerInfo.Info,ID:this.context.trailerInfo.ID})},n.prototype.computeBufferSize=function(){return Pn(this,void 0,void 0,function(){var e,t,r,i,o,a,l,d,c,u,f;return Rn(this,function(p){switch(p.label){case 0:e=NF.forVersion(1,7),t=e.sizeInBytes()+2,r=hq.create(),i=this.context.enumerateIndirectObjects(),o=0,a=i.length,p.label=1;case 1:return o<a?(l=i[o],d=l[0],r.addEntry(d,t),t+=this.computeIndirectObjectSize(l),this.shouldWaitForTick(1)?[4,a1()]:[3,3]):[3,4];case 2:p.sent(),p.label=3;case 3:return o++,[3,1];case 4:return c=t,t+=r.sizeInBytes()+1,u=Gle.of(this.createTrailerDict()),t+=u.sizeInBytes()+2,f=u3.forLastCrossRefSectionOffset(c),t+=f.sizeInBytes(),[2,{size:t,header:e,indirectObjects:i,xref:r,trailerDict:u,trailer:f}]}})})},n.forContext=function(e,t){return new n(e,t)},n}(),gq=function(n){xt(e,n);function e(t){var r=n.call(this)||this;return r.data=t,r}return e.prototype.clone=function(){return e.of(this.data.slice())},e.prototype.toString=function(){return"PDFInvalidObject("+this.data.length+" bytes)"},e.prototype.sizeInBytes=function(){return this.data.length},e.prototype.copyBytesInto=function(t,r){for(var i=this.data.length,o=0;o<i;o++)t[r++]=this.data[o];return i},e.of=function(t){return new e(t)},e}(Ca),np;(function(n){n[n.Deleted=0]="Deleted",n[n.Uncompressed=1]="Uncompressed",n[n.Compressed=2]="Compressed"})(np||(np={}));var Kle=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!0);var o=n.call(this,t,i)||this;return o.computeIndex=function(){for(var a=[],l=0,d=0,c=o.entries.length;d<c;d++){var u=o.entries[d],f=o.entries[d-1];d===0?a.push(u.ref.objectNumber):u.ref.objectNumber-f.ref.objectNumber>1&&(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;l<d;l++){var c=o.entries[l];if(c.type===np.Deleted){var u=c.type,f=c.nextFreeObjectNumber,p=c.ref;a[l]=[u,f,p.generationNumber]}if(c.type===np.Uncompressed){var u=c.type,g=c.offset,p=c.ref;a[l]=[u,g,p.generationNumber]}if(c.type===np.Compressed){var u=c.type,m=c.objectStreamRef,y=c.index;a[l]=[u,m.objectNumber,y]}}return a},o.computeMaxEntryByteWidths=function(){for(var a=o.entryTuplesCache.access(),l=[0,0,0],d=0,c=a.length;d<c;d++){var u=a[d],f=u[0],p=u[1],g=u[2],m=b5(f),y=b5(p),v=b5(g);m>l[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<a;o++){for(var l=t[o],d=l[0],c=l[1],u=l[2],f=ux(hx(d)),p=ux(hx(c)),g=ux(hx(u)),m=r[0]-1;m>=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<l;a++){for(var d=t[a],c=d[0],u=d[1],f=d[2],p=ux(hx(c)),g=ux(hx(u)),m=ux(hx(f)),y=r[0]-1;y>=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<y?(u=c[m],x=u[0],f=u[1],p=x===this.context.trailerInfo.Encrypt||f instanceof Gl||f instanceof gq||x.generationNumber!==0,p?(a.push(u),o.addUncompressedEntry(x,i),i+=this.computeIndirectObjectSize(u),this.shouldWaitForTick(1)?[4,a1()]:[3,3]):[3,4]):[3,6];case 2:C.sent(),C.label=3;case 3:return[3,5];case 4:v=JA(l),g=JA(d),(!v||v.length%this.objectsPerStream===0)&&(v=[],l.push(v),g=Mr.of(t++),d.push(g)),o.addCompressedEntry(x,g,v.length),v.push(u),C.label=5;case 5:return m++,[3,1];case 6:m=0,y=l.length,C.label=7;case 7:return m<y?(v=l[m],x=d[m],w=fq.withContextAndObjects(this.context,v,this.encodeStreams),o.addUncompressedEntry(x,i),i+=this.computeIndirectObjectSize([x,w]),a.push([x,w]),this.shouldWaitForTick(v.length)?[4,a1()]:[3,9]):[3,10];case 8:C.sent(),C.label=9;case 9:return m++,[3,7];case 10:return S=Mr.of(t++),o.dict.set(se.of("Size"),fn.of(t)),o.addUncompressedEntry(S,i),_=i,i+=this.computeIndirectObjectSize([S,o]),a.push([S,o]),b=u3.forLastCrossRefSectionOffset(_),i+=b.sizeInBytes(),[2,{size:i,header:r,indirectObjects:a,trailer:b}]}})})},e.forContext=function(t,r,i,o){return i===void 0&&(i=!0),o===void 0&&(o=50),new e(t,r,i,o)},e}(pq),dn=function(n){xt(e,n);function e(t){var r=n.call(this)||this;return r.value=t,r}return e.prototype.asBytes=function(){for(var t=this.value+(this.value.length%2===1?"0":""),r=t.length,i=new Uint8Array(t.length/2),o=0,a=0;o<r;){var l=parseInt(t.substring(o,o+2),16);i[a]=l,o+=2,a+=1}return i},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.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<a;o++)i+=Z_(r[o],4);return new e(i)},e}(Ca),iT=function(){function n(e,t){this.encoding=e===Wj.ZapfDingbats?B2.ZapfDingbats:e===Wj.Symbol?B2.Symbol:B2.WinAnsi,this.font=fle.load(e),this.fontName=this.font.FontName,this.customName=t}return n.prototype.encodeText=function(e){for(var t=this.encodeTextAsGlyphs(e),r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]=RF(t[i].code);return dn.of(r.join(""))},n.prototype.widthOfTextAtSize=function(e,t){for(var r=this.encodeTextAsGlyphs(e),i=0,o=0,a=r.length;o<a;o++){var l=r[o].name,d=(r[o+1]||{}).name,c=this.font.getXAxisKerningForPair(l,d)||0;i+=this.widthOfGlyph(l)+c}var u=t/1e3;return i*u},n.prototype.heightOfFontAtSize=function(e,t){t===void 0&&(t={});var r=t.descender,i=r===void 0?!0:r,o=this.font,a=o.Ascender,l=o.Descender,d=o.FontBBox,c=a||d[3],u=l||d[1],f=c-u;return i||(f+=l||0),f/1e3*e},n.prototype.sizeOfFontAtHeight=function(e){var t=this.font,r=t.Ascender,i=t.Descender,o=t.FontBBox,a=r||o[3],l=i||o[1];return 1e3*e/(a-l)},n.prototype.embedIntoContext=function(e,t){var r=e.obj({Type:"Font",Subtype:"Type1",BaseFont:this.customName||this.fontName,Encoding:this.encoding===B2.WinAnsi?"WinAnsiEncoding":void 0});return t?(e.assign(t,r),t):e.register(r)},n.prototype.widthOfGlyph=function(e){return this.font.getWidthOfGlyph(e)||250},n.prototype.encodeTextAsGlyphs=function(e){for(var t=Array.from(e),r=new Array(t.length),i=0,o=t.length;i<o;i++){var a=Ise(t[i]);r[i]=this.encoding.encodeUnicodeCodePoint(a)}return r},n.for=function(e,t){return new n(e,t)},n}(),Yle=function(n,e){for(var t=new Array(n.length),r=0,i=n.length;r<i;r++){var o=n[r],a=V4(_5(e(o))),l=V4.apply(void 0,o.codePoints.map($le));t[r]=[a,l]}return Qle(t)},Qle=function(n){return`/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo <<
/Registry (Adobe)
/Ordering (UCS)
/Supplement 0
>> def
/CMapName /Adobe-Identity-UCS def
/CMapType 2 def
1 begincodespacerange
<0000><ffff>
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<arguments.length;e++)n[e]=arguments[e];return"<"+n.join("")+">"},_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<<r-1};return n.fixedPitch&&t(1),n.serif&&t(2),t(3),n.script&&t(4),n.nonsymbolic&&t(6),n.italic&&t(7),n.allCap&&t(17),n.smallCap&&t(18),n.forceBold&&t(19),e},Jle=function(n){var e=n["OS/2"]?n["OS/2"].sFamilyClass:0,t=Zle({fixedPitch:n.post.isFixedPitch,serif:1<=e&&e<=7,script:e===10,italic:n.head.macStyle.italic});return t},Ir=function(n){xt(e,n);function e(t){var r=n.call(this)||this;return r.value=t,r}return e.prototype.asBytes=function(){for(var t=[],r="",i=!1,o=function(f){f!==void 0&&t.push(f),i=!1},a=0,l=this.value.length;a<l;a++){var d=this.value[a],c=mn(d),u=this.value[a+1];i?c===le.Newline||c===le.CarriageReturn?o():c===le.n?o(le.Newline):c===le.r?o(le.CarriageReturn):c===le.t?o(le.Tab):c===le.b?o(le.Backspace):c===le.f?o(le.FormFeed):c===le.LeftParen?o(le.LeftParen):c===le.RightParen?o(le.RightParen):c===le.Backspace?o(le.BackSlash):c>=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<d;l++){var c=o.font.characterSet[l];a[l]=o.font.glyphForCodePoint(c)}return Gse(a.sort(Vse),function(u){return u.id})},this.font=e,this.scale=1e3/this.font.unitsPerEm,this.fontData=t,this.fontName=this.font.postscriptName||"Font",this.customName=r,this.fontFeatures=i,this.baseFontName="",this.glyphCache=mf.populatedBy(this.allGlyphsInFontSortedById)}return n.for=function(e,t,r,i){return Pn(this,void 0,void 0,function(){var o;return Rn(this,function(a){switch(a.label){case 0:return[4,e.create(t)];case 1:return o=a.sent(),[2,new n(o,t,r,i)]}})})},n.prototype.encodeText=function(e){for(var t=this.font.layout(e,this.fontFeatures).glyphs,r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]=Z_(t[i].id,4);return dn.of(r.join(""))},n.prototype.widthOfTextAtSize=function(e,t){for(var r=this.font.layout(e,this.fontFeatures).glyphs,i=0,o=0,a=r.length;o<a;o++)i+=r[o].advanceWidth*this.scale;var l=t/1e3;return i*l},n.prototype.heightOfFontAtSize=function(e,t){t===void 0&&(t={});var r=t.descender,i=r===void 0?!0:r,o=this.font,a=o.ascent,l=o.descent,d=o.bbox,c=(a||d.maxY)*this.scale,u=(l||d.minY)*this.scale,f=c-u;return i||(f-=Math.abs(l)||0),f/1e3*e},n.prototype.sizeOfFontAtHeight=function(e){var t=this.font,r=t.ascent,i=t.descent,o=t.bbox,a=(r||o.maxY)*this.scale,l=(i||o.minY)*this.scale;return 1e3*e/(a-l)},n.prototype.embedIntoContext=function(e,t){return this.baseFontName=this.customName||e.addRandomSuffix(this.fontName),this.embedFontDict(e,t)},n.prototype.embedFontDict=function(e,t){return Pn(this,void 0,void 0,function(){var r,i,o;return Rn(this,function(a){switch(a.label){case 0:return[4,this.embedCIDFontDict(e)];case 1:return r=a.sent(),i=this.embedUnicodeCmap(e),o=e.obj({Type:"Font",Subtype:"Type0",BaseFont:this.baseFontName,Encoding:"Identity-H",DescendantFonts:[r],ToUnicode:i}),t?(e.assign(t,o),[2,t]):[2,e.register(o)]}})})},n.prototype.isCFF=function(){return this.font.cff},n.prototype.embedCIDFontDict=function(e){return Pn(this,void 0,void 0,function(){var t,r;return Rn(this,function(i){switch(i.label){case 0:return[4,this.embedFontDescriptor(e)];case 1:return t=i.sent(),r=e.obj({Type:"Font",Subtype:this.isCFF()?"CIDFontType0":"CIDFontType2",CIDToGIDMap:"Identity",BaseFont:this.baseFontName,CIDSystemInfo:{Registry:Ir.of("Adobe"),Ordering:Ir.of("Identity"),Supplement:0},FontDescriptor:t,W:this.computeWidths()}),[2,e.register(r)]}})})},n.prototype.embedFontDescriptor=function(e){return Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c,u,f,p,g,m,y,v;return Rn(this,function(x){switch(x.label){case 0:return[4,this.embedFontStream(e)];case 1:return t=x.sent(),r=this.scale,i=this.font,o=i.italicAngle,a=i.ascent,l=i.descent,d=i.capHeight,c=i.xHeight,u=this.font.bbox,f=u.minX,p=u.minY,g=u.maxX,m=u.maxY,y=e.obj((v={Type:"FontDescriptor",FontName:this.baseFontName,Flags:Jle(this.font),FontBBox:[f*r,p*r,g*r,m*r],ItalicAngle:o,Ascent:a*r,Descent:l*r,CapHeight:(d||a)*r,XHeight:(c||0)*r,StemV:0},v[this.isCFF()?"FontFile3":"FontFile2"]=t,v)),[2,e.register(y)]}})})},n.prototype.serializeFont=function(){return Pn(this,void 0,void 0,function(){return Rn(this,function(e){return[2,this.fontData]})})},n.prototype.embedFontStream=function(e){return Pn(this,void 0,void 0,function(){var t,r,i;return Rn(this,function(o){switch(o.label){case 0:return i=(r=e).flateStream,[4,this.serializeFont()];case 1:return t=i.apply(r,[o.sent(),{Subtype:this.isCFF()?"CIDFontType0C":void 0}]),[2,e.register(t)]}})})},n.prototype.embedUnicodeCmap=function(e){var t=Yle(this.glyphCache.access(),this.glyphId.bind(this)),r=e.flateStream(t);return e.register(r)},n.prototype.glyphId=function(e){return e?e.id:-1},n.prototype.computeWidths=function(){for(var e=this.glyphCache.access(),t=[],r=[],i=0,o=e.length;i<o;i++){var a=e[i],l=e[i-1],d=this.glyphId(a),c=this.glyphId(l);i===0?t.push(d):d-c!==1&&(t.push(r),t.push(d),r=[]),r.push(a.advanceWidth*this.scale)}return t.push(r),t},n}(),ede=function(n){xt(e,n);function e(t,r,i,o){var a=n.call(this,t,r,i,o)||this;return a.subset=a.font.createSubset(),a.glyphs=[],a.glyphCache=mf.populatedBy(function(){return a.glyphs}),a.glyphIdMap=new Map,a}return e.for=function(t,r,i,o){return Pn(this,void 0,void 0,function(){var a;return Rn(this,function(l){switch(l.label){case 0:return[4,t.create(r)];case 1:return a=l.sent(),[2,new e(a,r,i,o)]}})})},e.prototype.encodeText=function(t){for(var r=this.font.layout(t,this.fontFeatures).glyphs,i=new Array(r.length),o=0,a=r.length;o<a;o++){var l=r[o],d=this.subset.includeGlyph(l);this.glyphs[d-1]=l,this.glyphIdMap.set(l.id,d),i[o]=Z_(d,4)}return this.glyphCache.invalidate(),dn.of(i.join(""))},e.prototype.isCFF=function(){return this.subset.cff},e.prototype.glyphId=function(t){return t?this.glyphIdMap.get(t.id):-1},e.prototype.serializeFont=function(){var t=this;return new Promise(function(r,i){var o=[];t.subset.encodeStream().on("data",function(a){return o.push(a)}).on("end",function(){return r(qse(o))}).on("error",function(a){return i(a)})})},e}(h3),LB;(function(n){n.Source="Source",n.Data="Data",n.Alternative="Alternative",n.Supplement="Supplement",n.EncryptedPayload="EncryptedPayload",n.FormData="EncryptedPayload",n.Schema="Schema",n.Unspecified="Unspecified"})(LB||(LB={}));var tde=function(){function n(e,t,r){r===void 0&&(r={}),this.fileData=e,this.fileName=t,this.options=r}return n.for=function(e,t,r){return r===void 0&&(r={}),new n(e,t,r)},n.prototype.embedIntoContext=function(e,t){return Pn(this,void 0,void 0,function(){var r,i,o,a,l,d,c,u,f;return Rn(this,function(p){return r=this.options,i=r.mimeType,o=r.description,a=r.creationDate,l=r.modificationDate,d=r.afRelationship,c=e.flateStream(this.fileData,{Type:"EmbeddedFile",Subtype:i??void 0,Params:{Size:this.fileData.length,CreationDate:a?Ir.fromDate(a):void 0,ModDate:l?Ir.fromDate(l):void 0}}),u=e.register(c),f=e.obj({Type:"Filespec",F:Ir.of(this.fileName),UF:dn.fromText(this.fileName),EF:{F:u},Desc:o?dn.fromText(o):void 0,AFRelationship:d??void 0}),t?(e.assign(t,f),[2,t]):[2,e.register(f)]})})},n}(),G4=[65472,65473,65474,65475,65477,65478,65479,65480,65481,65482,65483,65484,65485,65486,65487],lb;(function(n){n.DeviceGray="DeviceGray",n.DeviceRGB="DeviceRGB",n.DeviceCMYK="DeviceCMYK"})(lb||(lb={}));var nde={1:lb.DeviceGray,3:lb.DeviceRGB,4:lb.DeviceCMYK},mq=function(){function n(e,t,r,i,o){this.imageData=e,this.bitsPerComponent=t,this.width=r,this.height=i,this.colorSpace=o}return n.for=function(e){return Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c,u,f;return Rn(this,function(p){if(t=new DataView(e.buffer),r=t.getUint16(0),r!==65496)throw new Error("SOI not found in JPEG");for(i=2;i<t.byteLength&&(o=t.getUint16(i),i+=2,!G4.includes(o));)i+=t.getUint16(i);if(!G4.includes(o))throw new Error("Invalid JPEG");if(i+=2,a=t.getUint8(i++),l=t.getUint16(i),i+=2,d=t.getUint16(i),i+=2,c=t.getUint8(i++),u=nde[c],!u)throw new Error("Unknown JPEG channel.");return f=u,[2,new n(e,a,d,l,f)]})})},n.prototype.embedIntoContext=function(e,t){return Pn(this,void 0,void 0,function(){var r;return Rn(this,function(i){return r=e.stream(this.imageData,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.bitsPerComponent,Width:this.width,Height:this.height,ColorSpace:this.colorSpace,Filter:"DCTDecode",Decode:this.colorSpace===lb.DeviceCMYK?[1,0,1,0,1,0,1,0]:void 0}),t?(e.assign(t,r),[2,t]):[2,e.register(r)]})})},n}(),dt={};dt.toRGBA8=function(n){var e=n.width,t=n.height;if(n.tabs.acTL==null)return[dt.toRGBA8.decodeImage(n.data,e,t,n).buffer];var r=[];n.frames[0].data==null&&(n.frames[0].data=n.data);for(var i=e*t*4,o=new Uint8Array(i),a=new Uint8Array(i),l=new Uint8Array(i),d=0;d<n.frames.length;d++){var c=n.frames[d],u=c.rect.x,f=c.rect.y,p=c.rect.width,g=c.rect.height,m=dt.toRGBA8.decodeImage(c.data,p,g,n);if(d!=0)for(var y=0;y<i;y++)l[y]=o[y];if(c.blend==0?dt._copyTile(m,p,g,o,e,t,u,f,0):c.blend==1&&dt._copyTile(m,p,g,o,e,t,u,f,1),r.push(o.buffer.slice(0)),c.dispose!=0){if(c.dispose==1)dt._copyTile(a,p,g,o,e,t,u,f,0);else if(c.dispose==2)for(var y=0;y<i;y++)o[y]=l[y]}}return r};dt.toRGBA8.decodeImage=function(n,e,t,r){var i=e*t,o=dt.decode._getBPP(r),a=Math.ceil(e*o/8),l=new Uint8Array(i*4),d=new Uint32Array(l.buffer),c=r.ctype,u=r.depth,f=dt._bin.readUshort;if(c==6){var p=i<<2;if(u==8)for(var g=0;g<p;g+=4)l[g]=n[g],l[g+1]=n[g+1],l[g+2]=n[g+2],l[g+3]=n[g+3];if(u==16)for(var g=0;g<p;g++)l[g]=n[g<<1]}else if(c==2){var m=r.tabs.tRNS;if(m==null){if(u==8)for(var g=0;g<i;g++){var y=g*3;d[g]=255<<24|n[y+2]<<16|n[y+1]<<8|n[y]}if(u==16)for(var g=0;g<i;g++){var y=g*6;d[g]=255<<24|n[y+4]<<16|n[y+2]<<8|n[y]}}else{var v=m[0],x=m[1],w=m[2];if(u==8)for(var g=0;g<i;g++){var S=g<<2,y=g*3;d[g]=255<<24|n[y+2]<<16|n[y+1]<<8|n[y],n[y]==v&&n[y+1]==x&&n[y+2]==w&&(l[S+3]=0)}if(u==16)for(var g=0;g<i;g++){var S=g<<2,y=g*6;d[g]=255<<24|n[y+4]<<16|n[y+2]<<8|n[y],f(n,y)==v&&f(n,y+2)==x&&f(n,y+4)==w&&(l[S+3]=0)}}}else if(c==3){var _=r.tabs.PLTE,b=r.tabs.tRNS,C=b?b.length:0;if(u==1)for(var T=0;T<t;T++)for(var F=T*a,A=T*e,g=0;g<e;g++){var S=A+g<<2,D=n[F+(g>>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<C?b[D]:255}if(u==2)for(var T=0;T<t;T++)for(var F=T*a,A=T*e,g=0;g<e;g++){var S=A+g<<2,D=n[F+(g>>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<C?b[D]:255}if(u==4)for(var T=0;T<t;T++)for(var F=T*a,A=T*e,g=0;g<e;g++){var S=A+g<<2,D=n[F+(g>>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<C?b[D]:255}if(u==8)for(var g=0;g<i;g++){var S=g<<2,D=n[g],P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D<C?b[D]:255}}else if(c==4){if(u==8)for(var g=0;g<i;g++){var S=g<<2,L=g<<1,W=n[L];l[S]=W,l[S+1]=W,l[S+2]=W,l[S+3]=n[L+1]}if(u==16)for(var g=0;g<i;g++){var S=g<<2,L=g<<2,W=n[L];l[S]=W,l[S+1]=W,l[S+2]=W,l[S+3]=n[L+2]}}else if(c==0)for(var v=r.tabs.tRNS?r.tabs.tRNS:-1,T=0;T<t;T++){var O=T*a,U=T*e;if(u==1)for(var M=0;M<e;M++){var W=255*(n[O+(M>>>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<e;M++){var W=85*(n[O+(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<e;M++){var W=17*(n[O+(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<e;M++){var W=n[O+M],I=W==v?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==16)for(var M=0;M<e;M++){var W=n[O+(M<<1)],I=f(n,O+(M<<g))==v?0:255;d[U+M]=I<<24|W<<16|W<<8|W}}return l};dt.decode=function(n){for(var e=new Uint8Array(n),t=8,r=dt._bin,i=r.readUshort,o=r.readUint,a={tabs:{},frames:[]},l=new Uint8Array(e.length),d=0,c,u=0,f=[137,80,78,71,13,10,26,10],p=0;p<8;p++)if(e[p]!=f[p])throw"The input is not a PNG file!";for(;t<e.length;){var g=r.readUint(e,t);t+=4;var m=r.readASCII(e,t,4);if(t+=4,m=="IHDR")dt.decode._IHDR(e,t,a);else if(m=="IDAT"){for(var p=0;p<g;p++)l[d+p]=e[t+p];d+=g}else if(m=="acTL")a.tabs[m]={num_frames:o(e,t),num_plays:o(e,t+4)},c=new Uint8Array(e.length);else if(m=="fcTL"){if(u!=0){var y=a.frames[a.frames.length-1];y.data=dt.decode._decompress(a,c.slice(0,u),y.rect.width,y.rect.height),u=0}var v={x:o(e,t+12),y:o(e,t+16),width:o(e,t+4),height:o(e,t+8)},x=i(e,t+22);x=i(e,t+20)/(x==0?100:x);var w={rect:v,delay:Math.round(x*1e3),dispose:e[t+24],blend:e[t+25]};a.frames.push(w)}else if(m=="fdAT"){for(var p=0;p<g-4;p++)c[u+p]=e[t+p+4];u+=g-4}else if(m=="pHYs")a.tabs[m]=[r.readUint(e,t),r.readUint(e,t+4),e[t+8]];else if(m=="cHRM"){a.tabs[m]=[];for(var p=0;p<8;p++)a.tabs[m].push(r.readUint(e,t+p*4))}else if(m=="tEXt"){a.tabs[m]==null&&(a.tabs[m]={});var S=r.nextZero(e,t),_=r.readASCII(e,t,S-t),b=r.readASCII(e,S+1,t+g-S-1);a.tabs[m][_]=b}else if(m=="iTXt"){a.tabs[m]==null&&(a.tabs[m]={});var S=0,C=t;S=r.nextZero(e,C);var _=r.readASCII(e,C,S-C);C=S+1,e[C],e[C+1],C+=2,S=r.nextZero(e,C),r.readASCII(e,C,S-C),C=S+1,S=r.nextZero(e,C),r.readUTF8(e,C,S-C),C=S+1;var b=r.readUTF8(e,C,g-(C-t));a.tabs[m][_]=b}else if(m=="PLTE")a.tabs[m]=r.readBytes(e,t,g);else if(m=="hIST"){var T=a.tabs.PLTE.length/3;a.tabs[m]=[];for(var p=0;p<T;p++)a.tabs[m].push(i(e,t+p*2))}else if(m=="tRNS")a.ctype==3?a.tabs[m]=r.readBytes(e,t,g):a.ctype==0?a.tabs[m]=i(e,t):a.ctype==2&&(a.tabs[m]=[i(e,t),i(e,t+2),i(e,t+4)]);else if(m=="gAMA")a.tabs[m]=r.readUint(e,t)/1e5;else if(m=="sRGB")a.tabs[m]=e[t];else if(m=="bKGD")a.ctype==0||a.ctype==4?a.tabs[m]=[i(e,t)]:a.ctype==2||a.ctype==6?a.tabs[m]=[i(e,t),i(e,t+2),i(e,t+4)]:a.ctype==3&&(a.tabs[m]=e[t]);else if(m=="IEND")break;t+=g,r.readUint(e,t),t+=4}if(u!=0){var y=a.frames[a.frames.length-1];y.data=dt.decode._decompress(a,c.slice(0,u),y.rect.width,y.rect.height),u=0}return a.data=dt.decode._decompress(a,l,a.width,a.height),delete a.compress,delete a.interlace,delete a.filter,a};dt.decode._decompress=function(n,e,t,r){var i=dt.decode._getBPP(n),o=Math.ceil(t*i/8),a=new Uint8Array((o+1+n.interlace)*r);return e=dt.decode._inflate(e,a),n.interlace==0?e=dt.decode._filterZero(e,n,0,t,r):n.interlace==1&&(e=dt.decode._readInterlace(e,n)),e};dt.decode._inflate=function(n,e){var t=dt.inflateRaw(new Uint8Array(n.buffer,2,n.length-6),e);return t};dt.inflateRaw=function(){var n={};return n.H={},n.H.N=function(e,t){var r=Uint8Array,i=0,o=0,a=0,l=0,d=0,c=0,u=0,f=0,p=0,g,m;if(e[0]==3&&e[1]==0)return t||new r(0);var y=n.H,v=y.b,x=y.e,w=y.R,S=y.n,_=y.A,b=y.Z,C=y.m,T=t==null;for(T&&(t=new r(e.length>>>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;P<d;P++){var L=x(e,p+P*3,3);C.Q[(C.X[P]<<1)+1]=L,L>D&&(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<<D)-1,a+l,e,p,C.v);var W=y.V(C.v,0,a,C.C);c=(1<<W)-1;var O=y.V(C.v,a,l,C.D);u=(1<<O)-1,S(C.C,W),_(C.C,W,g),S(C.D,O),_(C.D,O,m)}for(;;){var U=g[b(e,p)&c];p+=U&15;var M=U>>>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<I;)t[f]=t[f++-re],t[f]=t[f++-re],t[f]=t[f++-re],t[f]=t[f++-re];f=I}}}return t.length==f?t:t.slice(0,f)},n.H.W=function(e,t){var r=e.length;if(t<=r)return e;var i=new Uint8Array(r<<1);return i.set(e,0),i},n.H.R=function(e,t,r,i,o,a){for(var l=n.H.e,d=n.H.Z,c=0;c<r;){var u=e[d(i,o)&t];o+=u&15;var f=u>>>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<m;)a[c]=p,c++}}return o},n.H.V=function(e,t,r,i){for(var o=0,a=0,l=i.length>>>1;a<r;){var d=e[a+t];i[a<<1]=0,i[(a<<1)+1]=d,d>o&&(o=d),a++}for(;a<l;)i[a<<1]=0,i[(a<<1)+1]=0,a++;return o},n.H.n=function(e,t){for(var r=n.H.m,i=e.length,o,a,l,d,c,u=r.j,d=0;d<=t;d++)u[d]=0;for(d=1;d<i;d+=2)u[e[d]]++;var f=r.K;for(o=0,u[0]=0,a=1;a<=t;a++)o=o+u[a-1]<<1,f[a]=o;for(l=0;l<i;l+=2)c=e[l+1],c!=0&&(e[l]=f[c],f[c]++)},n.H.A=function(e,t,r){for(var i=e.length,o=n.H.m,a=o.r,l=0;l<i;l+=2)if(e[l+1]!=0)for(var d=l>>1,c=e[l+1],u=d<<4|c,f=t-c,p=e[l]<<f,g=p+(1<<f);p!=g;){var m=a[p]>>>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<e.length;o+=2){var a=e[o]<<t-e[o+1];e[o]=r[a]>>>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<<r)-1},n.H.b=function(e,t,r){return(e[t>>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)&(1<<r)-1},n.H.Z=function(e,t){return(e[t>>>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<t;r++){var i=r;i=(i&2863311530)>>>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<r;)w+=m,x++;for(var S=u[g];S<t;)S+=y,v++;var _=Math.ceil(v*i/8);dt.decode._filterZero(n,e,d,v,x);for(var b=0,C=c[g];C<r;){for(var T=u[g],F=d+b*_<<3;T<t;){if(i==1){var A=n[F>>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<o;P++)l[D+P]=n[(F>>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<a;f++)n[f+1]=n[f+1]+(n[f+1-o]>>>1)&255;for(var p=0;p<i;p++)if(d=t+p*a,c=d+p+1,u=n[c-1],f=0,u==0)for(;f<a;f++)n[d+f]=n[c+f];else if(u==1){for(;f<o;f++)n[d+f]=n[c+f];for(;f<a;f++)n[d+f]=n[c+f]+n[d+f-o]}else if(u==2)for(;f<a;f++)n[d+f]=n[c+f]+n[d+f-a];else if(u==3){for(;f<o;f++)n[d+f]=n[c+f]+(n[d+f-a]>>>1);for(;f<a;f++)n[d+f]=n[c+f]+(n[d+f-a]+n[d+f-o]>>>1)}else{for(;f<o;f++)n[d+f]=n[c+f]+l(0,n[d+f-a],0);for(;f<a;f++)n[d+f]=n[c+f]+l(n[d+f-o],n[d+f-a],n[d+f-o-a])}return n};dt.decode._paeth=function(n,e,t){var r=n+e-t,i=r-n,o=r-e,a=r-t;return i*i<=o*o&&i*i<=a*a?n:o*o<=a*a?e:t};dt.decode._IHDR=function(n,e,t){var r=dt._bin;t.width=r.readUint(n,e),e+=4,t.height=r.readUint(n,e),e+=4,t.depth=n[e],e++,t.ctype=n[e],e++,t.compress=n[e],e++,t.filter=n[e],e++,t.interlace=n[e],e++};dt._bin={nextZero:function(n,e){for(;n[e]!=0;)e++;return e},readUshort:function(n,e){return n[e]<<8|n[e+1]},writeUshort:function(n,e,t){n[e]=t>>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<t;i++)r+=String.fromCharCode(n[e+i]);return r},writeASCII:function(n,e,t){for(var r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)},readBytes:function(n,e,t){for(var r=[],i=0;i<t;i++)r.push(n[e+i]);return r},pad:function(n){return n.length<2?"0"+n:n},readUTF8:function(n,e,t){for(var r="",i,o=0;o<t;o++)r+="%"+dt._bin.pad(n[e+o].toString(16));try{i=decodeURIComponent(r)}catch{return dt._bin.readASCII(n,e,t)}return i}};dt._copyTile=function(n,e,t,r,i,o,a,l,d){for(var c=Math.min(e,i),u=Math.min(t,o),f=0,p=0,g=0;g<u;g++)for(var m=0;m<c;m++)if(a>=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;f<n.length;f++)d.frames.push({rect:{x:0,y:0,width:e,height:t},img:new Uint8Array(n[f]),blend:0,dispose:1,bpp:Math.ceil(c/8),bpl:Math.ceil(u/8)});dt.encode.compressPNG(d,0,!0);var p=dt.encode._main(d,e,t,a,l);return p};dt.encode._main=function(n,e,t,r,i){i==null&&(i={});var o=dt.crc.crc,a=dt._bin.writeUint,l=dt._bin.writeUshort,d=dt._bin.writeASCII,c=8,u=n.frames.length>1,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<g;m++)n.plte[m]>>>24!=255&&(f=!0);p+=8+g*3+4+(f?8+g*1+4:0)}for(var y=0;y<n.frames.length;y++){var v=n.frames[y];u&&(p+=38),p+=v.cimg.length+12,y!=0&&(p+=4)}p+=12;for(var x=new Uint8Array(p),w=[137,80,78,71,13,10,26,10],m=0;m<8;m++)x[m]=w[m];if(a(x,c,13),c+=4,d(x,c,"IHDR"),c+=4,a(x,c,e),c+=4,a(x,c,t),c+=4,x[c]=n.depth,c++,x[c]=n.ctype,c++,x[c]=0,c++,x[c]=0,c++,x[c]=0,c++,a(x,c,o(x,c-17,17)),c+=4,i.sRGB!=null&&(a(x,c,1),c+=4,d(x,c,"sRGB"),c+=4,x[c]=i.sRGB,c++,a(x,c,o(x,c-5,5)),c+=4),i.pHYs!=null&&(a(x,c,9),c+=4,d(x,c,"pHYs"),c+=4,a(x,c,i.pHYs[0]),c+=4,a(x,c,i.pHYs[1]),c+=4,x[c]=i.pHYs[2],c++,a(x,c,o(x,c-13,13)),c+=4),u&&(a(x,c,8),c+=4,d(x,c,"acTL"),c+=4,a(x,c,n.frames.length),c+=4,a(x,c,i.loop!=null?i.loop:0),c+=4,a(x,c,o(x,c-12,12)),c+=4),n.ctype==3){var g=n.plte.length;a(x,c,g*3),c+=4,d(x,c,"PLTE"),c+=4;for(var m=0;m<g;m++){var S=m*3,_=n.plte[m],b=_&255,C=_>>>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<g;m++)x[c+m]=n.plte[m]>>>24&255;c+=g,a(x,c,o(x,c-g-4,g+4)),c+=4}}for(var F=0,y=0;y<n.frames.length;y++){var v=n.frames[y];u&&(a(x,c,26),c+=4,d(x,c,"fcTL"),c+=4,a(x,c,F++),c+=4,a(x,c,v.rect.width),c+=4,a(x,c,v.rect.height),c+=4,a(x,c,v.rect.x),c+=4,a(x,c,v.rect.y),c+=4,l(x,c,r[y]),c+=2,l(x,c,1e3),c+=2,x[c]=v.dispose,c++,x[c]=v.blend,c++,a(x,c,o(x,c-30,30)),c+=4);var A=v.cimg,g=A.length;a(x,c,g+(y==0?0:4)),c+=4;var D=c;d(x,c,y==0?"IDAT":"fdAT"),c+=4,y!=0&&(a(x,c,F++),c+=4),x.set(A,c),c+=g,a(x,c,o(x,D,c-D)),c+=4}return a(x,c,0),c+=4,d(x,c,"IEND"),c+=4,a(x,c,o(x,c-4,4)),c+=4,x.buffer};dt.encode.compressPNG=function(n,e,t){for(var r=0;r<n.frames.length;r++){var i=n.frames[r];i.rect.width;var o=i.rect.height,a=new Uint8Array(o*i.bpl+o);i.cimg=dt.encode._filterZero(i.img,o,i.bpp,i.bpl,a,e,t)}};dt.encode.compress=function(n,e,t,r,i){for(var o=i[0],a=i[1],l=i[2],d=i[3],c=i[4],u=6,f=8,p=255,g=0;g<n.length;g++)for(var m=new Uint8Array(n[g]),y=m.length,v=0;v<y;v+=4)p&=m[v+3];var x=p!=255,w=dt.encode.framize(n,e,t,o,a,l),S={},_=[],b=[];if(r!=0){for(var C=[],v=0;v<w.length;v++)C.push(w[v].img.buffer);for(var T=dt.encode.concatRGBA(C),F=dt.quantize(T,r),A=0,D=new Uint8Array(F.abuf),v=0;v<w.length;v++){var P=w[v].img,L=P.length;b.push(new Uint8Array(F.inds.buffer,A>>2,L>>2));for(var g=0;g<L;g+=4)P[g]=D[A+g],P[g+1]=D[A+g+1],P[g+2]=D[A+g+2],P[g+3]=D[A+g+3];A+=L}for(var v=0;v<F.plte.length;v++)_.push(F.plte[v].est.rgba)}else for(var g=0;g<w.length;g++){var W=w[g],O=new Uint32Array(W.img.buffer),U=W.rect.width,y=O.length,M=new Uint8Array(y);b.push(M);for(var v=0;v<y;v++){var I=O[v];if(v!=0&&I==O[v-1])M[v]=M[v-1];else if(v>U&&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<w.length;g++){var W=w[g];W.rect.x,W.rect.y;var U=W.rect.width,G=W.rect.height,te=W.img;new Uint32Array(te.buffer);var re=4*U,me=4;if(z<=256&&c==!1){re=Math.ceil(f*U/8);for(var J=new Uint8Array(re*G),ne=b[g],ye=0;ye<G;ye++){var v=ye*re,ke=ye*U;if(f==8)for(var Ye=0;Ye<U;Ye++)J[v+Ye]=ne[ke+Ye];else if(f==4)for(var Ye=0;Ye<U;Ye++)J[v+(Ye>>1)]|=ne[ke+Ye]<<4-(Ye&1)*4;else if(f==2)for(var Ye=0;Ye<U;Ye++)J[v+(Ye>>2)]|=ne[ke+Ye]<<6-(Ye&3)*2;else if(f==1)for(var Ye=0;Ye<U;Ye++)J[v+(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;v<De;v++){var P=v*3,qe=v*4;J[P]=te[qe],J[P+1]=te[qe+1],J[P+2]=te[qe+2]}te=J,u=2,me=3,re=3*U}W.img=te,W.bpl=re,W.bpp=me}return{ctype:u,depth:f,plte:_,frames:w}};dt.encode.framize=function(n,e,t,r,i,o){for(var a=[],l=0;l<n.length;l++){var d=new Uint8Array(n[l]),c=new Uint32Array(d.buffer),u,f=0,p=0,g=e,m=t,y=r?1:0;if(l!=0){for(var v=o||r||l==1||a[l-2].dispose!=0?1:2,x=0,w=1e9,S=0;S<v;S++){for(var W=new Uint8Array(n[l-1-S]),_=new Uint32Array(n[l-1-S]),b=e,C=t,T=-1,F=-1,A=0;A<t;A++)for(var D=0;D<e;D++){var P=A*e+D;c[P]!=_[P]&&(D<b&&(b=D),D>T&&(T=D),A<C&&(C=A),A>F&&(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);L<w&&(w=L,x=S,f=b,p=C,g=T-b+1,m=F-C+1)}var W=new Uint8Array(n[l-1-x]);x==1&&(a[l-1].dispose=2),u=new Uint8Array(g*m*4),dt._copyTile(W,e,t,u,g,m,-f,-p,0),y=dt._copyTile(d,e,t,u,g,m,-f,-p,3)?1:0,y==1?dt.encode._prepareDiff(d,e,t,u,{x:f,y:p,width:g,height:m}):dt._copyTile(d,e,t,u,g,m,-f,-p,0)}else u=d.slice(0);a.push({rect:{x:f,y:p,width:g,height:m},img:u,blend:y,dispose:0})}if(r)for(var l=0;l<a.length;l++){var O=a[l];if(O.blend!=1){var U=O.rect,M=a[l-1].rect,I=Math.min(U.x,M.x),H=Math.min(U.y,M.y),z=Math.max(U.x+U.width,M.x+M.width),G=Math.max(U.y+U.height,M.y+M.height),te={x:I,y:H,width:z-I,height:G-H};a[l-1].dispose=1,l-1!=0&&dt.encode._updateFrame(n,e,t,a,l-1,te,i),dt.encode._updateFrame(n,e,t,a,l,te,i)}}var re=0;if(n.length!=1)for(var P=0;P<a.length;P++){var O=a[P];re+=O.rect.width*O.rect.height}return a};dt.encode._updateFrame=function(n,e,t,r,i,o,a){for(var l=Uint8Array,d=Uint32Array,c=new l(n[i-1]),u=new d(n[i-1]),f=i+1<n.length?new l(n[i+1]):null,p=new l(n[i]),g=new d(p.buffer),m=e,y=t,v=-1,x=-1,w=0;w<o.height;w++)for(var S=0;S<o.width;S++){var _=o.x+S,b=o.y+w,C=b*e+_,T=g[C];T==0||r[i-1].dispose==0&&u[C]==T&&(f==null||f[C*4+3]!=0)||(_<m&&(m=_),_>v&&(v=_),b<y&&(y=b),b>x&&(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<d.length;f++){for(var p=0;p<e;p++)dt.encode._filterLine(i,n,p,r,t,d[f]);l.push(u.deflate(i,c))}for(var g,m=1e9,f=0;f<l.length;f++)l[f].length<m&&(g=f,m=l[f].length);return l[g]};dt.encode._filterLine=function(n,e,t,r,i,o){var a=t*r,l=a+t,d=dt.decode._paeth;if(n[l]=o,l++,o==0)if(r<500)for(var c=0;c<r;c++)n[l+c]=e[a+c];else n.set(new Uint8Array(e.buffer,a,r),l);else if(o==1){for(var c=0;c<i;c++)n[l+c]=e[a+c];for(var c=i;c<r;c++)n[l+c]=e[a+c]-e[a+c-i]+256&255}else if(t==0){for(var c=0;c<i;c++)n[l+c]=e[a+c];if(o==2)for(var c=i;c<r;c++)n[l+c]=e[a+c];if(o==3)for(var c=i;c<r;c++)n[l+c]=e[a+c]-(e[a+c-i]>>1)+256&255;if(o==4)for(var c=i;c<r;c++)n[l+c]=e[a+c]-d(e[a+c-i],0,0)+256&255}else{if(o==2)for(var c=0;c<r;c++)n[l+c]=e[a+c]+256-e[a+c-r]&255;if(o==3){for(var c=0;c<i;c++)n[l+c]=e[a+c]+256-(e[a+c-r]>>1)&255;for(var c=i;c<r;c++)n[l+c]=e[a+c]+256-(e[a+c-r]+e[a+c-i]>>1)&255}if(o==4){for(var c=0;c<i;c++)n[l+c]=e[a+c]+256-d(0,e[a+c-r],0)&255;for(var c=i;c<r;c++)n[l+c]=e[a+c]+256-d(e[a+c-i],e[a+c-r],e[a+c-i-r])&255}}};dt.crc={table:function(){for(var n=new Uint32Array(256),e=0;e<256;e++){for(var t=e,r=0;r<8;r++)t&1?t=3988292384^t>>>1:t=t>>>1;n[e]=t}return n}(),update:function(n,e,t,r){for(var i=0;i<r;i++)n=dt.crc.table[(n^e[t+i])&255]^n>>>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<u;p+=4){var g=d[p]*.00392156862745098,m=d[p+1]*(1/255),y=d[p+2]*(1/255),v=d[p+3]*(1/255),x=dt.quantize.getNearest(a,g,m,y,v);f[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.length<e;){for(var a=0,l=0,d=0;d<o.length;d++)o[d].est.L>a&&(a=o[d].est.L,l=d);if(a<t)break;var c=o[l],u=dt.quantize.splitPixels(n,r,c.i0,c.i1,c.est.e,c.est.eMq255),f=c.i0>=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;d<o.length;d++)o[d].ind=d;return[i,o]};dt.quantize.getNearest=function(n,e,t,r,i){if(n.left==null)return n.tdst=dt.quantize.dist(n.est.q,e,t,r,i),n;var o=dt.quantize.planeDst(n.est,e,t,r,i),a=n.left,l=n.right;o>0&&(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.tdst<d.tdst?c:d};dt.quantize.planeDst=function(n,e,t,r,i){var o=n.e;return o[0]*e+o[1]*t+o[2]*r+o[3]*i-n.eMq};dt.quantize.dist=function(n,e,t,r,i){var o=e-n[0],a=t-n[1],l=r-n[2],d=i-n[3];return o*o+a*a+l*l+d*d};dt.quantize.splitPixels=function(n,e,t,r,i,o){var a=dt.quantize.vecDot;for(r-=4;t<r;){for(;a(n,t,i)<=o;)t+=4;for(;a(n,r,i)>o;)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<t;a+=4){var l=n[a]*.00392156862745098,d=n[a+1]*(1/255),c=n[a+2]*(1/255),u=n[a+3]*(1/255);i[0]+=l,i[1]+=d,i[2]+=c,i[3]+=u,r[0]+=l*l,r[1]+=l*d,r[2]+=l*c,r[3]+=l*u,r[5]+=d*d,r[6]+=d*c,r[7]+=d*u,r[10]+=c*c,r[11]+=c*u,r[15]+=u*u}return r[4]=r[1],r[8]=r[2],r[9]=r[6],r[12]=r[3],r[13]=r[7],r[14]=r[11],{R:r,m:i,N:o}};dt.quantize.estats=function(n){var e=n.R,t=n.m,r=n.N,i=t[0],o=t[1],a=t[2],l=t[3],d=r==0?0:1/r,c=[e[0]-i*i*d,e[1]-i*o*d,e[2]-i*a*d,e[3]-i*l*d,e[4]-o*i*d,e[5]-o*o*d,e[6]-o*a*d,e[7]-o*l*d,e[8]-a*i*d,e[9]-a*o*d,e[10]-a*a*d,e[11]-a*l*d,e[12]-l*i*d,e[13]-l*o*d,e[14]-l*a*d,e[15]-l*l*d],u=c,f=dt.M4,p=[.5,.5,.5,.5],g=0,m=0;if(r!=0)for(var y=0;y<10&&(p=f.multVec(u,p),m=Math.sqrt(f.dot(p,p)),p=f.sml(1/m,p),!(Math.abs(m-g)<1e-9));y++)g=m;var v=[i*d,o*d,a*d,l*d],x=f.dot(f.sml(255,v),p);return{Cov:c,q:v,e:p,L:g,eMq255:x,eMq:f.dot(p,v),rgba:(Math.round(255*v[3])<<24|Math.round(255*v[2])<<16|Math.round(255*v[1])<<8|Math.round(255*v[0])<<0)>>>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;t<n.length;t++)e+=n[t].byteLength;for(var r=new Uint8Array(e),i=0,t=0;t<n.length;t++){for(var o=new Uint8Array(n[t]),a=o.length,l=0;l<a;l+=4){var d=o[l],c=o[l+1],u=o[l+2],f=o[l+3];f==0&&(d=c=u=0),r[i+l]=d,r[i+l+1]=c,r[i+l+2]=u,r[i+l+3]=f}i+=a}return r.buffer};var rde=function(n){if(n===0)return um.Greyscale;if(n===2)return um.Truecolour;if(n===3)return um.IndexedColour;if(n===4)return um.GreyscaleWithAlpha;if(n===6)return um.TruecolourWithAlpha;throw new Error("Unknown color type: "+n)},ide=function(n){for(var e=Math.floor(n.length/4),t=new Uint8Array(e*3),r=new Uint8Array(e*1),i=0,o=0,a=0;i<n.length;)t[o++]=n[i++],t[o++]=n[i++],t[o++]=n[i++],r[a++]=n[i++];return{rgbChannel:t,alphaChannel:r}},um;(function(n){n.Greyscale="Greyscale",n.Truecolour="Truecolour",n.IndexedColour="IndexedColour",n.GreyscaleWithAlpha="GreyscaleWithAlpha",n.TruecolourWithAlpha="TruecolourWithAlpha"})(um||(um={}));var sde=function(){function n(e){var t=dt.decode(e),r=dt.toRGBA8(t);if(r.length>1)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.minBufferLength<e;)this.minBufferLength*=2}return Object.defineProperty(n.prototype,"isEmpty",{get:function(){for(;!this.eof&&this.bufferLength===0;)this.readBlock();return this.bufferLength===0},enumerable:!1,configurable:!0}),n.prototype.getByte=function(){for(var e=this.pos;this.bufferLength<=e;){if(this.eof)return-1;this.readBlock()}return this.buffer[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,i=this.pos;if(e){for(this.ensureBuffer(i+e),r=i+e;!this.eof&&this.bufferLength<r;)this.readBlock();var o=this.bufferLength;r>o&&(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<e;)r*=2;var i=new Uint8Array(r);return i.set(t),this.buffer=i},n}(),K4=function(n){return n===32||n===9||n===13||n===10},ade=function(n){xt(e,n);function e(t,r){var i=n.call(this,r)||this;return i.stream=t,i.input=new Uint8Array(5),r&&(r=.8*r),i}return e.prototype.readBlock=function(){for(var t=126,r=122,i=-1,o=this.stream,a=o.getByte();K4(a);)a=o.getByte();if(a===i||a===t){this.eof=!0;return}var l=this.bufferLength,d,c;if(a===r){for(d=this.ensureBuffer(l+4),c=0;c<4;++c)d[l+c]=0;this.bufferLength+=4}else{var u=this.input;for(u[0]=a,c=1;c<5;++c){for(a=o.getByte();K4(a);)a=o.getByte();if(u[c]=a,a===i||a===t)break}if(d=this.ensureBuffer(l+c-1),this.bufferLength+=c-1,c<5){for(;c<5;++c)u[c]=117;this.eof=!0}var f=0;for(c=0;c<5;++c)f=f*85+(u[c]-33);for(c=3;c>=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<c;d++){var u=r[d],f=void 0;if(u>=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;f<u;++f){if((a=i.getByte())===-1){this.eof=!0;break}t[f]=a}return}var p,g;if(o===1)p=ude,g=hde;else if(o===2){var m=this.getBits(5)+257,y=this.getBits(5)+1,v=this.getBits(4)+4,x=new Uint8Array(X4.length),w=void 0;for(w=0;w<v;++w)x[X4[w]]=this.getBits(3);var S=this.generateHuffmanTable(x);r=0,w=0;for(var _=m+y,b=new Uint8Array(_),C=void 0,T=void 0,F=void 0;w<_;){var A=this.getCode(S);if(A===16)C=2,T=3,F=r;else if(A===17)C=3,T=3,F=r=0;else if(A===18)C=7,T=11,F=r=0;else{b[w++]=r=A;continue}for(var D=this.getBits(C)+T;D-- >0;)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<r;++M,++L)t[L]=t[L-U]}},e.prototype.getBits=function(t){for(var r=this.stream,i=this.codeSize,o=this.codeBuf,a;i<t;){if((a=r.getByte())===-1)throw new Error("Bad encoding in flate stream");o|=a<<i,i+=8}return a=o&(1<<t)-1,this.codeBuf=o>>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<o&&(d=r.getByte())!==-1;)l|=d<<a,a+=8;var c=i[l&(1<<o)-1];typeof i=="number"&&console.log("FLATE:",c);var u=c>>16,f=c&65535;if(u<1||a<u)throw new Error("Bad encoding in flate stream");return this.codeBuf=l>>u,this.codeSize=a-u,f},e.prototype.generateHuffmanTable=function(t){var r=t.length,i=0,o;for(o=0;o<r;++o)t[o]>i&&(i=t[o]);for(var a=1<<i,l=new Int32Array(a),d=1,c=0,u=2;d<=i;++d,c<<=1,u<<=1)for(var f=0;f<r;++f)if(t[f]===d){var p=0,g=c;for(o=0;o<d;++o)p=p<<1|g&1,g>>=1;for(o=p;o<a;o+=u)l[o]=d<<16|f;++c}return[l,i]},e}(sC),pde=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,r)||this;o.stream=t,o.cachedData=0,o.bitsCached=0;for(var a=4096,l={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0},d=0;d<256;++d)l.dictionaryValues[d]=d,l.dictionaryLengths[d]=1;return o.lzwState=l,o}return e.prototype.readBlock=function(){var t=512,r=t*2,i=t,o,a,l,d=this.lzwState;if(d){var c=d.earlyChange,u=d.nextCode,f=d.dictionaryValues,p=d.dictionaryLengths,g=d.dictionaryPrevCodes,m=d.codeLength,y=d.prevCode,v=d.currentSequence,x=d.currentSequenceLength,w=0,S=this.bufferLength,_=this.ensureBuffer(this.bufferLength+r);for(o=0;o<t;o++){var b=this.readBits(m),C=x>0;if(!b||b<256)v[0]=b,x=1;else if(b>=258)if(b<u)for(x=p[b],a=x-1,l=b;a>=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<w){do r+=i;while(r<w);_=this.ensureBuffer(this.bufferLength+r)}for(a=0;a<x;a++)_[S++]=v[a]}d.nextCode=u,d.codeLength=m,d.prevCode=y,d.currentSequenceLength=x,this.bufferLength=S}},e.prototype.readBits=function(t){for(var r=this.bitsCached,i=this.cachedData;r<t;){var o=this.stream.getByte();if(o===-1)return this.eof=!0,null;i=i<<8|o,r+=8}return this.bitsCached=r-=t,this.cachedData=i,i>>>r&(1<<t)-1},e}(sC),gde=function(n){xt(e,n);function e(t,r){var i=n.call(this,r)||this;return i.stream=t,i}return e.prototype.readBlock=function(){var t=this.stream.getBytes(2);if(!t||t.length<2||t[0]===128){this.eof=!0;return}var r,i=this.bufferLength,o=t[0];if(o<128){if(r=this.ensureBuffer(i+o+1),r[i++]=t[1],o>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;d<o;d++)r[i++]=l}this.bufferLength=i},e}(sC),Y4=function(n,e,t){if(e===se.of("FlateDecode"))return new fde(n);if(e===se.of("LZWDecode")){var r=1;if(t instanceof _n){var i=t.lookup(se.of("EarlyChange"));i instanceof fn&&(r=i.asNumber())}return new pde(n,void 0,r)}if(e===se.of("ASCII85Decode"))return new ade(n);if(e===se.of("ASCIIHexDecode"))return new lde(n);if(e===se.of("RunLengthDecode"))return new gde(n);throw new kle(e.asString())},bq=function(n){var e=n.dict,t=n.contents,r=new xq(t),i=e.lookup(se.of("Filter")),o=e.lookup(se.of("DecodeParms"));if(i instanceof se)r=Y4(r,i,o);else if(i instanceof Sr)for(var a=0,l=i.size();a<l;a++)r=Y4(r,i.lookup(a,se),o&&o.lookupMaybe(a,_n));else if(i)throw new nT([se,Sr],i);return r},mde=function(n){var e=n.MediaBox(),t=e.lookup(2,fn).asNumber()-e.lookup(0,fn).asNumber(),r=e.lookup(3,fn).asNumber()-e.lookup(1,fn).asNumber();return{left:0,bottom:0,right:t,top:r}},yde=function(n){return[1,0,0,1,-n.left,-n.bottom]},vq=function(){function n(e,t,r){this.page=e;var i=t??mde(e);this.width=i.right-i.left,this.height=i.top-i.bottom,this.boundingBox=i,this.transformationMatrix=r??yde(i)}return n.for=function(e,t,r){return Pn(this,void 0,void 0,function(){return Rn(this,function(i){return[2,new n(e,t,r)]})})},n.prototype.embedIntoContext=function(e,t){return Pn(this,void 0,void 0,function(){var r,i,o,a,l,d,c,u,f,p;return Rn(this,function(g){if(r=this.page.normalizedEntries(),i=r.Contents,o=r.Resources,!i)throw new _le;return a=this.decodeContents(i),l=this.boundingBox,d=l.left,c=l.bottom,u=l.right,f=l.top,p=e.flateStream(a,{Type:"XObject",Subtype:"Form",FormType:1,BBox:[d,c,u,f],Matrix:this.transformationMatrix,Resources:o}),t?(e.assign(t,p),[2,t]):[2,e.register(p)]})})},n.prototype.decodeContents=function(e){for(var t=Uint8Array.of(le.Newline),r=[],i=0,o=e.size();i<o;i++){var a=e.lookup(i,Gl),l=void 0;if(a instanceof Hj)l=bq(a).decode();else if(a instanceof ZS)l=a.getUnencodedContents();else throw new Cle(a);r.push(l,t)}return Hse.apply(void 0,r)},n}(),z2=function(n,e){if(n!==void 0)return e[n]},JS;(function(n){n.UseNone="UseNone",n.UseOutlines="UseOutlines",n.UseThumbs="UseThumbs",n.UseOC="UseOC"})(JS||(JS={}));var ej;(function(n){n.L2R="L2R",n.R2L="R2L"})(ej||(ej={}));var tj;(function(n){n.None="None",n.AppDefault="AppDefault"})(tj||(tj={}));var sT;(function(n){n.Simplex="Simplex",n.DuplexFlipShortEdge="DuplexFlipShortEdge",n.DuplexFlipLongEdge="DuplexFlipLongEdge"})(sT||(sT={}));var Q4=function(){function n(e){this.dict=e}return n.prototype.lookupBool=function(e){var t=this.dict.lookup(se.of(e));if(t instanceof Uj)return t},n.prototype.lookupName=function(e){var t=this.dict.lookup(se.of(e));if(t instanceof se)return t},n.prototype.HideToolbar=function(){return this.lookupBool("HideToolbar")},n.prototype.HideMenubar=function(){return this.lookupBool("HideMenubar")},n.prototype.HideWindowUI=function(){return this.lookupBool("HideWindowUI")},n.prototype.FitWindow=function(){return this.lookupBool("FitWindow")},n.prototype.CenterWindow=function(){return this.lookupBool("CenterWindow")},n.prototype.DisplayDocTitle=function(){return this.lookupBool("DisplayDocTitle")},n.prototype.NonFullScreenPageMode=function(){return this.lookupName("NonFullScreenPageMode")},n.prototype.Direction=function(){return this.lookupName("Direction")},n.prototype.PrintScaling=function(){return this.lookupName("PrintScaling")},n.prototype.Duplex=function(){return this.lookupName("Duplex")},n.prototype.PickTrayByPDFSize=function(){return this.lookupBool("PickTrayByPDFSize")},n.prototype.PrintPageRange=function(){var e=this.dict.lookup(se.of("PrintPageRange"));if(e instanceof Sr)return e},n.prototype.NumCopies=function(){var e=this.dict.lookup(se.of("NumCopies"));if(e instanceof fn)return e},n.prototype.getHideToolbar=function(){var e,t;return(t=(e=this.HideToolbar())===null||e===void 0?void 0:e.asBoolean())!==null&&t!==void 0?t:!1},n.prototype.getHideMenubar=function(){var e,t;return(t=(e=this.HideMenubar())===null||e===void 0?void 0:e.asBoolean())!==null&&t!==void 0?t:!1},n.prototype.getHideWindowUI=function(){var e,t;return(t=(e=this.HideWindowUI())===null||e===void 0?void 0:e.asBoolean())!==null&&t!==void 0?t:!1},n.prototype.getFitWindow=function(){var e,t;return(t=(e=this.FitWindow())===null||e===void 0?void 0:e.asBoolean())!==null&&t!==void 0?t:!1},n.prototype.getCenterWindow=function(){var e,t;return(t=(e=this.CenterWindow())===null||e===void 0?void 0:e.asBoolean())!==null&&t!==void 0?t:!1},n.prototype.getDisplayDocTitle=function(){var e,t;return(t=(e=this.DisplayDocTitle())===null||e===void 0?void 0:e.asBoolean())!==null&&t!==void 0?t:!1},n.prototype.getNonFullScreenPageMode=function(){var e,t,r=(e=this.NonFullScreenPageMode())===null||e===void 0?void 0:e.decodeText();return(t=z2(r,JS))!==null&&t!==void 0?t:JS.UseNone},n.prototype.getReadingDirection=function(){var e,t,r=(e=this.Direction())===null||e===void 0?void 0:e.decodeText();return(t=z2(r,ej))!==null&&t!==void 0?t:ej.L2R},n.prototype.getPrintScaling=function(){var e,t,r=(e=this.PrintScaling())===null||e===void 0?void 0:e.decodeText();return(t=z2(r,tj))!==null&&t!==void 0?t:tj.AppDefault},n.prototype.getDuplex=function(){var e,t=(e=this.Duplex())===null||e===void 0?void 0:e.decodeText();return z2(t,sT)},n.prototype.getPickTrayByPDFSize=function(){var e;return(e=this.PickTrayByPDFSize())===null||e===void 0?void 0:e.asBoolean()},n.prototype.getPrintPageRange=function(){var e=this.PrintPageRange();if(!e)return[];for(var t=[],r=0;r<e.size();r+=2){var i=e.lookup(r,fn).asNumber(),o=e.lookup(r+1,fn).asNumber();t.push({start:i,end:o})}return t},n.prototype.getNumCopies=function(){var e,t;return(t=(e=this.NumCopies())===null||e===void 0?void 0:e.asNumber())!==null&&t!==void 0?t:1},n.prototype.setHideToolbar=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("HideToolbar"),t)},n.prototype.setHideMenubar=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("HideMenubar"),t)},n.prototype.setHideWindowUI=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("HideWindowUI"),t)},n.prototype.setFitWindow=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("FitWindow"),t)},n.prototype.setCenterWindow=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("CenterWindow"),t)},n.prototype.setDisplayDocTitle=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("DisplayDocTitle"),t)},n.prototype.setNonFullScreenPageMode=function(e){yg(e,"nonFullScreenPageMode",JS);var t=se.of(e);this.dict.set(se.of("NonFullScreenPageMode"),t)},n.prototype.setReadingDirection=function(e){yg(e,"readingDirection",ej);var t=se.of(e);this.dict.set(se.of("Direction"),t)},n.prototype.setPrintScaling=function(e){yg(e,"printScaling",tj);var t=se.of(e);this.dict.set(se.of("PrintScaling"),t)},n.prototype.setDuplex=function(e){yg(e,"duplex",sT);var t=se.of(e);this.dict.set(se.of("Duplex"),t)},n.prototype.setPickTrayByPDFSize=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("PickTrayByPDFSize"),t)},n.prototype.setPrintPageRange=function(e){Array.isArray(e)||(e=[e]);for(var t=[],r=0,i=e.length;r<i;r++)t.push(e[r].start),t.push(e[r].end);lq(t,"printPageRange",["number"]);var o=this.dict.context.obj(t);this.dict.set(se.of("PrintPageRange"),o)},n.prototype.setNumCopies=function(e){Hl(e,"numCopies",1,Number.MAX_VALUE),jle(e,"numCopies");var t=this.dict.context.obj(e);this.dict.set(se.of("NumCopies"),t)},n.fromDict=function(e){return new n(e)},n.create=function(e){var t=e.obj({});return new n(t)},n}(),xde=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+Tf/,wq=function(){function n(e,t){this.dict=e,this.ref=t}return n.prototype.T=function(){return this.dict.lookupMaybe(se.of("T"),Ir,dn)},n.prototype.Ff=function(){var e=this.getInheritableAttribute(se.of("Ff"));return this.dict.context.lookupMaybe(e,fn)},n.prototype.V=function(){var e=this.getInheritableAttribute(se.of("V"));return this.dict.context.lookup(e)},n.prototype.Kids=function(){return this.dict.lookupMaybe(se.of("Kids"),Sr)},n.prototype.DA=function(){var e=this.dict.lookup(se.of("DA"));if(e instanceof Ir||e instanceof dn)return e},n.prototype.setKids=function(e){this.dict.set(se.of("Kids"),this.dict.context.obj(e))},n.prototype.getParent=function(){var e=this.dict.get(se.of("Parent"));if(e instanceof Mr){var t=this.dict.lookup(se.of("Parent"),_n);return new n(t,e)}},n.prototype.setParent=function(e){e?this.dict.set(se.of("Parent"),e):this.dict.delete(se.of("Parent"))},n.prototype.getFullyQualifiedName=function(){var e=this.getParent();return e?e.getFullyQualifiedName()+"."+this.getPartialName():this.getPartialName()},n.prototype.getPartialName=function(){var e;return(e=this.T())===null||e===void 0?void 0:e.decodeText()},n.prototype.setPartialName=function(e){e?this.dict.set(se.of("T"),dn.fromText(e)):this.dict.delete(se.of("T"))},n.prototype.setDefaultAppearance=function(e){this.dict.set(se.of("DA"),Ir.of(e))},n.prototype.getDefaultAppearance=function(){var e=this.DA();return e instanceof dn?e.decodeText():e==null?void 0:e.asString()},n.prototype.setFontSize=function(e){var t,r=(t=this.getFullyQualifiedName())!==null&&t!==void 0?t:"",i=this.getDefaultAppearance();if(!i)throw new Dle(r);var o=Z6(i,xde);if(!o.match)throw new Ele(r);var a=i.slice(0,o.pos-o.match[0].length),l=o.pos<=i.length?i.slice(o.pos):"",d=o.match[1],c=a+" /"+d+" "+e+" Tf "+l;this.setDefaultAppearance(c)},n.prototype.getFlags=function(){var e,t;return(t=(e=this.Ff())===null||e===void 0?void 0:e.asNumber())!==null&&t!==void 0?t:0},n.prototype.setFlags=function(e){this.dict.set(se.of("Ff"),fn.of(e))},n.prototype.hasFlag=function(e){var t=this.getFlags();return(t&e)!==0},n.prototype.setFlag=function(e){var t=this.getFlags();this.setFlags(t|e)},n.prototype.clearFlag=function(e){var t=this.getFlags();this.setFlags(t&~e)},n.prototype.setFlagTo=function(e,t){t?this.setFlag(e):this.clearFlag(e)},n.prototype.getInheritableAttribute=function(e){var t;return this.ascend(function(r){t||(t=r.dict.get(e))}),t},n.prototype.ascend=function(e){e(this);var t=this.getParent();t&&t.ascend(e)},n}(),IP=function(){function n(e){this.dict=e}return n.prototype.W=function(){var e=this.dict.lookup(se.of("W"));if(e instanceof fn)return e},n.prototype.getWidth=function(){var e,t;return(t=(e=this.W())===null||e===void 0?void 0:e.asNumber())!==null&&t!==void 0?t:1},n.prototype.setWidth=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("W"),t)},n.fromDict=function(e){return new n(e)},n}(),bde=function(){function n(e){this.dict=e}return n.prototype.Rect=function(){return this.dict.lookup(se.of("Rect"),Sr)},n.prototype.AP=function(){return this.dict.lookupMaybe(se.of("AP"),_n)},n.prototype.F=function(){var e=this.dict.lookup(se.of("F"));return this.dict.context.lookupMaybe(e,fn)},n.prototype.getRectangle=function(){var e,t=this.Rect();return(e=t==null?void 0:t.asRectangle())!==null&&e!==void 0?e:{x:0,y:0,width:0,height:0}},n.prototype.setRectangle=function(e){var t=e.x,r=e.y,i=e.width,o=e.height,a=this.dict.context.obj([t,r,t+i,r+o]);this.dict.set(se.of("Rect"),a)},n.prototype.getAppearanceState=function(){var e=this.dict.lookup(se.of("AS"));if(e instanceof se)return e},n.prototype.setAppearanceState=function(e){this.dict.set(se.of("AS"),e)},n.prototype.setAppearances=function(e){this.dict.set(se.of("AP"),e)},n.prototype.ensureAP=function(){var e=this.AP();return e||(e=this.dict.context.obj({}),this.dict.set(se.of("AP"),e)),e},n.prototype.getNormalAppearance=function(){var e=this.ensureAP(),t=e.get(se.of("N"));if(t instanceof Mr||t instanceof _n)return t;throw new Error("Unexpected N type: "+(t==null?void 0:t.constructor.name))},n.prototype.setNormalAppearance=function(e){var t=this.ensureAP();t.set(se.of("N"),e)},n.prototype.setRolloverAppearance=function(e){var t=this.ensureAP();t.set(se.of("R"),e)},n.prototype.setDownAppearance=function(e){var t=this.ensureAP();t.set(se.of("D"),e)},n.prototype.removeRolloverAppearance=function(){var e=this.AP();e==null||e.delete(se.of("R"))},n.prototype.removeDownAppearance=function(){var e=this.AP();e==null||e.delete(se.of("D"))},n.prototype.getAppearances=function(){var e=this.AP();if(e){var t=e.lookup(se.of("N"),_n,Gl),r=e.lookupMaybe(se.of("R"),_n,Gl),i=e.lookupMaybe(se.of("D"),_n,Gl);return{normal:t,rollover:r,down:i}}},n.prototype.getFlags=function(){var e,t;return(t=(e=this.F())===null||e===void 0?void 0:e.asNumber())!==null&&t!==void 0?t:0},n.prototype.setFlags=function(e){this.dict.set(se.of("F"),fn.of(e))},n.prototype.hasFlag=function(e){var t=this.getFlags();return(t&e)!==0},n.prototype.setFlag=function(e){var t=this.getFlags();this.setFlags(t|e)},n.prototype.clearFlag=function(e){var t=this.getFlags();this.setFlags(t&~e)},n.prototype.setFlagTo=function(e,t){t?this.setFlag(e):this.clearFlag(e)},n.fromDict=function(e){return new n(e)},n}(),MP=function(){function n(e){this.dict=e}return n.prototype.R=function(){var e=this.dict.lookup(se.of("R"));if(e instanceof fn)return e},n.prototype.BC=function(){var e=this.dict.lookup(se.of("BC"));if(e instanceof Sr)return e},n.prototype.BG=function(){var e=this.dict.lookup(se.of("BG"));if(e instanceof Sr)return e},n.prototype.CA=function(){var e=this.dict.lookup(se.of("CA"));if(e instanceof dn||e instanceof Ir)return e},n.prototype.RC=function(){var e=this.dict.lookup(se.of("RC"));if(e instanceof dn||e instanceof Ir)return e},n.prototype.AC=function(){var e=this.dict.lookup(se.of("AC"));if(e instanceof dn||e instanceof Ir)return e},n.prototype.getRotation=function(){var e;return(e=this.R())===null||e===void 0?void 0:e.asNumber()},n.prototype.getBorderColor=function(){var e=this.BC();if(e){for(var t=[],r=0,i=e==null?void 0:e.size();r<i;r++){var o=e.get(r);o instanceof fn&&t.push(o.asNumber())}return t}},n.prototype.getBackgroundColor=function(){var e=this.BG();if(e){for(var t=[],r=0,i=e==null?void 0:e.size();r<i;r++){var o=e.get(r);o instanceof fn&&t.push(o.asNumber())}return t}},n.prototype.getCaptions=function(){var e=this.CA(),t=this.RC(),r=this.AC();return{normal:e==null?void 0:e.decodeText(),rollover:t==null?void 0:t.decodeText(),down:r==null?void 0:r.decodeText()}},n.prototype.setRotation=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("R"),t)},n.prototype.setBorderColor=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("BC"),t)},n.prototype.setBackgroundColor=function(e){var t=this.dict.context.obj(e);this.dict.set(se.of("BG"),t)},n.prototype.setCaptions=function(e){var t=dn.fromText(e.normal);if(this.dict.set(se.of("CA"),t),e.rollover){var r=dn.fromText(e.rollover);this.dict.set(se.of("RC"),r)}else this.dict.delete(se.of("RC"));if(e.down){var i=dn.fromText(e.down);this.dict.set(se.of("AC"),i)}else this.dict.delete(se.of("AC"))},n.fromDict=function(e){return new n(e)},n}(),NB=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.MK=function(){var t=this.dict.lookup(se.of("MK"));if(t instanceof _n)return t},e.prototype.BS=function(){var t=this.dict.lookup(se.of("BS"));if(t instanceof _n)return t},e.prototype.DA=function(){var t=this.dict.lookup(se.of("DA"));if(t instanceof Ir||t instanceof dn)return t},e.prototype.P=function(){var t=this.dict.get(se.of("P"));if(t instanceof Mr)return t},e.prototype.setP=function(t){this.dict.set(se.of("P"),t)},e.prototype.setDefaultAppearance=function(t){this.dict.set(se.of("DA"),Ir.of(t))},e.prototype.getDefaultAppearance=function(){var t=this.DA();return t instanceof dn?t.decodeText():t==null?void 0:t.asString()},e.prototype.getAppearanceCharacteristics=function(){var t=this.MK();if(t)return MP.fromDict(t)},e.prototype.getOrCreateAppearanceCharacteristics=function(){var t=this.MK();if(t)return MP.fromDict(t);var r=MP.fromDict(this.dict.context.obj({}));return this.dict.set(se.of("MK"),r.dict),r},e.prototype.getBorderStyle=function(){var t=this.BS();if(t)return IP.fromDict(t)},e.prototype.getOrCreateBorderStyle=function(){var t=this.BS();if(t)return IP.fromDict(t);var r=IP.fromDict(this.dict.context.obj({}));return this.dict.set(se.of("BS"),r.dict),r},e.prototype.getOnValue=function(){var t,r=(t=this.getAppearances())===null||t===void 0?void 0:t.normal;if(r instanceof _n)for(var i=r.keys(),o=0,a=i.length;o<a;o++){var l=i[o];if(l!==se.of("Off"))return l}},e.fromDict=function(t){return new e(t)},e.create=function(t,r){var i=t.obj({Type:"Annot",Subtype:"Widget",Rect:[0,0,0,0],Parent:r});return new e(i)},e}(bde),j1=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.FT=function(){var t=this.getInheritableAttribute(se.of("FT"));return this.dict.context.lookup(t,se)},e.prototype.getWidgets=function(){var t=this.Kids();if(!t)return[NB.fromDict(this.dict)];for(var r=new Array(t.size()),i=0,o=t.size();i<o;i++){var a=t.lookup(i,_n);r[i]=NB.fromDict(a)}return r},e.prototype.addWidget=function(t){var r=this.normalizedEntries().Kids;r.push(t)},e.prototype.removeWidget=function(t){var r=this.Kids();if(r){if(t<0||t>r.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();i<o;i++){var a=t.lookup(i);(a instanceof Ir||a instanceof dn)&&r.push(a)}return r}},e.prototype.removeExportValue=function(t){var r=this.Opt();if(r)if(r instanceof Ir||r instanceof dn){if(t!==0)throw new rT(t,0,0);this.setOpt([])}else{if(t<0||t>r.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;c<u;c++){var f=d[c],p=(r=a[c])!==null&&r!==void 0?r:dn.fromText((o=(i=f.getOnValue())===null||i===void 0?void 0:i.decodeText())!==null&&o!==void 0?o:"");l.push(p)}this.setOpt(l)},e.prototype.addOpt=function(t,r){var i;this.normalizeExportValues();var o=t.decodeText(),a;if(r)for(var l=(i=this.getExportValues())!==null&&i!==void 0?i:[],d=0,c=l.length;d<c;d++){var u=l[d];u.decodeText()===o&&(a=d)}var f=this.Opt();return f.push(t),a??f.size()-1},e.prototype.addWidgetWithOpt=function(t,r,i){var o=this.addOpt(r,i),a=se.of(String(o));return this.addWidget(t),a},e}(j1),WF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.setValue=function(t){var r,i=(r=this.getOnValue())!==null&&r!==void 0?r:se.of("Yes");if(t!==i&&t!==se.of("Off"))throw new l3;this.dict.set(se.of("V"),t);for(var o=this.getWidgets(),a=0,l=o.length;a<l;a++){var d=o[a],c=d.getOnValue()===t?t:se.of("Off");d.setAppearanceState(c)}},e.prototype.getValue=function(){var t=this.V();return t instanceof se?t:se.of("Off")},e.prototype.getOnValue=function(){var t=this.getWidgets()[0];return t==null?void 0:t.getOnValue()},e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Btn",Kids:[]}),i=t.register(r);return new e(r,i)},e}(f3),Ts=function(n){return 1<<n},sc;(function(n){n[n.ReadOnly=Ts(0)]="ReadOnly",n[n.Required=Ts(1)]="Required",n[n.NoExport=Ts(2)]="NoExport"})(sc||(sc={}));var Cd;(function(n){n[n.NoToggleToOff=Ts(14)]="NoToggleToOff",n[n.Radio=Ts(15)]="Radio",n[n.PushButton=Ts(16)]="PushButton",n[n.RadiosInUnison=Ts(25)]="RadiosInUnison"})(Cd||(Cd={}));var Ki;(function(n){n[n.Multiline=Ts(12)]="Multiline",n[n.Password=Ts(13)]="Password",n[n.FileSelect=Ts(20)]="FileSelect",n[n.DoNotSpellCheck=Ts(22)]="DoNotSpellCheck",n[n.DoNotScroll=Ts(23)]="DoNotScroll",n[n.Comb=Ts(24)]="Comb",n[n.RichText=Ts(25)]="RichText"})(Ki||(Ki={}));var Br;(function(n){n[n.Combo=Ts(17)]="Combo",n[n.Edit=Ts(18)]="Edit",n[n.Sort=Ts(19)]="Sort",n[n.MultiSelect=Ts(21)]="MultiSelect",n[n.DoNotSpellCheck=Ts(22)]="DoNotSpellCheck",n[n.CommitOnSelChange=Ts(26)]="CommitOnSelChange"})(Br||(Br={}));var Sq=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.setValues=function(t){if(this.hasFlag(Br.Combo)&&!this.hasFlag(Br.Edit)&&!this.valuesAreValid(t))throw new l3;if(t.length===0&&this.dict.delete(se.of("V")),t.length===1&&this.dict.set(se.of("V"),t[0]),t.length>1){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;o<a;o++){var l=i(o);if(typeof l=="object")return l.value}return!0},e.prototype.updateSelectedIndices=function(t){if(t.length>1){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;a<l;a++)o(a,l);this.dict.set(se.of("I"),this.dict.context.obj(r.sort()))}else this.dict.delete(se.of("I"))},e.prototype.getValues=function(){var t=this.V();if(t instanceof Ir||t instanceof dn)return[t];if(t instanceof Sr){for(var r=[],i=0,o=t.size();i<o;i++){var a=t.lookup(i);(a instanceof Ir||a instanceof dn)&&r.push(a)}return r}return[]},e.prototype.Opt=function(){return this.dict.lookupMaybe(se.of("Opt"),Ir,dn,Sr)},e.prototype.setOptions=function(t){for(var r=new Array(t.length),i=0,o=t.length;i<o;i++){var a=t[i],l=a.value,d=a.display;r[i]=this.dict.context.obj([l,d||l])}this.dict.set(se.of("Opt"),this.dict.context.obj(r))},e.prototype.getOptions=function(){var t=this.Opt();if(t instanceof Ir||t instanceof dn)return[{value:t,display:t}];if(t instanceof Sr){for(var r=[],i=0,o=t.size();i<o;i++){var a=t.lookup(i);if((a instanceof Ir||a instanceof dn)&&r.push({value:a,display:a}),a instanceof Sr&&a.size()>0){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;o<a;o++){var l=i[o],d=l.getOnValue()===t?t:se.of("Off");l.setAppearanceState(d)}},e.prototype.getValue=function(){var t=this.V();return t instanceof se?t:se.of("Off")},e.prototype.getOnValues=function(){for(var t=this.getWidgets(),r=[],i=0,o=t.length;i<o;i++){var a=t[i].getOnValue();a&&r.push(a)}return r},e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Btn",Ff:Cd.Radio,Kids:[]}),i=t.register(r);return new e(r,i)},e}(f3),GF=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",Kids:[]}),i=t.register(r);return new e(r,i)},e}(Sq),g3=function(n){if(!n)return[];for(var e=[],t=0,r=n.size();t<r;t++){var i=n.get(t),o=n.lookup(t);i instanceof Mr&&o instanceof _n&&e.push([jq(o,i),i])}return e},jq=function(n,e){var t=vde(n);return t?oT.fromDict(n,e):wde(n,e)},vde=function(n){var e=n.lookup(se.of("Kids"));if(e instanceof Sr)for(var t=0,r=e.size();t<r;t++){var i=e.lookup(t),o=i instanceof _n&&i.has(se.of("T"));if(o)return!0}return!1},wde=function(n,e){var t=m3(n,se.of("FT")),r=n.context.lookup(t,se);return r===se.of("Btn")?Sde(n,e):r===se.of("Ch")?jde(n,e):r===se.of("Tx")?HF.fromDict(n,e):r===se.of("Sig")?p3.fromDict(n,e):j1.fromDict(n,e)},Sde=function(n,e){var t,r=m3(n,se.of("Ff")),i=n.context.lookupMaybe(r,fn),o=(t=i==null?void 0:i.asNumber())!==null&&t!==void 0?t:0;return WB(o,Cd.PushButton)?qF.fromDict(n,e):WB(o,Cd.Radio)?VF.fromDict(n,e):WF.fromDict(n,e)},jde=function(n,e){var t,r=m3(n,se.of("Ff")),i=n.context.lookupMaybe(r,fn),o=(t=i==null?void 0:i.asNumber())!==null&&t!==void 0?t:0;return WB(o,Br.Combo)?UF.fromDict(n,e):GF.fromDict(n,e)},WB=function(n,e){return(n&e)!==0},m3=function(n,e){var t;return kq(n,function(r){t||(t=r.get(e))}),t},kq=function(n,e){e(n);var t=n.lookupMaybe(se.of("Parent"),_n);t&&kq(t,e)},aT=function(){function n(e){this.dict=e}return n.prototype.Fields=function(){var e=this.dict.lookup(se.of("Fields"));if(e instanceof Sr)return e},n.prototype.getFields=function(){for(var e=this.normalizedEntries().Fields,t=new Array(e.size()),r=0,i=e.size();r<i;r++){var o=e.get(r),a=e.lookup(r,_n);t[r]=[jq(a,o),o]}return t},n.prototype.getAllFields=function(){var e=[],t=function(r){if(r)for(var i=0,o=r.length;i<o;i++){var a=r[i];e.push(a);var l=a[0];l instanceof oT&&t(g3(l.Kids()))}};return t(this.getFields()),e},n.prototype.addField=function(e){var t=this.normalizedEntries().Fields;t==null||t.push(e)},n.prototype.removeField=function(e){var t=e.getParent(),r=t===void 0?this.normalizedEntries().Fields:t.Kids(),i=r==null?void 0:r.indexOf(e.ref);if(r===void 0||i===void 0)throw new Error("Tried to remove inexistent field "+e.getFullyQualifiedName());r.remove(i),t!==void 0&&r.size()===0&&this.removeField(t)},n.prototype.normalizedEntries=function(){var e=this.Fields();return e||(e=this.dict.context.obj([]),this.dict.set(se.of("Fields"),e)),{Fields:e}},n.fromDict=function(e){return new n(e)},n.create=function(e){var t=e.obj({Fields:[]});return new n(t)},n}(),_q=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.Pages=function(){return this.lookup(se.of("Pages"),_n)},e.prototype.AcroForm=function(){return this.lookupMaybe(se.of("AcroForm"),_n)},e.prototype.getAcroForm=function(){var t=this.AcroForm();if(t)return aT.fromDict(t)},e.prototype.getOrCreateAcroForm=function(){var t=this.getAcroForm();if(!t){t=aT.create(this.context);var r=this.context.register(t.dict);this.set(se.of("AcroForm"),r)}return t},e.prototype.ViewerPreferences=function(){return this.lookupMaybe(se.of("ViewerPreferences"),_n)},e.prototype.getViewerPreferences=function(){var t=this.ViewerPreferences();if(t)return Q4.fromDict(t)},e.prototype.getOrCreateViewerPreferences=function(){var t=this.getViewerPreferences();if(!t){t=Q4.create(this.context);var r=this.context.register(t.dict);this.set(se.of("ViewerPreferences"),r)}return t},e.prototype.insertLeafNode=function(t,r){var i=this.get(se.of("Pages")),o=this.Pages().insertLeafNode(t,r);return o||i},e.prototype.removeLeafNode=function(t){this.Pages().removeLeafNode(t)},e.withContextAndPages=function(t,r){var i=new Map;return i.set(se.of("Type"),se.of("Catalog")),i.set(se.of("Pages"),r),new e(i,t)},e.fromMapWithContext=function(t,r){return new e(t,r)},e}(_n),Cq=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.Parent=function(){return this.lookup(se.of("Parent"))},e.prototype.Kids=function(){return this.lookup(se.of("Kids"),Sr)},e.prototype.Count=function(){return this.lookup(se.of("Count"),fn)},e.prototype.pushTreeNode=function(t){var r=this.Kids();r.push(t)},e.prototype.pushLeafNode=function(t){var r=this.Kids();this.insertLeafKid(r.size(),t)},e.prototype.insertLeafNode=function(t,r){var i=this.Kids(),o=this.Count().asNumber();if(r>o)throw new z4(r,o);for(var a=r,l=0,d=i.size();l<d;l++){if(a===0){this.insertLeafKid(l,t);return}var c=i.get(l),u=this.context.lookup(c);if(u instanceof e){if(u.Count().asNumber()>a)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();l<d;l++){var c=i.get(l),u=this.context.lookup(c);if(u instanceof e)if(u.Count().asNumber()>a){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();i<o;i++){var a=r.get(i),l=this.context.lookup(a);l instanceof e&&l.traverse(t),t(l,a)}},e.prototype.insertLeafKid=function(t,r){var i=this.Kids();this.ascend(function(o){var a=o.Count().asNumber()+1;o.set(se.of("Count"),fn.of(a))}),i.insert(t,r)},e.prototype.removeKid=function(t){var r=this.Kids(),i=r.lookup(t);i instanceof yf&&this.ascend(function(o){var a=o.Count().asNumber()-1;o.set(se.of("Count"),fn.of(a))}),r.remove(t)},e.withContext=function(t,r){var i=new Map;return i.set(se.of("Type"),se.of("Pages")),i.set(se.of("Kids"),t.obj([])),i.set(se.of("Count"),t.obj(0)),r&&i.set(se.of("Parent"),r),new e(i,t)},e.fromMapWithContext=function(t,r){return new e(t,r)},e}(_n),oa=new Uint8Array(256);oa[le.Zero]=1;oa[le.One]=1;oa[le.Two]=1;oa[le.Three]=1;oa[le.Four]=1;oa[le.Five]=1;oa[le.Six]=1;oa[le.Seven]=1;oa[le.Eight]=1;oa[le.Nine]=1;var KF=new Uint8Array(256);KF[le.Period]=1;KF[le.Plus]=1;KF[le.Minus]=1;var y3=new Uint8Array(256);for(var Lw=0,kde=256;Lw<kde;Lw++)y3[Lw]=oa[Lw]||KF[Lw]?1:0;var $4=le.Newline,Z4=le.CarriageReturn,_de=function(){function n(e,t){t===void 0&&(t=!1),this.bytes=e,this.capNumbers=t}return n.prototype.parseRawInt=function(){for(var e="";!this.bytes.done();){var t=this.bytes.peek();if(!oa[t])break;e+=gf(this.bytes.next())}var r=Number(e);if(!e||!isFinite(r))throw new L4(this.bytes.position(),e);return r},n.prototype.parseRawNumber=function(){for(var e="";!this.bytes.done();){var t=this.bytes.peek();if(!y3[t]||(e+=gf(this.bytes.next()),t===le.Period))break}for(;!this.bytes.done();){var t=this.bytes.peek();if(!oa[t])break;e+=gf(this.bytes.next())}var r=Number(e);if(!e||!isFinite(r))throw new L4(this.bytes.position(),e);if(r>Number.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<i;r++)if(this.bytes.done()||this.bytes.next()!==e[r])return this.bytes.moveTo(t),!1;return!0},n}(),XF=function(){function n(e){this.idx=0,this.line=0,this.column=0,this.bytes=e,this.length=this.bytes.length}return n.prototype.moveTo=function(e){this.idx=e},n.prototype.next=function(){var e=this.bytes[this.idx++];return e===le.Newline?(this.line+=1,this.column=0):this.column+=1,e},n.prototype.assertNext=function(e){if(this.peek()!==e)throw new Ple(this.position(),e,this.peek());return this.next()},n.prototype.peek=function(){return this.bytes[this.idx]},n.prototype.peekAhead=function(e){return this.bytes[this.idx+e]},n.prototype.peekAt=function(e){return this.bytes[e]},n.prototype.done=function(){return this.idx>=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<i?(o=t[r],a=o.objectNumber,l=o.offset,this.bytes.moveTo(this.firstOffset+l),d=this.parseObject(),c=Mr.of(a,0),this.context.assign(c,d),this.shouldWaitForTick()?[4,a1()]:[3,3]):[3,4];case 2:u.sent(),u.label=3;case 3:return r++,[3,1];case 4:return[2]}})})},e.prototype.parseOffsetsAndObjectNumbers=function(){for(var t=[],r=0,i=this.objectCount;r<i;r++){this.skipWhitespaceAndComments();var o=this.parseRawInt();this.skipWhitespaceAndComments();var a=this.parseRawInt();t.push({objectNumber:o,offset:a})}return t},e.forStream=function(t,r){return new e(t,r)},e}(Aq),Tde=function(){function n(e){this.alreadyParsed=!1,this.dict=e.dict,this.bytes=XF.fromPDFRawStream(e),this.context=this.dict.context;var t=this.dict.lookup(se.of("Size"),fn),r=this.dict.lookup(se.of("Index"));if(r instanceof Sr){this.subsections=[];for(var i=0,o=r.size();i<o;i+=2){var a=r.lookup(i+0,fn).asNumber(),l=r.lookup(i+1,fn).asNumber();this.subsections.push({firstObjectNumber:a,length:l})}}else this.subsections=[{firstObjectNumber:0,length:t.asNumber()}];var d=this.dict.lookup(se.of("W"),Sr);this.byteWidths=[-1,-1,-1];for(var i=0,o=d.size();i<o;i++)this.byteWidths[i]=d.lookup(i,fn).asNumber()}return n.prototype.parseIntoContext=function(){if(this.alreadyParsed)throw new a3("PDFXRefStreamParser","parseIntoContext");this.alreadyParsed=!0,this.context.trailerInfo={Root:this.dict.get(se.of("Root")),Encrypt:this.dict.get(se.of("Encrypt")),Info:this.dict.get(se.of("Info")),ID:this.dict.get(se.of("ID"))};var e=this.parseEntries();return e},n.prototype.parseEntries=function(){for(var e=[],t=this.byteWidths,r=t[0],i=t[1],o=t[2],a=0,l=this.subsections.length;a<l;a++)for(var d=this.subsections[a],c=d.firstObjectNumber,u=d.length,f=0;f<u;f++){for(var p=0,g=0,m=r;g<m;g++)p=p<<8|this.bytes.next();for(var y=0,g=0,m=i;g<m;g++)y=y<<8|this.bytes.next();for(var v=0,g=0,m=o;g<m;g++)v=v<<8|this.bytes.next();r===0&&(p=1);var x=c+f,w={ref:Mr.of(x,v),offset:y,deleted:p===0,inObjectStream:p===2};e.push(w)}return e},n.forStream=function(e){return new n(e)},n}(),Fde=function(n){xt(e,n);function e(t,r,i,o){r===void 0&&(r=1/0),i===void 0&&(i=!1),o===void 0&&(o=!1);var a=n.call(this,XF.of(t),OB.create(),o)||this;return a.alreadyParsed=!1,a.parsedObjects=0,a.shouldWaitForTick=function(){return a.parsedObjects+=1,a.parsedObjects%a.objectsPerTick===0},a.objectsPerTick=r,a.throwOnInvalidObject=i,a}return e.prototype.parseDocument=function(){return Pn(this,void 0,void 0,function(){var t,r;return Rn(this,function(i){switch(i.label){case 0:if(this.alreadyParsed)throw new a3("PDFParser","parseDocument");this.alreadyParsed=!0,this.context.header=this.parseHeader(),i.label=1;case 1:return this.bytes.done()?[3,3]:[4,this.parseDocumentSection()];case 2:if(i.sent(),r=this.bytes.offset(),r===t)throw new zle(this.bytes.position());return t=r,[3,1];case 3:return this.maybeRecoverRoot(),this.context.lookup(Mr.of(0))&&(console.warn("Removing parsed object: 0 0 R"),this.context.delete(Mr.of(0))),[2,this.context]}})})},e.prototype.maybeRecoverRoot=function(){var t=function(u){return u instanceof _n&&u.lookup(se.of("Type"))===se.of("Catalog")},r=this.context.lookup(this.context.trailerInfo.Root);if(!t(r))for(var i=this.context.enumerateIndirectObjects(),o=0,a=i.length;o<a;o++){var l=i[o],d=l[0],c=l[1];t(c)&&(this.context.trailerInfo.Root=d)}},e.prototype.parseHeader=function(){for(;!this.bytes.done();){if(this.matchKeyword(ai.header)){var t=this.parseRawInt();this.bytes.assertNext(le.Period);var r=this.parseRawInt(),i=NF.forVersion(t,r);return this.skipBinaryHeaderComment(),i}this.bytes.next()}throw new Ole(this.bytes.position())},e.prototype.parseIndirectObjectHeader=function(){this.skipWhitespaceAndComments();var t=this.parseRawInt();this.skipWhitespaceAndComments();var r=this.parseRawInt();if(this.skipWhitespaceAndComments(),!this.matchKeyword(ai.obj))throw new Lle(this.bytes.position(),ai.obj);return Mr.of(t,r)},e.prototype.matchIndirectObjectHeader=function(){var t=this.bytes.offset();try{return this.parseIndirectObjectHeader(),!0}catch{return this.bytes.moveTo(t),!1}},e.prototype.parseIndirectObject=function(){return Pn(this,void 0,void 0,function(){var t,r;return Rn(this,function(i){switch(i.label){case 0:return t=this.parseIndirectObjectHeader(),this.skipWhitespaceAndComments(),r=this.parseObject(),this.skipWhitespaceAndComments(),this.matchKeyword(ai.endobj),r instanceof Hj&&r.dict.lookup(se.of("Type"))===se.of("ObjStm")?[4,Ade.forStream(r,this.shouldWaitForTick).parseIntoContext()]:[3,2];case 1:return i.sent(),[3,3];case 2:r instanceof Hj&&r.dict.lookup(se.of("Type"))===se.of("XRef")?Tde.forStream(r).parseIntoContext():this.context.assign(t,r),i.label=3;case 3:return[2,t]}})})},e.prototype.tryToParseInvalidIndirectObject=function(){var t=this.bytes.position(),r="Trying to parse invalid object: "+JSON.stringify(t)+")";if(this.throwOnInvalidObject)throw new Error(r);console.warn(r);var i=this.parseIndirectObjectHeader();console.warn("Invalid object ref: "+i),this.skipWhitespaceAndComments();for(var o=this.bytes.offset(),a=!0;!this.bytes.done()&&(this.matchKeyword(ai.endobj)&&(a=!1),!!a);)this.bytes.next();if(a)throw new Ble(t);var l=this.bytes.offset()-ai.endobj.length,d=gq.of(this.bytes.slice(o,l));return this.context.assign(i,d),i},e.prototype.parseIndirectObjects=function(){return Pn(this,void 0,void 0,function(){var t;return Rn(this,function(r){switch(r.label){case 0:this.skipWhitespaceAndComments(),r.label=1;case 1:if(!(!this.bytes.done()&&oa[this.bytes.peek()]))return[3,8];t=this.bytes.offset(),r.label=2;case 2:return r.trys.push([2,4,,5]),[4,this.parseIndirectObject()];case 3:return r.sent(),[3,5];case 4:return r.sent(),this.bytes.moveTo(t),this.tryToParseInvalidIndirectObject(),[3,5];case 5:return this.skipWhitespaceAndComments(),this.skipJibberish(),this.shouldWaitForTick()?[4,a1()]:[3,7];case 6:r.sent(),r.label=7;case 7:return[3,1];case 8:return[2]}})})},e.prototype.maybeParseCrossRefSection=function(){if(this.skipWhitespaceAndComments(),!!this.matchKeyword(ai.xref)){this.skipWhitespaceAndComments();for(var t=-1,r=hq.createEmpty();!this.bytes.done()&&oa[this.bytes.peek()];){var i=this.parseRawInt();this.skipWhitespaceAndComments();var o=this.parseRawInt();this.skipWhitespaceAndComments();var a=this.bytes.peek();if(a===le.n||a===le.f){var l=Mr.of(t,o);this.bytes.next()===le.n?r.addEntry(l,i):r.addDeletedEntry(l,i),t+=1}else t=i;this.skipWhitespaceAndComments()}return r}},e.prototype.maybeParseTrailerDict=function(){if(this.skipWhitespaceAndComments(),!!this.matchKeyword(ai.trailer)){this.skipWhitespaceAndComments();var t=this.parseDict(),r=this.context;r.trailerInfo={Root:t.get(se.of("Root"))||r.trailerInfo.Root,Encrypt:t.get(se.of("Encrypt"))||r.trailerInfo.Encrypt,Info:t.get(se.of("Info"))||r.trailerInfo.Info,ID:t.get(se.of("ID"))||r.trailerInfo.ID}}},e.prototype.maybeParseTrailer=function(){if(this.skipWhitespaceAndComments(),!!this.matchKeyword(ai.startxref)){this.skipWhitespaceAndComments();var t=this.parseRawInt();return this.skipWhitespace(),this.matchKeyword(ai.eof),this.skipWhitespaceAndComments(),this.matchKeyword(ai.eof),this.skipWhitespaceAndComments(),u3.forLastCrossRefSectionOffset(t)}},e.prototype.parseDocumentSection=function(){return Pn(this,void 0,void 0,function(){return Rn(this,function(t){switch(t.label){case 0:return[4,this.parseIndirectObjects()];case 1:return t.sent(),this.maybeParseCrossRefSection(),this.maybeParseTrailerDict(),this.maybeParseTrailer(),this.skipJibberish(),[2]}})})},e.prototype.skipJibberish=function(){for(this.skipWhitespaceAndComments();!this.bytes.done();){var t=this.bytes.offset(),r=this.bytes.peek(),i=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<<n},nj;(function(n){n[n.Invisible=Gc(0)]="Invisible",n[n.Hidden=Gc(1)]="Hidden",n[n.Print=Gc(2)]="Print",n[n.NoZoom=Gc(3)]="NoZoom",n[n.NoRotate=Gc(4)]="NoRotate",n[n.NoView=Gc(5)]="NoView",n[n.ReadOnly=Gc(6)]="ReadOnly",n[n.Locked=Gc(7)]="Locked",n[n.ToggleNoView=Gc(8)]="ToggleNoView",n[n.LockedContents=Gc(9)]="LockedContents"})(nj||(nj={}));var YF=function(n){return n instanceof se?n:se.of(n)},pn=function(n){return n instanceof fn?n:fn.of(n)},Mn=function(n){return n instanceof fn?n.asNumber():n},qj;(function(n){n.Degrees="degrees",n.Radians="radians"})(qj||(qj={}));var cn=function(n){return Ie(n,"degreeAngle",["number"]),{type:qj.Degrees,angle:n}},Tq=qj.Radians,Fq=qj.Degrees,Dq=function(n){return n*Math.PI/180},Dde=function(n){return n*180/Math.PI},Mo=function(n){return n.type===Tq?n.angle:n.type===Fq?Dq(n.angle):eC("Invalid rotation: "+JSON.stringify(n))},Eq=function(n){return n.type===Tq?Dde(n.angle):n.type===Fq?n.angle:eC("Invalid rotation: "+JSON.stringify(n))},If=function(n){n===void 0&&(n=0);var e=n/90%4;return e===0?0:e===1?90:e===2?180:e===3?270:0},z0=function(n,e){e===void 0&&(e=0);var t=If(e);return t===90||t===270?{width:n.height,height:n.width}:{width:n.width,height:n.height}},Ede=function(n,e,t){e===void 0&&(e=0),t===void 0&&(t=0);var r=n.x,i=n.y,o=n.width,a=n.height,l=If(t),d=e/2;return l===0?{x:r-d,y:i-d,width:o,height:a}:l===90?{x:r-a+d,y:i-d,width:a,height:o}:l===180?{x:r-o+d,y:i-a+d,width:o,height:a}:l===270?{x:r-d,y:i-o+d,width:a,height:o}:{x:r-d,y:i-d,width:o,height:a}},Pq=function(){return or.of(pr.ClipNonZero)},lT=Math.cos,dT=Math.sin,cT=Math.tan,QF=function(n,e,t,r,i,o){return or.of(pr.ConcatTransformationMatrix,[pn(n),pn(e),pn(t),pn(r),pn(i),pn(o)])},Rd=function(n,e){return QF(1,0,0,1,n,e)},Vj=function(n,e){return QF(n,0,0,e,0,0)},k1=function(n){return QF(lT(Mn(n)),dT(Mn(n)),-dT(Mn(n)),lT(Mn(n)),0,0)},L2=function(n){return k1(Dq(Mn(n)))},x3=function(n,e){return QF(1,cT(Mn(n)),cT(Mn(e)),1,0,0)},$F=function(n,e){return or.of(pr.SetLineDashPattern,["["+n.map(pn).join(" ")+"]",pn(e)])},Kx;(function(n){n[n.Butt=0]="Butt",n[n.Round=1]="Round",n[n.Projecting=2]="Projecting"})(Kx||(Kx={}));var ZF=function(n){return or.of(pr.SetLineCapStyle,[pn(n)])},J4;(function(n){n[n.Miter=0]="Miter",n[n.Round=1]="Round",n[n.Bevel=2]="Bevel"})(J4||(J4={}));var O0=function(n){return or.of(pr.SetGraphicsStateParams,[YF(n)])},qs=function(){return or.of(pr.PushGraphicsState)},Vs=function(){return or.of(pr.PopGraphicsState)},oC=function(n){return or.of(pr.SetLineWidth,[pn(n)])},ql=function(n,e,t,r,i,o){return or.of(pr.AppendBezierCurve,[pn(n),pn(e),pn(t),pn(r),pn(i),pn(o)])},N2=function(n,e,t,r){return or.of(pr.CurveToReplicateInitialPoint,[pn(n),pn(e),pn(t),pn(r)])},zg=function(){return or.of(pr.ClosePath)},Ou=function(n,e){return or.of(pr.MoveTo,[pn(n),pn(e)])},ho=function(n,e){return or.of(pr.LineTo,[pn(n),pn(e)])},aC=function(){return or.of(pr.StrokePath)},b3=function(){return or.of(pr.FillNonZero)},v3=function(){return or.of(pr.FillNonZeroAndStroke)},Rq=function(){return or.of(pr.EndPath)},Pde=function(){return or.of(pr.NextLine)},Bq=function(n){return or.of(pr.ShowText,[n])},Iq=function(){return or.of(pr.BeginText)},Mq=function(){return or.of(pr.EndText)},w3=function(n,e){return or.of(pr.SetFontAndSize,[YF(n),pn(e)])},Rde=function(n){return or.of(pr.SetTextLineHeight,[pn(n)])},eN;(function(n){n[n.Fill=0]="Fill",n[n.Outline=1]="Outline",n[n.FillAndOutline=2]="FillAndOutline",n[n.Invisible=3]="Invisible",n[n.FillAndClip=4]="FillAndClip",n[n.OutlineAndClip=5]="OutlineAndClip",n[n.FillAndOutlineAndClip=6]="FillAndOutlineAndClip",n[n.Clip=7]="Clip"})(eN||(eN={}));var Bde=function(n,e,t,r,i,o){return or.of(pr.SetTextMatrix,[pn(n),pn(e),pn(t),pn(r),pn(i),pn(o)])},zq=function(n,e,t,r,i){return Bde(lT(Mn(n)),dT(Mn(n))+cT(Mn(e)),-dT(Mn(n))+cT(Mn(t)),lT(Mn(n)),r,i)},S3=function(n){return or.of(pr.DrawObject,[YF(n)])},Ide=function(n){return or.of(pr.NonStrokingColorGray,[pn(n)])},Mde=function(n){return or.of(pr.StrokingColorGray,[pn(n)])},zde=function(n,e,t){return or.of(pr.NonStrokingColorRgb,[pn(n),pn(e),pn(t)])},Ode=function(n,e,t){return or.of(pr.StrokingColorRgb,[pn(n),pn(e),pn(t)])},Lde=function(n,e,t,r){return or.of(pr.NonStrokingColorCmyk,[pn(n),pn(e),pn(t),pn(r)])},Nde=function(n,e,t,r){return or.of(pr.StrokingColorCmyk,[pn(n),pn(e),pn(t),pn(r)])},Oq=function(n){return or.of(pr.BeginMarkedContent,[YF(n)])},Lq=function(){return or.of(pr.EndMarkedContent)},Og;(function(n){n.Grayscale="Grayscale",n.RGB="RGB",n.CMYK="CMYK"})(Og||(Og={}));var Nq=function(n){return Hl(n,"gray",0,1),{type:Og.Grayscale,gray:n}},zr=function(n,e,t){return Hl(n,"red",0,1),Hl(e,"green",0,1),Hl(t,"blue",0,1),{type:Og.RGB,red:n,green:e,blue:t}},Wq=function(n,e,t,r){return Hl(n,"cyan",0,1),Hl(e,"magenta",0,1),Hl(t,"yellow",0,1),Hl(r,"key",0,1),{type:Og.CMYK,cyan:n,magenta:e,yellow:t,key:r}},j3=Og.Grayscale,k3=Og.RGB,_3=Og.CMYK,L0=function(n){return n.type===j3?Ide(n.gray):n.type===k3?zde(n.red,n.green,n.blue):n.type===_3?Lde(n.cyan,n.magenta,n.yellow,n.key):eC("Invalid color: "+JSON.stringify(n))},lC=function(n){return n.type===j3?Mde(n.gray):n.type===k3?Ode(n.red,n.green,n.blue):n.type===_3?Nde(n.cyan,n.magenta,n.yellow,n.key):eC("Invalid color: "+JSON.stringify(n))},Aa=function(n,e){return e===void 0&&(e=1),(n==null?void 0:n.length)===1?Nq(n[0]*e):(n==null?void 0:n.length)===3?zr(n[0]*e,n[1]*e,n[2]*e):(n==null?void 0:n.length)===4?Wq(n[0]*e,n[1]*e,n[2]*e,n[3]*e):void 0},tN=function(n){return n.type===j3?[n.gray]:n.type===k3?[n.red,n.green,n.blue]:n.type===_3?[n.cyan,n.magenta,n.yellow,n.key]:eC("Invalid color: "+JSON.stringify(n))},$t=0,Zt=0,ir=0,sr=0,aS=0,lS=0,nN=new Map([["A",7],["a",7],["C",6],["c",6],["H",1],["h",1],["L",2],["l",2],["M",2],["m",2],["Q",4],["q",4],["S",4],["s",4],["T",2],["t",2],["V",1],["v",1],["Z",0],["z",0]]),Wde=function(n){for(var e,t=[],r=[],i="",o=!1,a=0,l=0,d=n;l<d.length;l++){var c=d[l];if(nN.has(c))a=nN.get(c),e&&(i.length>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;t<n.length;t++){var r=n[t];if(r.cmd&&typeof rN[r.cmd]=="function"){var i=rN[r.cmd](r.args);Array.isArray(i)?e=e.concat(i):e.push(i)}}return e},rN={M:function(n){return $t=n[0],Zt=n[1],ir=sr=null,aS=$t,lS=Zt,Ou($t,Zt)},m:function(n){return $t+=n[0],Zt+=n[1],ir=sr=null,aS=$t,lS=Zt,Ou($t,Zt)},C:function(n){return $t=n[4],Zt=n[5],ir=n[2],sr=n[3],ql(n[0],n[1],n[2],n[3],n[4],n[5])},c:function(n){var e=ql(n[0]+$t,n[1]+Zt,n[2]+$t,n[3]+Zt,n[4]+$t,n[5]+Zt);return ir=$t+n[2],sr=Zt+n[3],$t+=n[4],Zt+=n[5],e},S:function(n){(ir===null||sr===null)&&(ir=$t,sr=Zt);var e=ql($t-(ir-$t),Zt-(sr-Zt),n[0],n[1],n[2],n[3]);return ir=n[0],sr=n[1],$t=n[2],Zt=n[3],e},s:function(n){(ir===null||sr===null)&&(ir=$t,sr=Zt);var e=ql($t-(ir-$t),Zt-(sr-Zt),$t+n[0],Zt+n[1],$t+n[2],Zt+n[3]);return ir=$t+n[0],sr=Zt+n[1],$t+=n[2],Zt+=n[3],e},Q:function(n){return ir=n[0],sr=n[1],$t=n[2],Zt=n[3],N2(n[0],n[1],$t,Zt)},q:function(n){var e=N2(n[0]+$t,n[1]+Zt,n[2]+$t,n[3]+Zt);return ir=$t+n[0],sr=Zt+n[1],$t+=n[2],Zt+=n[3],e},T:function(n){ir===null||sr===null?(ir=$t,sr=Zt):(ir=$t-(ir-$t),sr=Zt-(sr-Zt));var e=N2(ir,sr,n[0],n[1]);return ir=$t-(ir-$t),sr=Zt-(sr-Zt),$t=n[0],Zt=n[1],e},t:function(n){ir===null||sr===null?(ir=$t,sr=Zt):(ir=$t-(ir-$t),sr=Zt-(sr-Zt));var e=N2(ir,sr,$t+n[0],Zt+n[1]);return $t+=n[0],Zt+=n[1],e},A:function(n){var e=iN($t,Zt,n);return $t=n[5],Zt=n[6],e},a:function(n){n[5]+=$t,n[6]+=Zt;var e=iN($t,Zt,n);return $t=n[5],Zt=n[6],e},L:function(n){return $t=n[0],Zt=n[1],ir=sr=null,ho($t,Zt)},l:function(n){return $t+=n[0],Zt+=n[1],ir=sr=null,ho($t,Zt)},H:function(n){return $t=n[0],ir=sr=null,ho($t,Zt)},h:function(n){return $t+=n[0],ir=sr=null,ho($t,Zt)},V:function(n){return Zt=n[0],ir=sr=null,ho($t,Zt)},v:function(n){return Zt+=n[0],ir=sr=null,ho($t,Zt)},Z:function(){var n=zg();return $t=aS,Zt=lS,n},z:function(){var n=zg();return $t=aS,Zt=lS,n}},iN=function(n,e,t){for(var r=t[0],i=t[1],o=t[2],a=t[3],l=t[4],d=t[5],c=t[6],u=Hde(d,c,r,i,a,l,o,n,e),f=[],p=0,g=u;p<g.length;p++){var m=g[p],y=qde.apply(void 0,m);f.push(ql.apply(void 0,y))}return f},Hde=function(n,e,t,r,i,o,a,l,d){var c=a*(Math.PI/180),u=Math.sin(c),f=Math.cos(c);t=Math.abs(t),r=Math.abs(r),ir=f*(l-n)*.5+u*(d-e)*.5,sr=f*(d-e)*.5-u*(l-n)*.5;var p=ir*ir/(t*t)+sr*sr/(r*r);p>1&&(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;U<W;U++){var M=D+U*L/W,I=D+(U+1)*L/W;O[U]=[F,A,M,I,t,r,u,f]}return O},qde=function(n,e,t,r,i,o,a,l){var d=l*i,c=-a*o,u=a*i,f=l*o,p=.5*(r-t),g=8/3*Math.sin(p*.5)*Math.sin(p*.5)/Math.sin(p),m=n+Math.cos(t)-g*Math.sin(t),y=e+Math.sin(t)+g*Math.cos(t),v=n+Math.cos(r),x=e+Math.sin(r),w=v+g*Math.sin(r),S=x-g*Math.cos(r),_=[d*m+c*y,u*m+f*y,d*w+c*S,u*w+f*S,d*v+c*x,u*v+f*x];return _},Vde=function(n){return Ude(Wde(n))},Gde=function(n,e){for(var t=[qs(),e.graphicsState&&O0(e.graphicsState),Iq(),L0(e.color),w3(e.font,e.size),Rde(e.lineHeight),zq(Mo(e.rotate),Mo(e.xSkew),Mo(e.ySkew),e.x,e.y)].filter(Boolean),r=0,i=n.length;r<i;r++)t.push(Bq(n[r]),Pde());return t.push(Mq(),Vs()),t},Uq=function(n,e){return[qs(),e.graphicsState&&O0(e.graphicsState),Rd(e.x,e.y),k1(Mo(e.rotate)),Vj(e.width,e.height),x3(Mo(e.xSkew),Mo(e.ySkew)),S3(n),Vs()].filter(Boolean)},Kde=function(n,e){return[qs(),e.graphicsState&&O0(e.graphicsState),Rd(e.x,e.y),k1(Mo(e.rotate)),Vj(e.xScale,e.yScale),x3(Mo(e.xSkew),Mo(e.ySkew)),S3(n),Vs()].filter(Boolean)},Xde=function(n){var e,t;return[qs(),n.graphicsState&&O0(n.graphicsState),n.color&&lC(n.color),oC(n.thickness),$F((e=n.dashArray)!==null&&e!==void 0?e:[],(t=n.dashPhase)!==null&&t!==void 0?t:0),Ou(n.start.x,n.start.y),n.lineCap&&ZF(n.lineCap),Ou(n.start.x,n.start.y),ho(n.end.x,n.end.y),aC(),Vs()].filter(Boolean)},l1=function(n){var e,t;return[qs(),n.graphicsState&&O0(n.graphicsState),n.color&&L0(n.color),n.borderColor&&lC(n.borderColor),oC(n.borderWidth),n.borderLineCap&&ZF(n.borderLineCap),$F((e=n.borderDashArray)!==null&&e!==void 0?e:[],(t=n.borderDashPhase)!==null&&t!==void 0?t:0),Rd(n.x,n.y),k1(Mo(n.rotate)),x3(Mo(n.xSkew),Mo(n.ySkew)),Ou(0,0),ho(0,n.height),ho(n.width,n.height),ho(n.width,0),zg(),n.color&&n.borderWidth?v3():n.color?b3():n.borderColor?aC():zg(),Vs()].filter(Boolean)},uT=4*((Math.sqrt(2)-1)/3),Yde=function(n){var e=Mn(n.x),t=Mn(n.y),r=Mn(n.xScale),i=Mn(n.yScale);e-=r,t-=i;var o=r*uT,a=i*uT,l=e+r*2,d=t+i*2,c=e+r,u=t+i;return[qs(),Ou(e,u),ql(e,u-a,c-o,t,c,t),ql(c+o,t,l,u-a,l,u),ql(l,u+a,c+o,d,c,d),ql(c-o,d,e,u+a,e,u),Vs()]},Qde=function(n){var e=Mn(n.x),t=Mn(n.y),r=Mn(n.xScale),i=Mn(n.yScale),o=-r,a=-i,l=r*uT,d=i*uT,c=o+r*2,u=a+i*2,f=o+r,p=a+i;return[Rd(e,t),k1(Mo(n.rotate)),Ou(o,p),ql(o,p-d,f-l,a,f,a),ql(f+l,a,c,p-d,c,p),ql(c,p+d,f+l,u,f,u),ql(f-l,u,o,p+d,o,p)]},UB=function(n){var e,t,r;return fr([qs(),n.graphicsState&&O0(n.graphicsState),n.color&&L0(n.color),n.borderColor&&lC(n.borderColor),oC(n.borderWidth),n.borderLineCap&&ZF(n.borderLineCap),$F((e=n.borderDashArray)!==null&&e!==void 0?e:[],(t=n.borderDashPhase)!==null&&t!==void 0?t:0)],n.rotate===void 0?Yde({x:n.x,y:n.y,xScale:n.xScale,yScale:n.yScale}):Qde({x:n.x,y:n.y,xScale:n.xScale,yScale:n.yScale,rotate:(r=n.rotate)!==null&&r!==void 0?r:cn(0)}),[n.color&&n.borderWidth?v3():n.color?b3():n.borderColor?aC():zg(),Vs()]).filter(Boolean)},$de=function(n,e){var t,r,i;return fr([qs(),e.graphicsState&&O0(e.graphicsState),Rd(e.x,e.y),k1(Mo((t=e.rotate)!==null&&t!==void 0?t:cn(0))),e.scale?Vj(e.scale,-e.scale):Vj(1,-1),e.color&&L0(e.color),e.borderColor&&lC(e.borderColor),e.borderWidth&&oC(e.borderWidth),e.borderLineCap&&ZF(e.borderLineCap),$F((r=e.borderDashArray)!==null&&r!==void 0?r:[],(i=e.borderDashPhase)!==null&&i!==void 0?i:0)],Vde(n),[e.color&&e.borderWidth?v3():e.color?b3():e.borderColor?aC():zg(),Vs()]).filter(Boolean)},Zde=function(n){var e=Mn(n.size),t=-1+.75,r=-1+.51,i=1-.525,o=1-.31,a=-1+.325,l=.3995/(i-r)+r;return[qs(),n.color&&lC(n.color),oC(n.thickness),Rd(n.x,n.y),Ou(a*e,l*e),ho(t*e,r*e),ho(o*e,i*e),aC(),Vs()].filter(Boolean)},Kg=function(n){return n.rotation===0?[Rd(0,0),L2(0)]:n.rotation===90?[Rd(n.width,0),L2(90)]:n.rotation===180?[Rd(n.width,n.height),L2(180)]:n.rotation===270?[Rd(0,n.height),L2(270)]:[]},W2=function(n){var e=l1({x:n.x,y:n.y,width:n.width,height:n.height,borderWidth:n.borderWidth,color:n.color,borderColor:n.borderColor,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)});if(!n.filled)return e;var t=Mn(n.width),r=Mn(n.height),i=Math.min(t,r)/2,o=Zde({x:t/2,y:r/2,size:i,thickness:n.thickness,color:n.markColor});return fr([qs()],e,o,[Vs()])},U2=function(n){var e=Mn(n.width),t=Mn(n.height),r=Math.min(e,t)/2,i=UB({x:n.x,y:n.y,xScale:r,yScale:r,color:n.color,borderColor:n.borderColor,borderWidth:n.borderWidth});if(!n.filled)return i;var o=UB({x:n.x,y:n.y,xScale:r*.45,yScale:r*.45,color:n.dotColor,borderColor:void 0,borderWidth:0});return fr([qs()],i,o,[Vs()])},sN=function(n){var e=Mn(n.x),t=Mn(n.y),r=Mn(n.width),i=Mn(n.height),o=l1({x:e,y:t,width:r,height:i,borderWidth:n.borderWidth,color:n.color,borderColor:n.borderColor,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)}),a=C3(n.textLines,{color:n.textColor,font:n.font,size:n.fontSize,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)});return fr([qs()],o,a,[Vs()])},C3=function(n,e){for(var t=[Iq(),L0(e.color),w3(e.font,e.size)],r=0,i=n.length;r<i;r++){var o=n[r],a=o.encoded,l=o.x,d=o.y;t.push(zq(Mo(e.rotate),Mo(e.xSkew),Mo(e.ySkew),l,d),Bq(a))}return t.push(Mq()),t},Hq=function(n){var e=Mn(n.x),t=Mn(n.y),r=Mn(n.width),i=Mn(n.height),o=Mn(n.borderWidth),a=Mn(n.padding),l=e+o/2+a,d=t+o/2+a,c=r-(o/2+a)*2,u=i-(o/2+a)*2,f=[Ou(l,d),ho(l,d+u),ho(l+c,d+u),ho(l+c,d),zg(),Pq(),Rq()],p=l1({x:e,y:t,width:r,height:i,borderWidth:n.borderWidth,color:n.color,borderColor:n.borderColor,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)}),g=C3(n.textLines,{color:n.textColor,font:n.font,size:n.fontSize,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)}),m=fr([Oq("Tx"),qs()],g,[Vs(),Lq()]);return fr([qs()],p,f,m,[Vs()])},Jde=function(n){for(var e=Mn(n.x),t=Mn(n.y),r=Mn(n.width),i=Mn(n.height),o=Mn(n.lineHeight),a=Mn(n.borderWidth),l=Mn(n.padding),d=e+a/2+l,c=t+a/2+l,u=r-(a/2+l)*2,f=i-(a/2+l)*2,p=[Ou(d,c),ho(d,c+f),ho(d+u,c+f),ho(d+u,c),zg(),Pq(),Rq()],g=l1({x:e,y:t,width:r,height:i,borderWidth:n.borderWidth,color:n.color,borderColor:n.borderColor,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)}),m=[],y=0,v=n.selectedLines.length;y<v;y++){var x=n.textLines[n.selectedLines[y]];m.push.apply(m,l1({x:x.x-l,y:x.y-(o-x.height)/2,width:r-a,height:x.height+(o-x.height)/2,borderWidth:0,color:n.selectedColor,borderColor:void 0,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)}))}var w=C3(n.textLines,{color:n.textColor,font:n.font,size:n.fontSize,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)}),S=fr([Oq("Tx"),qs()],w,[Vs(),Lq()]);return fr([qs()],g,m,p,S,[Vs()])},ece=function(n){xt(e,n);function e(){var t=this,r="Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.";return t=n.call(this,r)||this,t}return e}(Error),tce=function(n){xt(e,n);function e(){var t=this,r="Input to `PDFDocument.embedFont` was a custom font, but no `fontkit` instance was found. You must register a `fontkit` instance with `PDFDocument.registerFontkit(...)` before embedding custom fonts.";return t=n.call(this,r)||this,t}return e}(Error),nce=function(n){xt(e,n);function e(){var t=this,r="A `page` passed to `PDFDocument.addPage` or `PDFDocument.insertPage` was from a different (foreign) PDF document. If you want to copy pages from one PDFDocument to another, you must use `PDFDocument.copyPages(...)` to copy the pages before adding or inserting them.";return t=n.call(this,r)||this,t}return e}(Error),rce=function(n){xt(e,n);function e(){var t=this,r="PDFDocument has no pages so `PDFDocument.removePage` cannot be called";return t=n.call(this,r)||this,t}return e}(Error),ice=function(n){xt(e,n);function e(t){var r=this,i='PDFDocument has no form field with the name "'+t+'"';return r=n.call(this,i)||this,r}return e}(Error),rm=function(n){xt(e,n);function e(t,r,i){var o,a,l=this,d=r==null?void 0:r.name,c=(a=(o=i==null?void 0:i.constructor)===null||o===void 0?void 0:o.name)!==null&&a!==void 0?a:i,u='Expected field "'+t+'" to be of type '+d+", "+("but it is actually of type "+c);return l=n.call(this,u)||this,l}return e}(Error);(function(n){xt(e,n);function e(t){var r=this,i='Failed to select check box due to missing onValue: "'+t+'"';return r=n.call(this,i)||this,r}return e})(Error);var qq=function(n){xt(e,n);function e(t){var r=this,i='A field already exists with the specified name: "'+t+'"';return r=n.call(this,i)||this,r}return e}(Error),sce=function(n){xt(e,n);function e(t){var r=this,i='Field name contains invalid component: "'+t+'"';return r=n.call(this,i)||this,r}return e}(Error);(function(n){xt(e,n);function e(t){var r=this,i='A non-terminal field already exists with the specified name: "'+t+'"';return r=n.call(this,i)||this,r}return e})(Error);var oce=function(n){xt(e,n);function e(t){var r=this,i="Reading rich text fields is not supported: Attempted to read rich text field: "+t;return r=n.call(this,i)||this,r}return e}(Error),ace=function(n){xt(e,n);function e(t,r){var i=this,o="Failed to layout combed text as lineLength="+t+" is greater than cellCount="+r;return i=n.call(this,o)||this,i}return e}(Error),lce=function(n){xt(e,n);function e(t,r,i){var o=this,a="Attempted to set text with length="+t+" for TextField with maxLength="+r+" and name="+i;return o=n.call(this,a)||this,o}return e}(Error),dce=function(n){xt(e,n);function e(t,r,i){var o=this,a="Attempted to set maxLength="+r+", which is less than "+t+", the length of this field's current value (name="+i+")";return o=n.call(this,a)||this,o}return e}(Error),Os;(function(n){n[n.Left=0]="Left",n[n.Center=1]="Center",n[n.Right=2]="Right"})(Os||(Os={}));var Vq=4,Gq=500,Kq=function(n,e,t,r){r===void 0&&(r=!1);for(var i=Vq;i<Gq;){for(var o=0,a=0,l=n.length;a<l;a++){o+=1;for(var d=n[a],c=d.split(" "),u=t.width,f=0,p=c.length;f<p;f++){var g=f===p-1,m=g?c[f]:c[f]+" ",y=e.widthOfTextAtSize(m,i);u-=y,u<=0&&(o+=1,u=t.width-y)}}if(!r&&o>n.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);a<Gq;){for(var d=0,c=l.length;d<c;d++){var u=l[d],f=e.widthOfTextAtSize(u,a)>i*.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(d<e){var c=n.substring(o)||void 0;return{line:a,encoded:l,width:d,remainder:c}}o=(i=uce(a))!==null&&i!==void 0?i:0}return{line:n,encoded:t.encodeText(n),width:t.widthOfTextAtSize(n,r),remainder:void 0}},Xq=function(n,e){var t=e.alignment,r=e.fontSize,i=e.font,o=e.bounds,a=dH(J_(n));(r===void 0||r===0)&&(r=Kq(a,i,o,!0));for(var l=i.heightAtSize(r),d=l+l*.2,c=[],u=o.x,f=o.y,p=o.x+o.width,g=o.y+o.height,m=o.y+o.height,y=0,v=a.length;y<v;y++)for(var x=a[y];x!==void 0;){var w=hce(x,o.width,i,r),S=w.line,_=w.encoded,b=w.width,C=w.remainder,T=t===Os.Left?o.x:t===Os.Center?o.x+o.width/2-b/2:t===Os.Right?o.x+o.width-b:o.x;m-=d,T<u&&(u=T),m<f&&(f=m),T+b>p&&(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;y<o;){var x=uH(a,v),w=x[0],S=x[1],_=r.encodeText(w),b=r.widthOfTextAtSize(w,t),C=i.x+(l*y+l/2),T=C-b/2;T<f&&(f=T),c<p&&(p=c),T+b>g&&(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;F<A;F++)T+=b[F],F<A-1&&(T+=`
`);for(var D=1,P={x:p+D,y:p+D,width:y-(p+D)*2,height:v-(p+D)*2},L=Xq(T,{alignment:Os.Left,fontSize:l??d,font:t,bounds:P}),W=L.lines,O=L.fontSize,U=L.lineHeight,M=[],F=0,A=W.length;F<A;F++){var I=W[F];C.includes(I.text)&&M.push(F)}var H=zr(153/255,193/255,218/255),z=(i=o??a)!==null&&i!==void 0?i:w;return Ud(o||l!==void 0?e:n.acroField,z,t,O),fr(x,Jde({x:0+p/2,y:0+p/2,width:y-p,height:v-p,borderWidth:p??0,borderColor:S,textColor:z,font:t.name,fontSize:O,color:_,textLines:W,lineHeight:U,selectedColor:H,selectedLines:M,padding:D}))},Yq=function(){function n(e,t,r){this.alreadyEmbedded=!1,Ie(e,"ref",[[Mr,"PDFRef"]]),Ie(t,"doc",[[Af,"PDFDocument"]]),Ie(r,"embedder",[[vq,"PDFPageEmbedder"]]),this.ref=e,this.doc=t,this.width=r.width,this.height=r.height,this.embedder=r}return n.prototype.scale=function(e){return Ie(e,"factor",["number"]),{width:this.width*e,height:this.height*e}},n.prototype.size=function(){return this.scale(1)},n.prototype.embed=function(){return Pn(this,void 0,void 0,function(){return Rn(this,function(e){switch(e.label){case 0:return this.alreadyEmbedded?[3,2]:[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:e.sent(),this.alreadyEmbedded=!0,e.label=2;case 2:return[2]}})})},n.of=function(e,t,r){return new n(e,t,r)},n}(),Yl=function(){function n(e,t,r){this.modified=!0,Ie(e,"ref",[[Mr,"PDFRef"]]),Ie(t,"doc",[[Af,"PDFDocument"]]),Ie(r,"embedder",[[h3,"CustomFontEmbedder"],[iT,"StandardFontEmbedder"]]),this.ref=e,this.doc=t,this.name=r.fontName,this.embedder=r}return n.prototype.encodeText=function(e){return Ie(e,"text",["string"]),this.modified=!0,this.embedder.encodeText(e)},n.prototype.widthOfTextAtSize=function(e,t){return Ie(e,"text",["string"]),Ie(t,"size",["number"]),this.embedder.widthOfTextAtSize(e,t)},n.prototype.heightAtSize=function(e,t){var r;return Ie(e,"size",["number"]),mt(t==null?void 0:t.descender,"options.descender",["boolean"]),this.embedder.heightOfFontAtSize(e,{descender:(r=t==null?void 0:t.descender)!==null&&r!==void 0?r:!0})},n.prototype.sizeAtHeight=function(e){return Ie(e,"height",["number"]),this.embedder.sizeOfFontAtHeight(e)},n.prototype.getCharacterSet=function(){return this.embedder instanceof iT?this.embedder.encoding.supportedCodePoints:this.embedder.font.characterSet},n.prototype.embed=function(){return Pn(this,void 0,void 0,function(){return Rn(this,function(e){switch(e.label){case 0:return this.modified?[4,this.embedder.embedIntoContext(this.doc.context,this.ref)]:[3,2];case 1:e.sent(),this.modified=!1,e.label=2;case 2:return[2]}})})},n.of=function(e,t,r){return new n(e,t,r)},n}(),HB=function(){function n(e,t,r){Ie(e,"ref",[[Mr,"PDFRef"]]),Ie(t,"doc",[[Af,"PDFDocument"]]),Ie(r,"embedder",[[mq,"JpegEmbedder"],[yq,"PngEmbedder"]]),this.ref=e,this.doc=t,this.width=r.width,this.height=r.height,this.embedder=r}return n.prototype.scale=function(e){return Ie(e,"factor",["number"]),{width:this.width*e,height:this.height*e}},n.prototype.scaleToFit=function(e,t){Ie(e,"width",["number"]),Ie(t,"height",["number"]);var r=e/this.width,i=t/this.height,o=Math.min(r,i);return this.scale(o)},n.prototype.size=function(){return this.scale(1)},n.prototype.embed=function(){return Pn(this,void 0,void 0,function(){var e,t,r;return Rn(this,function(i){switch(i.label){case 0:return this.embedder?(this.embedTask||(e=this,t=e.doc,r=e.ref,this.embedTask=this.embedder.embedIntoContext(t.context,r)),[4,this.embedTask]):[2];case 1:return i.sent(),this.embedder=void 0,[2]}})})},n.of=function(e,t,r){return new n(e,t,r)},n}(),Pg;(function(n){n[n.Left=0]="Left",n[n.Center=1]="Center",n[n.Right=2]="Right"})(Pg||(Pg={}));var C1=function(n){mt(n==null?void 0:n.x,"options.x",["number"]),mt(n==null?void 0:n.y,"options.y",["number"]),mt(n==null?void 0:n.width,"options.width",["number"]),mt(n==null?void 0:n.height,"options.height",["number"]),mt(n==null?void 0:n.textColor,"options.textColor",[[Object,"Color"]]),mt(n==null?void 0:n.backgroundColor,"options.backgroundColor",[[Object,"Color"]]),mt(n==null?void 0:n.borderColor,"options.borderColor",[[Object,"Color"]]),mt(n==null?void 0:n.borderWidth,"options.borderWidth",["number"]),mt(n==null?void 0:n.rotate,"options.rotate",[[Object,"Rotation"]])},N0=function(){function n(e,t,r){Ie(e,"acroField",[[j1,"PDFAcroTerminal"]]),Ie(t,"ref",[[Mr,"PDFRef"]]),Ie(r,"doc",[[Af,"PDFDocument"]]),this.acroField=e,this.ref=t,this.doc=r}return n.prototype.getName=function(){var e;return(e=this.acroField.getFullyQualifiedName())!==null&&e!==void 0?e:""},n.prototype.isReadOnly=function(){return this.acroField.hasFlag(sc.ReadOnly)},n.prototype.enableReadOnly=function(){this.acroField.setFlagTo(sc.ReadOnly,!0)},n.prototype.disableReadOnly=function(){this.acroField.setFlagTo(sc.ReadOnly,!1)},n.prototype.isRequired=function(){return this.acroField.hasFlag(sc.Required)},n.prototype.enableRequired=function(){this.acroField.setFlagTo(sc.Required,!0)},n.prototype.disableRequired=function(){this.acroField.setFlagTo(sc.Required,!1)},n.prototype.isExported=function(){return!this.acroField.hasFlag(sc.NoExport)},n.prototype.enableExporting=function(){this.acroField.setFlagTo(sc.NoExport,!1)},n.prototype.disableExporting=function(){this.acroField.setFlagTo(sc.NoExport,!0)},n.prototype.needsAppearancesUpdate=function(){throw new Pd(this.constructor.name,"needsAppearancesUpdate")},n.prototype.defaultUpdateAppearances=function(e){throw new Pd(this.constructor.name,"defaultUpdateAppearances")},n.prototype.markAsDirty=function(){this.doc.getForm().markFieldAsDirty(this.ref)},n.prototype.markAsClean=function(){this.doc.getForm().markFieldAsClean(this.ref)},n.prototype.isDirty=function(){return this.doc.getForm().fieldIsDirty(this.ref)},n.prototype.createWidget=function(e){var t,r=e.textColor,i=e.backgroundColor,o=e.borderColor,a=e.borderWidth,l=Eq(e.rotate),d=e.caption,c=e.x,u=e.y,f=e.width+a,p=e.height+a,g=!!e.hidden,m=e.page;dq(l,"degreesAngle",90);var y=NB.create(this.doc.context,this.ref),v=Ede({x:c,y:u,width:f,height:p},a,l);y.setRectangle(v),m&&y.setP(m);var x=y.getOrCreateAppearanceCharacteristics();i&&x.setBackgroundColor(tN(i)),x.setRotation(l),d&&x.setCaptions({normal:d}),o&&x.setBorderColor(tN(o));var w=y.getOrCreateBorderStyle();if(a!==void 0&&w.setWidth(a),y.setFlagTo(nj.Print,!0),y.setFlagTo(nj.Hidden,g),y.setFlagTo(nj.Invisible,!1),r){var S=(t=this.acroField.getDefaultAppearance())!==null&&t!==void 0?t:"",_=S+`
`+L0(r).toString();this.acroField.setDefaultAppearance(_)}return y},n.prototype.updateWidgetAppearanceWithFont=function(e,t,r){var i=r.normal,o=r.rollover,a=r.down;this.updateWidgetAppearances(e,{normal:this.createAppearanceStream(e,i,t),rollover:o&&this.createAppearanceStream(e,o,t),down:a&&this.createAppearanceStream(e,a,t)})},n.prototype.updateOnOffWidgetAppearance=function(e,t,r){var i=r.normal,o=r.rollover,a=r.down;this.updateWidgetAppearances(e,{normal:this.createAppearanceDict(e,i,t),rollover:o&&this.createAppearanceDict(e,o,t),down:a&&this.createAppearanceDict(e,a,t)})},n.prototype.updateWidgetAppearances=function(e,t){var r=t.normal,i=t.rollover,o=t.down;e.setNormalAppearance(r),i?e.setRolloverAppearance(i):e.removeRolloverAppearance(),o?e.setDownAppearance(o):e.removeDownAppearance()},n.prototype.createAppearanceStream=function(e,t,r){var i,o=this.acroField.dict.context,a=e.getRectangle(),l=a.width,d=a.height,c=r&&{Font:(i={},i[r.name]=r.ref,i)},u=o.formXObject(t,{Resources:c,BBox:o.obj([0,0,l,d]),Matrix:o.obj([1,0,0,1,0,0])}),f=o.register(u);return f},n.prototype.createImageAppearanceStream=function(e,t,r){var i,o,a=this.acroField.dict.context,l=e.getRectangle(),d=e.getAppearanceCharacteristics(),c=e.getBorderStyle(),u=(o=c==null?void 0:c.getWidth())!==null&&o!==void 0?o:0,f=If(d==null?void 0:d.getRotation()),p=Kg(wn(wn({},l),{rotation:f})),g=z0(l,f),m=t.scaleToFit(g.width-u*2,g.height-u*2),y={x:u,y:u,width:m.width,height:m.height,rotate:cn(0),xSkew:cn(0),ySkew:cn(0)};r===Pg.Center?(y.x+=(g.width-u*2)/2-m.width/2,y.y+=(g.height-u*2)/2-m.height/2):r===Pg.Right&&(y.x=g.width-u-m.width,y.y=g.height-u-m.height);var v=this.doc.context.addRandomSuffix("Image",10),x=fr(p,Uq(v,y)),w={XObject:(i={},i[v]=t.ref,i)},S=a.formXObject(x,{Resources:w,BBox:a.obj([0,0,l.width,l.height]),Matrix:a.obj([1,0,0,1,0,0])});return a.register(S)},n.prototype.createAppearanceDict=function(e,t,r){var i=this.acroField.dict.context,o=this.createAppearanceStream(e,t.on),a=this.createAppearanceStream(e,t.off),l=i.obj({});return l.set(r,o),l.set(se.of("Off"),a),l},n}(),dS=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroCheckBox",[[WF,"PDFAcroCheckBox"]]),o.acroField=t,o}return e.prototype.check=function(){var t,r=(t=this.acroField.getOnValue())!==null&&t!==void 0?t:se.of("Yes");this.markAsDirty(),this.acroField.setValue(r)},e.prototype.uncheck=function(){this.markAsDirty(),this.acroField.setValue(se.of("Off"))},e.prototype.isChecked=function(){var t=this.acroField.getOnValue();return!!t&&t===this.acroField.getValue()},e.prototype.addToPage=function(t,r){var i,o,a,l,d,c;Ie(t,"page",[[Ad,"PDFPage"]]),C1(r),r||(r={}),"textColor"in r||(r.textColor=zr(0,0,0)),"backgroundColor"in r||(r.backgroundColor=zr(1,1,1)),"borderColor"in r||(r.borderColor=zr(0,0,0)),"borderWidth"in r||(r.borderWidth=1);var u=this.createWidget({x:(i=r.x)!==null&&i!==void 0?i:0,y:(o=r.y)!==null&&o!==void 0?o:0,width:(a=r.width)!==null&&a!==void 0?a:50,height:(l=r.height)!==null&&l!==void 0?l:50,textColor:r.textColor,backgroundColor:r.backgroundColor,borderColor:r.borderColor,borderWidth:(d=r.borderWidth)!==null&&d!==void 0?d:0,rotate:(c=r.rotate)!==null&&c!==void 0?c:cn(0),hidden:r.hidden,page:t.ref}),f=this.doc.context.register(u.dict);this.acroField.addWidget(f),u.setAppearanceState(se.of("Off")),this.updateWidgetAppearance(u,se.of("Yes")),t.node.addAnnot(f)},e.prototype.needsAppearancesUpdate=function(){for(var t,r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=a.getAppearanceState(),d=(t=a.getAppearances())===null||t===void 0?void 0:t.normal;if(!(d instanceof _n)||l&&!d.has(l))return!0}return!1},e.prototype.defaultUpdateAppearances=function(){this.updateAppearances()},e.prototype.updateAppearances=function(t){var r;mt(t,"provider",[Function]);for(var i=this.acroField.getWidgets(),o=0,a=i.length;o<a;o++){var l=i[o],d=(r=l.getOnValue())!==null&&r!==void 0?r:se.of("Yes");d&&this.updateWidgetAppearance(l,d,t)}this.markAsClean()},e.prototype.updateWidgetAppearance=function(t,r,i){var o=i??mce,a=_1(o(this,t));this.updateOnOffWidgetAppearance(t,r,a)},e.of=function(t,r,i){return new e(t,r,i)},e}(N0),C5=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroComboBox",[[UF,"PDFAcroComboBox"]]),o.acroField=t,o}return e.prototype.getOptions=function(){for(var t=this.acroField.getOptions(),r=new Array(t.length),i=0,o=r.length;i<o;i++){var a=t[i],l=a.display,d=a.value;r[i]=(l??d).decodeText()}return r},e.prototype.getSelected=function(){for(var t=this.acroField.getValues(),r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]=t[i].decodeText();return r},e.prototype.setOptions=function(t){Ie(t,"options",[Array]);for(var r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]={value:dn.fromText(t[i])};this.acroField.setOptions(r)},e.prototype.addOptions=function(t){Ie(t,"options",["string",Array]);for(var r=Array.isArray(t)?t:[t],i=this.acroField.getOptions(),o=new Array(r.length),a=0,l=r.length;a<l;a++)o[a]={value:dn.fromText(r[a])};this.acroField.setOptions(i.concat(o))},e.prototype.select=function(t,r){r===void 0&&(r=!1),Ie(t,"options",["string",Array]),Ie(r,"merge",["boolean"]);var i=Array.isArray(t)?t:[t],o=this.getOptions(),a=i.find(function(f){return!o.includes(f)});a&&this.enableEditing(),this.markAsDirty(),(i.length>1||i.length===1&&r)&&this.enableMultiselect();for(var l=new Array(i.length),d=0,c=i.length;d<c;d++)l[d]=dn.fromText(i[d]);if(r){var u=this.acroField.getValues();this.acroField.setValues(u.concat(l))}else this.acroField.setValues(l)},e.prototype.clear=function(){this.markAsDirty(),this.acroField.setValues([])},e.prototype.setFontSize=function(t){LF(t,"fontSize"),this.acroField.setFontSize(t),this.markAsDirty()},e.prototype.isEditable=function(){return this.acroField.hasFlag(Br.Edit)},e.prototype.enableEditing=function(){this.acroField.setFlagTo(Br.Edit,!0)},e.prototype.disableEditing=function(){this.acroField.setFlagTo(Br.Edit,!1)},e.prototype.isSorted=function(){return this.acroField.hasFlag(Br.Sort)},e.prototype.enableSorting=function(){this.acroField.setFlagTo(Br.Sort,!0)},e.prototype.disableSorting=function(){this.acroField.setFlagTo(Br.Sort,!1)},e.prototype.isMultiselect=function(){return this.acroField.hasFlag(Br.MultiSelect)},e.prototype.enableMultiselect=function(){this.acroField.setFlagTo(Br.MultiSelect,!0)},e.prototype.disableMultiselect=function(){this.acroField.setFlagTo(Br.MultiSelect,!1)},e.prototype.isSpellChecked=function(){return!this.acroField.hasFlag(Br.DoNotSpellCheck)},e.prototype.enableSpellChecking=function(){this.acroField.setFlagTo(Br.DoNotSpellCheck,!1)},e.prototype.disableSpellChecking=function(){this.acroField.setFlagTo(Br.DoNotSpellCheck,!0)},e.prototype.isSelectOnClick=function(){return this.acroField.hasFlag(Br.CommitOnSelChange)},e.prototype.enableSelectOnClick=function(){this.acroField.setFlagTo(Br.CommitOnSelChange,!0)},e.prototype.disableSelectOnClick=function(){this.acroField.setFlagTo(Br.CommitOnSelChange,!1)},e.prototype.addToPage=function(t,r){var i,o,a,l,d,c,u;Ie(t,"page",[[Ad,"PDFPage"]]),C1(r),r||(r={}),"textColor"in r||(r.textColor=zr(0,0,0)),"backgroundColor"in r||(r.backgroundColor=zr(1,1,1)),"borderColor"in r||(r.borderColor=zr(0,0,0)),"borderWidth"in r||(r.borderWidth=1);var f=this.createWidget({x:(i=r.x)!==null&&i!==void 0?i:0,y:(o=r.y)!==null&&o!==void 0?o:0,width:(a=r.width)!==null&&a!==void 0?a:200,height:(l=r.height)!==null&&l!==void 0?l:50,textColor:r.textColor,backgroundColor:r.backgroundColor,borderColor:r.borderColor,borderWidth:(d=r.borderWidth)!==null&&d!==void 0?d:0,rotate:(c=r.rotate)!==null&&c!==void 0?c:cn(0),hidden:r.hidden,page:t.ref}),p=this.doc.context.register(f.dict);this.acroField.addWidget(p);var g=(u=r.font)!==null&&u!==void 0?u:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(f,g),t.node.addAnnot(p)},e.prototype.needsAppearancesUpdate=function(){var t;if(this.isDirty())return!0;for(var r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=((t=a.getAppearances())===null||t===void 0?void 0:t.normal)instanceof Gl;if(!l)return!0}return!1},e.prototype.defaultUpdateAppearances=function(t){Ie(t,"font",[[Yl,"PDFFont"]]),this.updateAppearances(t)},e.prototype.updateAppearances=function(t,r){Ie(t,"font",[[Yl,"PDFFont"]]),mt(r,"provider",[Function]);for(var i=this.acroField.getWidgets(),o=0,a=i.length;o<a;o++){var l=i[o];this.updateWidgetAppearance(l,t,r)}this.markAsClean()},e.prototype.updateWidgetAppearance=function(t,r,i){var o=i??vce,a=_1(o(this,t,r));this.updateWidgetAppearanceWithFont(t,r,a)},e.of=function(t,r,i){return new e(t,r,i)},e}(N0),A5=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroListBox",[[GF,"PDFAcroListBox"]]),o.acroField=t,o}return e.prototype.getOptions=function(){for(var t=this.acroField.getOptions(),r=new Array(t.length),i=0,o=r.length;i<o;i++){var a=t[i],l=a.display,d=a.value;r[i]=(l??d).decodeText()}return r},e.prototype.getSelected=function(){for(var t=this.acroField.getValues(),r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]=t[i].decodeText();return r},e.prototype.setOptions=function(t){Ie(t,"options",[Array]),this.markAsDirty();for(var r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]={value:dn.fromText(t[i])};this.acroField.setOptions(r)},e.prototype.addOptions=function(t){Ie(t,"options",["string",Array]),this.markAsDirty();for(var r=Array.isArray(t)?t:[t],i=this.acroField.getOptions(),o=new Array(r.length),a=0,l=r.length;a<l;a++)o[a]={value:dn.fromText(r[a])};this.acroField.setOptions(i.concat(o))},e.prototype.select=function(t,r){r===void 0&&(r=!1),Ie(t,"options",["string",Array]),Ie(r,"merge",["boolean"]);var i=Array.isArray(t)?t:[t],o=this.getOptions();ble(i,"option",o),this.markAsDirty(),(i.length>1||i.length===1&&r)&&this.enableMultiselect();for(var a=new Array(i.length),l=0,d=i.length;l<d;l++)a[l]=dn.fromText(i[l]);if(r){var c=this.acroField.getValues();this.acroField.setValues(c.concat(a))}else this.acroField.setValues(a)},e.prototype.clear=function(){this.markAsDirty(),this.acroField.setValues([])},e.prototype.setFontSize=function(t){LF(t,"fontSize"),this.acroField.setFontSize(t),this.markAsDirty()},e.prototype.isSorted=function(){return this.acroField.hasFlag(Br.Sort)},e.prototype.enableSorting=function(){this.acroField.setFlagTo(Br.Sort,!0)},e.prototype.disableSorting=function(){this.acroField.setFlagTo(Br.Sort,!1)},e.prototype.isMultiselect=function(){return this.acroField.hasFlag(Br.MultiSelect)},e.prototype.enableMultiselect=function(){this.acroField.setFlagTo(Br.MultiSelect,!0)},e.prototype.disableMultiselect=function(){this.acroField.setFlagTo(Br.MultiSelect,!1)},e.prototype.isSelectOnClick=function(){return this.acroField.hasFlag(Br.CommitOnSelChange)},e.prototype.enableSelectOnClick=function(){this.acroField.setFlagTo(Br.CommitOnSelChange,!0)},e.prototype.disableSelectOnClick=function(){this.acroField.setFlagTo(Br.CommitOnSelChange,!1)},e.prototype.addToPage=function(t,r){var i,o,a,l,d,c,u;Ie(t,"page",[[Ad,"PDFPage"]]),C1(r),r||(r={}),"textColor"in r||(r.textColor=zr(0,0,0)),"backgroundColor"in r||(r.backgroundColor=zr(1,1,1)),"borderColor"in r||(r.borderColor=zr(0,0,0)),"borderWidth"in r||(r.borderWidth=1);var f=this.createWidget({x:(i=r.x)!==null&&i!==void 0?i:0,y:(o=r.y)!==null&&o!==void 0?o:0,width:(a=r.width)!==null&&a!==void 0?a:200,height:(l=r.height)!==null&&l!==void 0?l:100,textColor:r.textColor,backgroundColor:r.backgroundColor,borderColor:r.borderColor,borderWidth:(d=r.borderWidth)!==null&&d!==void 0?d:0,rotate:(c=r.rotate)!==null&&c!==void 0?c:cn(0),hidden:r.hidden,page:t.ref}),p=this.doc.context.register(f.dict);this.acroField.addWidget(p);var g=(u=r.font)!==null&&u!==void 0?u:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(f,g),t.node.addAnnot(p)},e.prototype.needsAppearancesUpdate=function(){var t;if(this.isDirty())return!0;for(var r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=((t=a.getAppearances())===null||t===void 0?void 0:t.normal)instanceof Gl;if(!l)return!0}return!1},e.prototype.defaultUpdateAppearances=function(t){Ie(t,"font",[[Yl,"PDFFont"]]),this.updateAppearances(t)},e.prototype.updateAppearances=function(t,r){Ie(t,"font",[[Yl,"PDFFont"]]),mt(r,"provider",[Function]);for(var i=this.acroField.getWidgets(),o=0,a=i.length;o<a;o++){var l=i[o];this.updateWidgetAppearance(l,t,r)}this.markAsClean()},e.prototype.updateWidgetAppearance=function(t,r,i){var o=i??wce,a=_1(o(this,t,r));this.updateWidgetAppearanceWithFont(t,r,a)},e.of=function(t,r,i){return new e(t,r,i)},e}(N0),cS=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroRadioButton",[[VF,"PDFAcroRadioButton"]]),o.acroField=t,o}return e.prototype.getOptions=function(){var t=this.acroField.getExportValues();if(t){for(var r=new Array(t.length),i=0,o=t.length;i<o;i++)r[i]=t[i].decodeText();return r}for(var a=this.acroField.getOnValues(),l=new Array(a.length),i=0,o=l.length;i<o;i++)l[i]=a[i].decodeText();return l},e.prototype.getSelected=function(){var t=this.acroField.getValue();if(t!==se.of("Off")){var r=this.acroField.getExportValues();if(r){for(var i=this.acroField.getOnValues(),o=0,a=i.length;o<a;o++)if(i[o]===t)return r[o].decodeText()}return t.decodeText()}},e.prototype.select=function(t){Ie(t,"option",["string"]);var r=this.getOptions();yg(t,"option",r),this.markAsDirty();var i=this.acroField.getOnValues(),o=this.acroField.getExportValues();if(o)for(var a=0,l=o.length;a<l;a++)o[a].decodeText()===t&&this.acroField.setValue(i[a]);else for(var a=0,l=i.length;a<l;a++){var d=i[a];d.decodeText()===t&&this.acroField.setValue(d)}},e.prototype.clear=function(){this.markAsDirty(),this.acroField.setValue(se.of("Off"))},e.prototype.isOffToggleable=function(){return!this.acroField.hasFlag(Cd.NoToggleToOff)},e.prototype.enableOffToggling=function(){this.acroField.setFlagTo(Cd.NoToggleToOff,!1)},e.prototype.disableOffToggling=function(){this.acroField.setFlagTo(Cd.NoToggleToOff,!0)},e.prototype.isMutuallyExclusive=function(){return!this.acroField.hasFlag(Cd.RadiosInUnison)},e.prototype.enableMutualExclusion=function(){this.acroField.setFlagTo(Cd.RadiosInUnison,!1)},e.prototype.disableMutualExclusion=function(){this.acroField.setFlagTo(Cd.RadiosInUnison,!0)},e.prototype.addOptionToPage=function(t,r,i){var o,a,l,d,c,u,f,p,g;Ie(t,"option",["string"]),Ie(r,"page",[[Ad,"PDFPage"]]),C1(i);var m=this.createWidget({x:(o=i==null?void 0:i.x)!==null&&o!==void 0?o:0,y:(a=i==null?void 0:i.y)!==null&&a!==void 0?a:0,width:(l=i==null?void 0:i.width)!==null&&l!==void 0?l:50,height:(d=i==null?void 0:i.height)!==null&&d!==void 0?d:50,textColor:(c=i==null?void 0:i.textColor)!==null&&c!==void 0?c:zr(0,0,0),backgroundColor:(u=i==null?void 0:i.backgroundColor)!==null&&u!==void 0?u:zr(1,1,1),borderColor:(f=i==null?void 0:i.borderColor)!==null&&f!==void 0?f:zr(0,0,0),borderWidth:(p=i==null?void 0:i.borderWidth)!==null&&p!==void 0?p:1,rotate:(g=i==null?void 0:i.rotate)!==null&&g!==void 0?g:cn(0),hidden:i==null?void 0:i.hidden,page:r.ref}),y=this.doc.context.register(m.dict),v=this.acroField.addWidgetWithOpt(y,dn.fromText(t),!this.isMutuallyExclusive());m.setAppearanceState(se.of("Off")),this.updateWidgetAppearance(m,v),r.node.addAnnot(y)},e.prototype.needsAppearancesUpdate=function(){for(var t,r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=a.getAppearanceState(),d=(t=a.getAppearances())===null||t===void 0?void 0:t.normal;if(!(d instanceof _n)||l&&!d.has(l))return!0}return!1},e.prototype.defaultUpdateAppearances=function(){this.updateAppearances()},e.prototype.updateAppearances=function(t){mt(t,"provider",[Function]);for(var r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=a.getOnValue();l&&this.updateWidgetAppearance(a,l,t)}},e.prototype.updateWidgetAppearance=function(t,r,i){var o=i??yce,a=_1(o(this,t));this.updateOnOffWidgetAppearance(t,r,a)},e.of=function(t,r,i){return new e(t,r,i)},e}(N0),qB=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroSignature",[[p3,"PDFAcroSignature"]]),o.acroField=t,o}return e.prototype.needsAppearancesUpdate=function(){return!1},e.of=function(t,r,i){return new e(t,r,i)},e}(N0),T5=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroText",[[HF,"PDFAcroText"]]),o.acroField=t,o}return e.prototype.getText=function(){var t=this.acroField.getValue();if(!t&&this.isRichFormatted())throw new oce(this.getName());return t==null?void 0:t.decodeText()},e.prototype.setText=function(t){mt(t,"text",["string"]);var r=this.getMaxLength();if(r!==void 0&&t&&t.length>r)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;a<l;a++){var d=o[a],c=this.createImageAppearanceStream(d,t,i);this.updateWidgetAppearances(d,{normal:c})}this.markAsClean()},e.prototype.setFontSize=function(t){LF(t,"fontSize"),this.acroField.setFontSize(t),this.markAsDirty()},e.prototype.isMultiline=function(){return this.acroField.hasFlag(Ki.Multiline)},e.prototype.enableMultiline=function(){this.markAsDirty(),this.acroField.setFlagTo(Ki.Multiline,!0)},e.prototype.disableMultiline=function(){this.markAsDirty(),this.acroField.setFlagTo(Ki.Multiline,!1)},e.prototype.isPassword=function(){return this.acroField.hasFlag(Ki.Password)},e.prototype.enablePassword=function(){this.acroField.setFlagTo(Ki.Password,!0)},e.prototype.disablePassword=function(){this.acroField.setFlagTo(Ki.Password,!1)},e.prototype.isFileSelector=function(){return this.acroField.hasFlag(Ki.FileSelect)},e.prototype.enableFileSelection=function(){this.acroField.setFlagTo(Ki.FileSelect,!0)},e.prototype.disableFileSelection=function(){this.acroField.setFlagTo(Ki.FileSelect,!1)},e.prototype.isSpellChecked=function(){return!this.acroField.hasFlag(Ki.DoNotSpellCheck)},e.prototype.enableSpellChecking=function(){this.acroField.setFlagTo(Ki.DoNotSpellCheck,!1)},e.prototype.disableSpellChecking=function(){this.acroField.setFlagTo(Ki.DoNotSpellCheck,!0)},e.prototype.isScrollable=function(){return!this.acroField.hasFlag(Ki.DoNotScroll)},e.prototype.enableScrolling=function(){this.acroField.setFlagTo(Ki.DoNotScroll,!1)},e.prototype.disableScrolling=function(){this.acroField.setFlagTo(Ki.DoNotScroll,!0)},e.prototype.isCombed=function(){return this.acroField.hasFlag(Ki.Comb)&&!this.isMultiline()&&!this.isPassword()&&!this.isFileSelector()&&this.getMaxLength()!==void 0},e.prototype.enableCombing=function(){if(this.getMaxLength()===void 0){var t="PDFTextFields must have a max length in order to be combed";console.warn(t)}this.markAsDirty(),this.disableMultiline(),this.disablePassword(),this.disableFileSelection(),this.acroField.setFlagTo(Ki.Comb,!0)},e.prototype.disableCombing=function(){this.markAsDirty(),this.acroField.setFlagTo(Ki.Comb,!1)},e.prototype.isRichFormatted=function(){return this.acroField.hasFlag(Ki.RichText)},e.prototype.enableRichFormatting=function(){this.acroField.setFlagTo(Ki.RichText,!0)},e.prototype.disableRichFormatting=function(){this.acroField.setFlagTo(Ki.RichText,!1)},e.prototype.addToPage=function(t,r){var i,o,a,l,d,c,u;Ie(t,"page",[[Ad,"PDFPage"]]),C1(r),r||(r={}),"textColor"in r||(r.textColor=zr(0,0,0)),"backgroundColor"in r||(r.backgroundColor=zr(1,1,1)),"borderColor"in r||(r.borderColor=zr(0,0,0)),"borderWidth"in r||(r.borderWidth=1);var f=this.createWidget({x:(i=r.x)!==null&&i!==void 0?i:0,y:(o=r.y)!==null&&o!==void 0?o:0,width:(a=r.width)!==null&&a!==void 0?a:200,height:(l=r.height)!==null&&l!==void 0?l:50,textColor:r.textColor,backgroundColor:r.backgroundColor,borderColor:r.borderColor,borderWidth:(d=r.borderWidth)!==null&&d!==void 0?d:0,rotate:(c=r.rotate)!==null&&c!==void 0?c:cn(0),hidden:r.hidden,page:t.ref}),p=this.doc.context.register(f.dict);this.acroField.addWidget(p);var g=(u=r.font)!==null&&u!==void 0?u:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(f,g),t.node.addAnnot(p)},e.prototype.needsAppearancesUpdate=function(){var t;if(this.isDirty())return!0;for(var r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=((t=a.getAppearances())===null||t===void 0?void 0:t.normal)instanceof Gl;if(!l)return!0}return!1},e.prototype.defaultUpdateAppearances=function(t){Ie(t,"font",[[Yl,"PDFFont"]]),this.updateAppearances(t)},e.prototype.updateAppearances=function(t,r){Ie(t,"font",[[Yl,"PDFFont"]]),mt(r,"provider",[Function]);for(var i=this.acroField.getWidgets(),o=0,a=i.length;o<a;o++){var l=i[o];this.updateWidgetAppearance(l,t,r)}this.markAsClean()},e.prototype.updateWidgetAppearance=function(t,r,i){var o=i??bce,a=_1(o(this,t,r));this.updateWidgetAppearanceWithFont(t,r,a)},e.of=function(t,r,i){return new e(t,r,i)},e}(N0),fT;(function(n){n.Courier="Courier",n.CourierBold="Courier-Bold",n.CourierOblique="Courier-Oblique",n.CourierBoldOblique="Courier-BoldOblique",n.Helvetica="Helvetica",n.HelveticaBold="Helvetica-Bold",n.HelveticaOblique="Helvetica-Oblique",n.HelveticaBoldOblique="Helvetica-BoldOblique",n.TimesRoman="Times-Roman",n.TimesRomanBold="Times-Bold",n.TimesRomanItalic="Times-Italic",n.TimesRomanBoldItalic="Times-BoldItalic",n.Symbol="Symbol",n.ZapfDingbats="ZapfDingbats"})(fT||(fT={}));var Sce=function(){function n(e,t){var r=this;this.embedDefaultFont=function(){return r.doc.embedStandardFont(fT.Helvetica)},Ie(e,"acroForm",[[aT,"PDFAcroForm"]]),Ie(t,"doc",[[Af,"PDFDocument"]]),this.acroForm=e,this.doc=t,this.dirtyFields=new Set,this.defaultFontCache=mf.populatedBy(this.embedDefaultFont)}return n.prototype.hasXFA=function(){return this.acroForm.dict.has(se.of("XFA"))},n.prototype.deleteXFA=function(){this.acroForm.dict.delete(se.of("XFA"))},n.prototype.getFields=function(){for(var e=this.acroForm.getAllFields(),t=[],r=0,i=e.length;r<i;r++){var o=e[r],a=o[0],l=o[1],d=jce(a,l,this.doc);d&&t.push(d)}return t},n.prototype.getFieldMaybe=function(e){Ie(e,"name",["string"]);for(var t=this.getFields(),r=0,i=t.length;r<i;r++){var o=t[r];if(o.getName()===e)return o}},n.prototype.getField=function(e){Ie(e,"name",["string"]);var t=this.getFieldMaybe(e);if(t)return t;throw new ice(e)},n.prototype.getButton=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof F5)return t;throw new rm(e,F5,t)},n.prototype.getCheckBox=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof dS)return t;throw new rm(e,dS,t)},n.prototype.getDropdown=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof C5)return t;throw new rm(e,C5,t)},n.prototype.getOptionList=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof A5)return t;throw new rm(e,A5,t)},n.prototype.getRadioGroup=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof cS)return t;throw new rm(e,cS,t)},n.prototype.getSignature=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof qB)return t;throw new rm(e,qB,t)},n.prototype.getTextField=function(e){Ie(e,"name",["string"]);var t=this.getField(e);if(t instanceof T5)return t;throw new rm(e,T5,t)},n.prototype.createButton=function(e){Ie(e,"name",["string"]);var t=gx(e),r=this.findOrCreateNonTerminals(t.nonTerminal),i=qF.create(this.doc.context);return i.setPartialName(t.terminal),mx(r,[i,i.ref],t.terminal),F5.of(i,i.ref,this.doc)},n.prototype.createCheckBox=function(e){Ie(e,"name",["string"]);var t=gx(e),r=this.findOrCreateNonTerminals(t.nonTerminal),i=WF.create(this.doc.context);return i.setPartialName(t.terminal),mx(r,[i,i.ref],t.terminal),dS.of(i,i.ref,this.doc)},n.prototype.createDropdown=function(e){Ie(e,"name",["string"]);var t=gx(e),r=this.findOrCreateNonTerminals(t.nonTerminal),i=UF.create(this.doc.context);return i.setPartialName(t.terminal),mx(r,[i,i.ref],t.terminal),C5.of(i,i.ref,this.doc)},n.prototype.createOptionList=function(e){Ie(e,"name",["string"]);var t=gx(e),r=this.findOrCreateNonTerminals(t.nonTerminal),i=GF.create(this.doc.context);return i.setPartialName(t.terminal),mx(r,[i,i.ref],t.terminal),A5.of(i,i.ref,this.doc)},n.prototype.createRadioGroup=function(e){Ie(e,"name",["string"]);var t=gx(e),r=this.findOrCreateNonTerminals(t.nonTerminal),i=VF.create(this.doc.context);return i.setPartialName(t.terminal),mx(r,[i,i.ref],t.terminal),cS.of(i,i.ref,this.doc)},n.prototype.createTextField=function(e){Ie(e,"name",["string"]);var t=gx(e),r=this.findOrCreateNonTerminals(t.nonTerminal),i=HF.create(this.doc.context);return i.setPartialName(t.terminal),mx(r,[i,i.ref],t.terminal),T5.of(i,i.ref,this.doc)},n.prototype.flatten=function(e){e===void 0&&(e={updateFieldAppearances:!0}),e.updateFieldAppearances&&this.updateFieldAppearances();for(var t=this.getFields(),r=0,i=t.length;r<i;r++){for(var o=t[r],a=o.acroField.getWidgets(),l=0,d=a.length;l<d;l++){var c=a[l],u=this.findWidgetPage(c),f=this.findWidgetAppearanceRef(o,c),p=u.node.newXObject("FlatWidget",f),g=c.getRectangle(),m=fr([qs(),Rd(g.x,g.y)],Kg(wn(wn({},g),{rotation:0})),[S3(p),Vs()]).filter(Boolean);u.pushOperators.apply(u,m)}this.removeField(o)}},n.prototype.removeField=function(e){for(var t=e.acroField.getWidgets(),r=new Set,i=0,o=t.length;i<o;i++){var a=t[i],l=this.findWidgetAppearanceRef(e,a),d=this.findWidgetPage(a);r.add(d),d.node.removeAnnot(l)}r.forEach(function(g){return g.node.removeAnnot(e.ref)}),this.acroForm.removeField(e.acroField);for(var c=e.acroField.normalizedEntries().Kids,u=c.size(),f=0;f<u;f++){var p=c.get(f);p instanceof Mr&&this.doc.context.delete(p)}this.doc.context.delete(e.ref)},n.prototype.updateFieldAppearances=function(e){mt(e,"font",[[Yl,"PDFFont"]]),e=e??this.getDefaultFont();for(var t=this.getFields(),r=0,i=t.length;r<i;r++){var o=t[r];o.needsAppearancesUpdate()&&o.defaultUpdateAppearances(e)}},n.prototype.markFieldAsDirty=function(e){mt(e,"fieldRef",[[Mr,"PDFRef"]]),this.dirtyFields.add(e)},n.prototype.markFieldAsClean=function(e){mt(e,"fieldRef",[[Mr,"PDFRef"]]),this.dirtyFields.delete(e)},n.prototype.fieldIsDirty=function(e){return mt(e,"fieldRef",[[Mr,"PDFRef"]]),this.dirtyFields.has(e)},n.prototype.getDefaultFont=function(){return this.defaultFontCache.access()},n.prototype.findWidgetPage=function(e){var t=e.P(),r=this.doc.getPages().find(function(o){return o.ref===t});if(r===void 0){var i=this.doc.context.getObjectRef(e.dict);if(i===void 0)throw new Error("Could not find PDFRef for PDFObject");if(r=this.doc.findPageForAnnotationRef(i),r===void 0)throw new Error("Could not find page for PDFRef "+i)}return r},n.prototype.findWidgetAppearanceRef=function(e,t){var r,i=t.getNormalAppearance();if(i instanceof _n&&(e instanceof dS||e instanceof cS)){var o=e.acroField.getValue(),a=(r=i.get(o))!==null&&r!==void 0?r:i.get(se.of("Off"));a instanceof Mr&&(i=a)}if(!(i instanceof Mr)){var l=e.getName();throw new Error("Failed to extract appearance ref for: "+l)}return i},n.prototype.findOrCreateNonTerminals=function(e){for(var t=[this.acroForm],r=0,i=e.length;r<i;r++){var o=e[r];if(!o)throw new sce(o);var a=t[0],l=t[1],d=this.findNonTerminal(o,a);if(d)t=d;else{var c=oT.create(this.doc.context);c.setPartialName(o),c.setParent(l);var u=this.doc.context.register(c.dict);a.addField(u),t=[c,u]}}return t},n.prototype.findNonTerminal=function(e,t){for(var r=t instanceof aT?this.acroForm.getFields():g3(t.Kids()),i=0,o=r.length;i<o;i++){var a=r[i],l=a[0],d=a[1];if(l.getPartialName()===e){if(l instanceof oT)return[l,d];throw new qq(e)}}},n.of=function(e,t){return new n(e,t)},n}(),jce=function(n,e,t){if(n instanceof qF)return F5.of(n,e,t);if(n instanceof WF)return dS.of(n,e,t);if(n instanceof UF)return C5.of(n,e,t);if(n instanceof GF)return A5.of(n,e,t);if(n instanceof HF)return T5.of(n,e,t);if(n instanceof VF)return cS.of(n,e,t);if(n instanceof p3)return qB.of(n,e,t)},gx=function(n){if(n.length===0)throw new Error("PDF field names must not be empty strings");for(var e=n.split("."),t=0,r=e.length;t<r;t++)if(e[t]==="")throw new Error('Periods in PDF field names must be separated by at least one character: "'+n+'"');return e.length===1?{nonTerminal:[],terminal:e[0]}:{nonTerminal:e.slice(0,e.length-1),terminal:e[e.length-1]}},mx=function(n,e,t){for(var r=n[0],i=n[1],o=e[0],a=e[1],l=r.normalizedEntries(),d=g3("Kids"in l?l.Kids:l.Fields),c=0,u=d.length;c<u;c++)if(d[c][0].getPartialName()===t)throw new qq(t);r.addField(a),o.setParent(i)},kce={A4:[595.28,841.89]},VB;(function(n){n[n.Fastest=1/0]="Fastest",n[n.Fast=1500]="Fast",n[n.Medium=500]="Medium",n[n.Slow=100]="Slow"})(VB||(VB={}));var _ce=function(){function n(e,t,r){this.alreadyEmbedded=!1,this.ref=e,this.doc=t,this.embedder=r}return n.prototype.embed=function(){return Pn(this,void 0,void 0,function(){var e,t,r,i,o;return Rn(this,function(a){switch(a.label){case 0:return this.alreadyEmbedded?[3,2]:[4,this.embedder.embedIntoContext(this.doc.context,this.ref)];case 1:e=a.sent(),this.doc.catalog.has(se.of("Names"))||this.doc.catalog.set(se.of("Names"),this.doc.context.obj({})),t=this.doc.catalog.lookup(se.of("Names"),_n),t.has(se.of("EmbeddedFiles"))||t.set(se.of("EmbeddedFiles"),this.doc.context.obj({})),r=t.lookup(se.of("EmbeddedFiles"),_n),r.has(se.of("Names"))||r.set(se.of("Names"),this.doc.context.obj([])),i=r.lookup(se.of("Names"),Sr),i.push(dn.fromText(this.embedder.fileName)),i.push(e),this.doc.catalog.has(se.of("AF"))||this.doc.catalog.set(se.of("AF"),this.doc.context.obj([])),o=this.doc.catalog.lookup(se.of("AF"),Sr),o.push(e),this.alreadyEmbedded=!0,a.label=2;case 2:return[2]}})})},n.of=function(e,t,r){return new n(e,t,r)},n}(),Cce=function(){function n(e,t,r){this.alreadyEmbedded=!1,this.ref=e,this.doc=t,this.embedder=r}return n.prototype.embed=function(){return Pn(this,void 0,void 0,function(){var e,t,r,i,o,a,l;return Rn(this,function(d){switch(d.label){case 0:return this.alreadyEmbedded?[3,2]:(e=this.doc,t=e.catalog,r=e.context,[4,this.embedder.embedIntoContext(this.doc.context,this.ref)]);case 1:i=d.sent(),t.has(se.of("Names"))||t.set(se.of("Names"),r.obj({})),o=t.lookup(se.of("Names"),_n),o.has(se.of("JavaScript"))||o.set(se.of("JavaScript"),r.obj({})),a=o.lookup(se.of("JavaScript"),_n),a.has(se.of("Names"))||a.set(se.of("Names"),r.obj([])),l=a.lookup(se.of("Names"),Sr),l.push(dn.fromText(this.embedder.scriptName)),l.push(i),this.alreadyEmbedded=!0,d.label=2;case 2:return[2]}})})},n.of=function(e,t,r){return new n(e,t,r)},n}(),Ace=function(){function n(e,t){this.script=e,this.scriptName=t}return n.for=function(e,t){return new n(e,t)},n.prototype.embedIntoContext=function(e,t){return Pn(this,void 0,void 0,function(){var r;return Rn(this,function(i){return r=e.obj({Type:"Action",S:"JavaScript",JS:dn.fromText(this.script)}),t?(e.assign(t,r),[2,t]):[2,e.register(r)]})})},n}(),Af=function(){function n(e,t,r){var i=this;if(this.defaultWordBreaks=[" "],this.computePages=function(){var o=[];return i.catalog.Pages().traverse(function(a,l){if(a instanceof yf){var d=i.pageMap.get(a);d||(d=Ad.of(a,l,i),i.pageMap.set(a,d)),o.push(d)}}),o},this.getOrCreateForm=function(){var o=i.catalog.getOrCreateAcroForm();return Sce.of(o,i)},Ie(e,"context",[[OB,"PDFContext"]]),Ie(t,"ignoreEncryption",["boolean"]),this.context=e,this.catalog=e.lookup(e.trailerInfo.Root),this.isEncrypted=!!e.lookup(e.trailerInfo.Encrypt),this.pageCache=mf.populatedBy(this.computePages),this.pageMap=new Map,this.formCache=mf.populatedBy(this.getOrCreateForm),this.fonts=[],this.images=[],this.embeddedPages=[],this.embeddedFiles=[],this.javaScripts=[],!t&&this.isEncrypted)throw new ece;r&&this.updateInfoDict()}return n.load=function(e,t){return t===void 0&&(t={}),Pn(this,void 0,void 0,function(){var r,i,o,a,l,d,c,u,f,p,g,m;return Rn(this,function(y){switch(y.label){case 0:return r=t.ignoreEncryption,i=r===void 0?!1:r,o=t.parseSpeed,a=o===void 0?VB.Slow:o,l=t.throwOnInvalidObject,d=l===void 0?!1:l,c=t.updateMetadata,u=c===void 0?!0:c,f=t.capNumbers,p=f===void 0?!1:f,Ie(e,"pdf",["string",Uint8Array,ArrayBuffer]),Ie(i,"ignoreEncryption",["boolean"]),Ie(a,"parseSpeed",["number"]),Ie(d,"throwOnInvalidObject",["boolean"]),g=Iw(e),[4,Fde.forBytesWithOptions(g,a,d,p).parseDocument()];case 1:return m=y.sent(),[2,new n(m,i,u)]}})})},n.create=function(e){return e===void 0&&(e={}),Pn(this,void 0,void 0,function(){var t,r,i,o,a,l;return Rn(this,function(d){return t=e.updateMetadata,r=t===void 0?!0:t,i=OB.create(),o=Cq.withContext(i),a=i.register(o),l=_q.withContextAndPages(i,a),i.trailerInfo.Root=i.register(l),[2,new n(i,!1,r)]})})},n.prototype.registerFontkit=function(e){this.fontkit=e},n.prototype.getForm=function(){var e=this.formCache.access();return e.hasXFA()&&(console.warn("Removing XFA form data as pdf-lib does not support reading or writing XFA"),e.deleteXFA()),e},n.prototype.getTitle=function(){var e=this.getInfoDict().lookup(se.Title);if(e)return Vf(e),e.decodeText()},n.prototype.getAuthor=function(){var e=this.getInfoDict().lookup(se.Author);if(e)return Vf(e),e.decodeText()},n.prototype.getSubject=function(){var e=this.getInfoDict().lookup(se.Subject);if(e)return Vf(e),e.decodeText()},n.prototype.getKeywords=function(){var e=this.getInfoDict().lookup(se.Keywords);if(e)return Vf(e),e.decodeText()},n.prototype.getCreator=function(){var e=this.getInfoDict().lookup(se.Creator);if(e)return Vf(e),e.decodeText()},n.prototype.getProducer=function(){var e=this.getInfoDict().lookup(se.Producer);if(e)return Vf(e),e.decodeText()},n.prototype.getCreationDate=function(){var e=this.getInfoDict().lookup(se.CreationDate);if(e)return Vf(e),e.decodeDate()},n.prototype.getModificationDate=function(){var e=this.getInfoDict().lookup(se.ModDate);if(e)return Vf(e),e.decodeDate()},n.prototype.setTitle=function(e,t){Ie(e,"title",["string"]);var r=se.of("Title");if(this.getInfoDict().set(r,dn.fromText(e)),t!=null&&t.showInWindowTitleBar){var i=this.catalog.getOrCreateViewerPreferences();i.setDisplayDocTitle(!0)}},n.prototype.setAuthor=function(e){Ie(e,"author",["string"]);var t=se.of("Author");this.getInfoDict().set(t,dn.fromText(e))},n.prototype.setSubject=function(e){Ie(e,"author",["string"]);var t=se.of("Subject");this.getInfoDict().set(t,dn.fromText(e))},n.prototype.setKeywords=function(e){Ie(e,"keywords",[Array]);var t=se.of("Keywords");this.getInfoDict().set(t,dn.fromText(e.join(" ")))},n.prototype.setCreator=function(e){Ie(e,"creator",["string"]);var t=se.of("Creator");this.getInfoDict().set(t,dn.fromText(e))},n.prototype.setProducer=function(e){Ie(e,"creator",["string"]);var t=se.of("Producer");this.getInfoDict().set(t,dn.fromText(e))},n.prototype.setLanguage=function(e){Ie(e,"language",["string"]);var t=se.of("Lang");this.catalog.set(t,Ir.of(e))},n.prototype.setCreationDate=function(e){Ie(e,"creationDate",[[Date,"Date"]]);var t=se.of("CreationDate");this.getInfoDict().set(t,Ir.fromDate(e))},n.prototype.setModificationDate=function(e){Ie(e,"modificationDate",[[Date,"Date"]]);var t=se.of("ModDate");this.getInfoDict().set(t,Ir.fromDate(e))},n.prototype.getPageCount=function(){return this.pageCount===void 0&&(this.pageCount=this.getPages().length),this.pageCount},n.prototype.getPages=function(){return this.pageCache.access()},n.prototype.getPage=function(e){var t=this.getPages();return Hl(e,"index",0,t.length-1),t[e]},n.prototype.getPageIndices=function(){return Xse(0,this.getPageCount())},n.prototype.removePage=function(e){var t=this.getPageCount();if(this.pageCount===0)throw new rce;Hl(e,"index",0,t-1),this.catalog.removeLeafNode(e),this.pageCount=t-1},n.prototype.addPage=function(e){return Ie(e,"page",["undefined",[Ad,"PDFPage"],Array]),this.insertPage(this.getPageCount(),e)},n.prototype.insertPage=function(e,t){var r=this.getPageCount();if(Hl(e,"index",0,r),Ie(t,"page",["undefined",[Ad,"PDFPage"],Array]),!t||Array.isArray(t)){var i=Array.isArray(t)?t:kce.A4;t=Ad.create(this),t.setSize.apply(t,i)}else if(t.doc!==this)throw new nce;var o=this.catalog.insertLeafNode(t.ref,e);return t.node.setParent(o),this.pageMap.set(t.node,t),this.pageCache.invalidate(),this.pageCount=r+1,t},n.prototype.copyPages=function(e,t){return Pn(this,void 0,void 0,function(){var r,i,o,a,l,d,c,u;return Rn(this,function(f){switch(f.label){case 0:return Ie(e,"srcDoc",[[n,"PDFDocument"]]),Ie(t,"indices",[Array]),[4,e.flush()];case 1:for(f.sent(),r=q4.for(e.context,this.context),i=e.getPages(),o=new Array(t.length),a=0,l=t.length;a<l;a++)d=i[t[a]],c=r.copy(d.node),u=this.context.register(c),o[a]=Ad.of(c,u,this);return[2,o]}})})},n.prototype.copy=function(){return Pn(this,void 0,void 0,function(){var e,t,r,i;return Rn(this,function(o){switch(o.label){case 0:return[4,n.create()];case 1:return e=o.sent(),[4,e.copyPages(this,this.getPageIndices())];case 2:for(t=o.sent(),r=0,i=t.length;r<i;r++)e.addPage(t[r]);return this.getAuthor()!==void 0&&e.setAuthor(this.getAuthor()),this.getCreationDate()!==void 0&&e.setCreationDate(this.getCreationDate()),this.getCreator()!==void 0&&e.setCreator(this.getCreator()),this.getModificationDate()!==void 0&&e.setModificationDate(this.getModificationDate()),this.getProducer()!==void 0&&e.setProducer(this.getProducer()),this.getSubject()!==void 0&&e.setSubject(this.getSubject()),this.getTitle()!==void 0&&e.setTitle(this.getTitle()),e.defaultWordBreaks=this.defaultWordBreaks,[2,e]}})})},n.prototype.addJavaScript=function(e,t){Ie(e,"name",["string"]),Ie(t,"script",["string"]);var r=Ace.for(t,e),i=this.context.nextRef(),o=Cce.of(i,this,r);this.javaScripts.push(o)},n.prototype.attach=function(e,t,r){return r===void 0&&(r={}),Pn(this,void 0,void 0,function(){var i,o,a,l;return Rn(this,function(d){return Ie(e,"attachment",["string",Uint8Array,ArrayBuffer]),Ie(t,"name",["string"]),mt(r.mimeType,"mimeType",["string"]),mt(r.description,"description",["string"]),mt(r.creationDate,"options.creationDate",[Date]),mt(r.modificationDate,"options.modificationDate",[Date]),ld(r.afRelationship,"options.afRelationship",LB),i=Iw(e),o=tde.for(i,t,r),a=this.context.nextRef(),l=_ce.of(a,this,o),this.embeddedFiles.push(l),[2]})})},n.prototype.embedFont=function(e,t){return t===void 0&&(t={}),Pn(this,void 0,void 0,function(){var r,i,o,a,l,d,c,u,f,p;return Rn(this,function(g){switch(g.label){case 0:return r=t.subset,i=r===void 0?!1:r,o=t.customName,a=t.features,Ie(e,"font",["string",Uint8Array,ArrayBuffer]),Ie(i,"subset",["boolean"]),I4(e)?(l=iT.for(e,o),[3,7]):[3,1];case 1:return Qse(e)?(d=Iw(e),c=this.assertFontkit(),i?[4,ede.for(c,d,o,a)]:[3,3]):[3,6];case 2:return u=g.sent(),[3,5];case 3:return[4,h3.for(c,d,o,a)];case 4:u=g.sent(),g.label=5;case 5:return l=u,[3,7];case 6:throw new TypeError("`font` must be one of `StandardFonts | string | Uint8Array | ArrayBuffer`");case 7:return f=this.context.nextRef(),p=Yl.of(f,this,l),this.fonts.push(p),[2,p]}})})},n.prototype.embedStandardFont=function(e,t){if(Ie(e,"font",["string"]),!I4(e))throw new TypeError("`font` must be one of type `StandardFonts`");var r=iT.for(e,t),i=this.context.nextRef(),o=Yl.of(i,this,r);return this.fonts.push(o),o},n.prototype.embedJpg=function(e){return Pn(this,void 0,void 0,function(){var t,r,i,o;return Rn(this,function(a){switch(a.label){case 0:return Ie(e,"jpg",["string",Uint8Array,ArrayBuffer]),t=Iw(e),[4,mq.for(t)];case 1:return r=a.sent(),i=this.context.nextRef(),o=HB.of(i,this,r),this.images.push(o),[2,o]}})})},n.prototype.embedPng=function(e){return Pn(this,void 0,void 0,function(){var t,r,i,o;return Rn(this,function(a){switch(a.label){case 0:return Ie(e,"png",["string",Uint8Array,ArrayBuffer]),t=Iw(e),[4,yq.for(t)];case 1:return r=a.sent(),i=this.context.nextRef(),o=HB.of(i,this,r),this.images.push(o),[2,o]}})})},n.prototype.embedPdf=function(e,t){return t===void 0&&(t=[0]),Pn(this,void 0,void 0,function(){var r,i,o;return Rn(this,function(a){switch(a.label){case 0:return Ie(e,"pdf",["string",Uint8Array,ArrayBuffer,[n,"PDFDocument"]]),Ie(t,"indices",[Array]),e instanceof n?(i=e,[3,3]):[3,1];case 1:return[4,n.load(e)];case 2:i=a.sent(),a.label=3;case 3:return r=i,o=Yse(r.getPages(),t),[2,this.embedPages(o)]}})})},n.prototype.embedPage=function(e,t,r){return Pn(this,void 0,void 0,function(){var i;return Rn(this,function(o){switch(o.label){case 0:return Ie(e,"page",[[Ad,"PDFPage"]]),[4,this.embedPages([e],[t],[r])];case 1:return i=o.sent()[0],[2,i]}})})},n.prototype.embedPages=function(e,t,r){return t===void 0&&(t=[]),r===void 0&&(r=[]),Pn(this,void 0,void 0,function(){var c,u,i,o,a,l,d,c,u,f,p,g,m,y,v;return Rn(this,function(x){switch(x.label){case 0:if(e.length===0)return[2,[]];for(c=0,u=e.length-1;c<u;c++)if(i=e[c],o=e[c+1],i.node.context!==o.node.context)throw new Ale;a=e[0].node.context,l=a===this.context?function(w){return w}:q4.for(a,this.context).copy,d=new Array(e.length),c=0,u=e.length,x.label=1;case 1:return c<u?(f=l(e[c].node),p=t[c],g=r[c],[4,vq.for(f,p,g)]):[3,4];case 2:m=x.sent(),y=this.context.nextRef(),d[c]=Yq.of(y,this,m),x.label=3;case 3:return c++,[3,1];case 4:return(v=this.embeddedPages).push.apply(v,d),[2,d]}})})},n.prototype.flush=function(){return Pn(this,void 0,void 0,function(){return Rn(this,function(e){switch(e.label){case 0:return[4,this.embedAll(this.fonts)];case 1:return e.sent(),[4,this.embedAll(this.images)];case 2:return e.sent(),[4,this.embedAll(this.embeddedPages)];case 3:return e.sent(),[4,this.embedAll(this.embeddedFiles)];case 4:return e.sent(),[4,this.embedAll(this.javaScripts)];case 5:return e.sent(),[2]}})})},n.prototype.save=function(e){return e===void 0&&(e={}),Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c,u,f;return Rn(this,function(p){switch(p.label){case 0:return t=e.useObjectStreams,r=t===void 0?!0:t,i=e.addDefaultPage,o=i===void 0?!0:i,a=e.objectsPerTick,l=a===void 0?50:a,d=e.updateFieldAppearances,c=d===void 0?!0:d,Ie(r,"useObjectStreams",["boolean"]),Ie(o,"addDefaultPage",["boolean"]),Ie(l,"objectsPerTick",["number"]),Ie(c,"updateFieldAppearances",["boolean"]),o&&this.getPageCount()===0&&this.addPage(),c&&(u=this.formCache.getValue(),u&&u.updateFieldAppearances()),[4,this.flush()];case 1:return p.sent(),f=r?Xle:pq,[2,f.forContext(this.context,l).serializeToBuffer()]}})})},n.prototype.saveAsBase64=function(e){return e===void 0&&(e={}),Pn(this,void 0,void 0,function(){var t,r,i,o,a;return Rn(this,function(l){switch(l.label){case 0:return t=e.dataUri,r=t===void 0?!1:t,i=Ese(e,["dataUri"]),Ie(r,"dataUri",["boolean"]),[4,this.save(i)];case 1:return o=l.sent(),a=Pse(o),[2,r?"data:application/pdf;base64,"+a:a]}})})},n.prototype.findPageForAnnotationRef=function(e){for(var t=this.getPages(),r=0,i=t.length;r<i;r++){var o=t[r],a=o.node.Annots();if((a==null?void 0:a.indexOf(e))!==void 0)return o}},n.prototype.embedAll=function(e){return Pn(this,void 0,void 0,function(){var t,r;return Rn(this,function(i){switch(i.label){case 0:t=0,r=e.length,i.label=1;case 1:return t<r?[4,e[t].embed()]:[3,4];case 2:i.sent(),i.label=3;case 3:return t++,[3,1];case 4:return[2]}})})},n.prototype.updateInfoDict=function(){var e="pdf-lib (https://github.com/Hopding/pdf-lib)",t=new Date,r=this.getInfoDict();this.setProducer(e),this.setModificationDate(t),r.get(se.of("Creator"))||this.setCreator(e),r.get(se.of("CreationDate"))||this.setCreationDate(t)},n.prototype.getInfoDict=function(){var e=this.context.lookup(this.context.trailerInfo.Info);if(e instanceof _n)return e;var t=this.context.obj({});return this.context.trailerInfo.Info=this.context.register(t),t},n.prototype.assertFontkit=function(){if(!this.fontkit)throw new tce;return this.fontkit},n}();function Vf(n){if(!(n instanceof dn)&&!(n instanceof Ir))throw new nT([dn,Ir],n)}var mh;(function(n){n.Normal="Normal",n.Multiply="Multiply",n.Screen="Screen",n.Overlay="Overlay",n.Darken="Darken",n.Lighten="Lighten",n.ColorDodge="ColorDodge",n.ColorBurn="ColorBurn",n.HardLight="HardLight",n.SoftLight="SoftLight",n.Difference="Difference",n.Exclusion="Exclusion"})(mh||(mh={}));var Ad=function(){function n(e,t,r){this.fontSize=24,this.fontColor=zr(0,0,0),this.lineHeight=24,this.x=0,this.y=0,Ie(e,"leafNode",[[yf,"PDFPageLeaf"]]),Ie(t,"ref",[[Mr,"PDFRef"]]),Ie(r,"doc",[[Af,"PDFDocument"]]),this.node=e,this.ref=t,this.doc=r}return n.prototype.setRotation=function(e){var t=Eq(e);dq(t,"degreesAngle",90),this.node.set(se.of("Rotate"),this.doc.context.obj(t))},n.prototype.getRotation=function(){var e=this.node.Rotate();return cn(e?e.asNumber():0)},n.prototype.setSize=function(e,t){Ie(e,"width",["number"]),Ie(t,"height",["number"]);var r=this.getMediaBox();this.setMediaBox(r.x,r.y,e,t);var i=this.getCropBox(),o=this.getBleedBox(),a=this.getTrimBox(),l=this.getArtBox(),d=this.node.CropBox(),c=this.node.BleedBox(),u=this.node.TrimBox(),f=this.node.ArtBox();d&&I2(i,r)&&this.setCropBox(r.x,r.y,e,t),c&&I2(o,r)&&this.setBleedBox(r.x,r.y,e,t),u&&I2(a,r)&&this.setTrimBox(r.x,r.y,e,t),f&&I2(l,r)&&this.setArtBox(r.x,r.y,e,t)},n.prototype.setWidth=function(e){Ie(e,"width",["number"]),this.setSize(e,this.getSize().height)},n.prototype.setHeight=function(e){Ie(e,"height",["number"]),this.setSize(this.getSize().width,e)},n.prototype.setMediaBox=function(e,t,r,i){Ie(e,"x",["number"]),Ie(t,"y",["number"]),Ie(r,"width",["number"]),Ie(i,"height",["number"]);var o=this.doc.context.obj([e,t,e+r,t+i]);this.node.set(se.MediaBox,o)},n.prototype.setCropBox=function(e,t,r,i){Ie(e,"x",["number"]),Ie(t,"y",["number"]),Ie(r,"width",["number"]),Ie(i,"height",["number"]);var o=this.doc.context.obj([e,t,e+r,t+i]);this.node.set(se.CropBox,o)},n.prototype.setBleedBox=function(e,t,r,i){Ie(e,"x",["number"]),Ie(t,"y",["number"]),Ie(r,"width",["number"]),Ie(i,"height",["number"]);var o=this.doc.context.obj([e,t,e+r,t+i]);this.node.set(se.BleedBox,o)},n.prototype.setTrimBox=function(e,t,r,i){Ie(e,"x",["number"]),Ie(t,"y",["number"]),Ie(r,"width",["number"]),Ie(i,"height",["number"]);var o=this.doc.context.obj([e,t,e+r,t+i]);this.node.set(se.TrimBox,o)},n.prototype.setArtBox=function(e,t,r,i){Ie(e,"x",["number"]),Ie(t,"y",["number"]),Ie(r,"width",["number"]),Ie(i,"height",["number"]);var o=this.doc.context.obj([e,t,e+r,t+i]);this.node.set(se.ArtBox,o)},n.prototype.getSize=function(){var e=this.getMediaBox(),t=e.width,r=e.height;return{width:t,height:r}},n.prototype.getWidth=function(){return this.getSize().width},n.prototype.getHeight=function(){return this.getSize().height},n.prototype.getMediaBox=function(){var e=this.node.MediaBox();return e.asRectangle()},n.prototype.getCropBox=function(){var e,t=this.node.CropBox();return(e=t==null?void 0:t.asRectangle())!==null&&e!==void 0?e:this.getMediaBox()},n.prototype.getBleedBox=function(){var e,t=this.node.BleedBox();return(e=t==null?void 0:t.asRectangle())!==null&&e!==void 0?e:this.getCropBox()},n.prototype.getTrimBox=function(){var e,t=this.node.TrimBox();return(e=t==null?void 0:t.asRectangle())!==null&&e!==void 0?e:this.getCropBox()},n.prototype.getArtBox=function(){var e,t=this.node.ArtBox();return(e=t==null?void 0:t.asRectangle())!==null&&e!==void 0?e:this.getCropBox()},n.prototype.translateContent=function(e,t){Ie(e,"x",["number"]),Ie(t,"y",["number"]),this.node.normalize(),this.getContentStream();var r=this.createContentStream(qs(),Rd(e,t)),i=this.doc.context.register(r),o=this.createContentStream(Vs()),a=this.doc.context.register(o);this.node.wrapContentStreams(i,a)},n.prototype.scale=function(e,t){Ie(e,"x",["number"]),Ie(t,"y",["number"]),this.setSize(this.getWidth()*e,this.getHeight()*t),this.scaleContent(e,t),this.scaleAnnotations(e,t)},n.prototype.scaleContent=function(e,t){Ie(e,"x",["number"]),Ie(t,"y",["number"]),this.node.normalize(),this.getContentStream();var r=this.createContentStream(qs(),Vj(e,t)),i=this.doc.context.register(r),o=this.createContentStream(Vs()),a=this.doc.context.register(o);this.node.wrapContentStreams(i,a)},n.prototype.scaleAnnotations=function(e,t){Ie(e,"x",["number"]),Ie(t,"y",["number"]);var r=this.node.Annots();if(r)for(var i=0;i<r.size();i++){var o=r.lookup(i);o instanceof _n&&this.scaleAnnot(o,e,t)}},n.prototype.resetPosition=function(){this.getContentStream(!1),this.x=0,this.y=0},n.prototype.setFont=function(e){Ie(e,"font",[[Yl,"PDFFont"]]),this.font=e,this.fontKey=this.node.newFontDictionary(this.font.name,this.font.ref)},n.prototype.setFontSize=function(e){Ie(e,"fontSize",["number"]),this.fontSize=e},n.prototype.setFontColor=function(e){Ie(e,"fontColor",[[Object,"Color"]]),this.fontColor=e},n.prototype.setLineHeight=function(e){Ie(e,"lineHeight",["number"]),this.lineHeight=e},n.prototype.getPosition=function(){return{x:this.x,y:this.y}},n.prototype.getX=function(){return this.x},n.prototype.getY=function(){return this.y},n.prototype.moveTo=function(e,t){Ie(e,"x",["number"]),Ie(t,"y",["number"]),this.x=e,this.y=t},n.prototype.moveDown=function(e){Ie(e,"yDecrease",["number"]),this.y-=e},n.prototype.moveUp=function(e){Ie(e,"yIncrease",["number"]),this.y+=e},n.prototype.moveLeft=function(e){Ie(e,"xDecrease",["number"]),this.x-=e},n.prototype.moveRight=function(e){Ie(e,"xIncrease",["number"]),this.x+=e},n.prototype.pushOperators=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];lq(e,"operator",[[or,"PDFOperator"]]);var r=this.getContentStream();r.push.apply(r,e)},n.prototype.drawText=function(e,t){var r,i,o,a,l,d,c;t===void 0&&(t={}),Ie(e,"text",["string"]),mt(t.color,"options.color",[[Object,"Color"]]),nc(t.opacity,"opacity.opacity",0,1),mt(t.font,"options.font",[[Yl,"PDFFont"]]),mt(t.size,"options.size",["number"]),mt(t.rotate,"options.rotate",[[Object,"Rotation"]]),mt(t.xSkew,"options.xSkew",[[Object,"Rotation"]]),mt(t.ySkew,"options.ySkew",[[Object,"Rotation"]]),mt(t.x,"options.x",["number"]),mt(t.y,"options.y",["number"]),mt(t.lineHeight,"options.lineHeight",["number"]),mt(t.maxWidth,"options.maxWidth",["number"]),mt(t.wordBreaks,"options.wordBreaks",[Array]),ld(t.blendMode,"options.blendMode",mh);for(var u=this.setOrEmbedFont(t.font),f=u.oldFont,p=u.newFont,g=u.newFontKey,m=t.size||this.fontSize,y=t.wordBreaks||this.doc.defaultWordBreaks,v=function(T){return p.widthOfTextAtSize(T,m)},x=t.maxWidth===void 0?dH(J_(e)):Wse(e,y,t.maxWidth,v),w=new Array(x.length),S=0,_=x.length;S<_;S++)w[S]=p.encodeText(x[S]);var b=this.maybeEmbedGraphicsState({opacity:t.opacity,blendMode:t.blendMode}),C=this.getContentStream();C.push.apply(C,Gde(w,{color:(r=t.color)!==null&&r!==void 0?r:this.fontColor,font:g,size:m,rotate:(i=t.rotate)!==null&&i!==void 0?i:cn(0),xSkew:(o=t.xSkew)!==null&&o!==void 0?o:cn(0),ySkew:(a=t.ySkew)!==null&&a!==void 0?a:cn(0),x:(l=t.x)!==null&&l!==void 0?l:this.x,y:(d=t.y)!==null&&d!==void 0?d:this.y,lineHeight:(c=t.lineHeight)!==null&&c!==void 0?c:this.lineHeight,graphicsState:b})),t.font&&(f?this.setFont(f):this.resetFont())},n.prototype.drawImage=function(e,t){var r,i,o,a,l,d,c;t===void 0&&(t={}),Ie(e,"image",[[HB,"PDFImage"]]),mt(t.x,"options.x",["number"]),mt(t.y,"options.y",["number"]),mt(t.width,"options.width",["number"]),mt(t.height,"options.height",["number"]),mt(t.rotate,"options.rotate",[[Object,"Rotation"]]),mt(t.xSkew,"options.xSkew",[[Object,"Rotation"]]),mt(t.ySkew,"options.ySkew",[[Object,"Rotation"]]),nc(t.opacity,"opacity.opacity",0,1),ld(t.blendMode,"options.blendMode",mh);var u=this.node.newXObject("Image",e.ref),f=this.maybeEmbedGraphicsState({opacity:t.opacity,blendMode:t.blendMode}),p=this.getContentStream();p.push.apply(p,Uq(u,{x:(r=t.x)!==null&&r!==void 0?r:this.x,y:(i=t.y)!==null&&i!==void 0?i:this.y,width:(o=t.width)!==null&&o!==void 0?o:e.size().width,height:(a=t.height)!==null&&a!==void 0?a:e.size().height,rotate:(l=t.rotate)!==null&&l!==void 0?l:cn(0),xSkew:(d=t.xSkew)!==null&&d!==void 0?d:cn(0),ySkew:(c=t.ySkew)!==null&&c!==void 0?c:cn(0),graphicsState:f}))},n.prototype.drawPage=function(e,t){var r,i,o,a,l;t===void 0&&(t={}),Ie(e,"embeddedPage",[[Yq,"PDFEmbeddedPage"]]),mt(t.x,"options.x",["number"]),mt(t.y,"options.y",["number"]),mt(t.xScale,"options.xScale",["number"]),mt(t.yScale,"options.yScale",["number"]),mt(t.width,"options.width",["number"]),mt(t.height,"options.height",["number"]),mt(t.rotate,"options.rotate",[[Object,"Rotation"]]),mt(t.xSkew,"options.xSkew",[[Object,"Rotation"]]),mt(t.ySkew,"options.ySkew",[[Object,"Rotation"]]),nc(t.opacity,"opacity.opacity",0,1),ld(t.blendMode,"options.blendMode",mh);var d=this.node.newXObject("EmbeddedPdfPage",e.ref),c=this.maybeEmbedGraphicsState({opacity:t.opacity,blendMode:t.blendMode}),u=t.width!==void 0?t.width/e.width:t.xScale!==void 0?t.xScale:1,f=t.height!==void 0?t.height/e.height:t.yScale!==void 0?t.yScale:1,p=this.getContentStream();p.push.apply(p,Kde(d,{x:(r=t.x)!==null&&r!==void 0?r:this.x,y:(i=t.y)!==null&&i!==void 0?i:this.y,xScale:u,yScale:f,rotate:(o=t.rotate)!==null&&o!==void 0?o:cn(0),xSkew:(a=t.xSkew)!==null&&a!==void 0?a:cn(0),ySkew:(l=t.ySkew)!==null&&l!==void 0?l:cn(0),graphicsState:c}))},n.prototype.drawSvgPath=function(e,t){var r,i,o,a,l,d,c,u,f;t===void 0&&(t={}),Ie(e,"path",["string"]),mt(t.x,"options.x",["number"]),mt(t.y,"options.y",["number"]),mt(t.scale,"options.scale",["number"]),mt(t.rotate,"options.rotate",[[Object,"Rotation"]]),mt(t.borderWidth,"options.borderWidth",["number"]),mt(t.color,"options.color",[[Object,"Color"]]),nc(t.opacity,"opacity.opacity",0,1),mt(t.borderColor,"options.borderColor",[[Object,"Color"]]),mt(t.borderDashArray,"options.borderDashArray",[Array]),mt(t.borderDashPhase,"options.borderDashPhase",["number"]),ld(t.borderLineCap,"options.borderLineCap",Kx),nc(t.borderOpacity,"options.borderOpacity",0,1),ld(t.blendMode,"options.blendMode",mh);var p=this.maybeEmbedGraphicsState({opacity:t.opacity,borderOpacity:t.borderOpacity,blendMode:t.blendMode});!("color"in t)&&!("borderColor"in t)&&(t.borderColor=zr(0,0,0));var g=this.getContentStream();g.push.apply(g,$de(e,{x:(r=t.x)!==null&&r!==void 0?r:this.x,y:(i=t.y)!==null&&i!==void 0?i:this.y,scale:t.scale,rotate:(o=t.rotate)!==null&&o!==void 0?o:cn(0),color:(a=t.color)!==null&&a!==void 0?a:void 0,borderColor:(l=t.borderColor)!==null&&l!==void 0?l:void 0,borderWidth:(d=t.borderWidth)!==null&&d!==void 0?d:0,borderDashArray:(c=t.borderDashArray)!==null&&c!==void 0?c:void 0,borderDashPhase:(u=t.borderDashPhase)!==null&&u!==void 0?u:void 0,borderLineCap:(f=t.borderLineCap)!==null&&f!==void 0?f:void 0,graphicsState:p}))},n.prototype.drawLine=function(e){var t,r,i,o,a;Ie(e.start,"options.start",[[Object,"{ x: number, y: number }"]]),Ie(e.end,"options.end",[[Object,"{ x: number, y: number }"]]),Ie(e.start.x,"options.start.x",["number"]),Ie(e.start.y,"options.start.y",["number"]),Ie(e.end.x,"options.end.x",["number"]),Ie(e.end.y,"options.end.y",["number"]),mt(e.thickness,"options.thickness",["number"]),mt(e.color,"options.color",[[Object,"Color"]]),mt(e.dashArray,"options.dashArray",[Array]),mt(e.dashPhase,"options.dashPhase",["number"]),ld(e.lineCap,"options.lineCap",Kx),nc(e.opacity,"opacity.opacity",0,1),ld(e.blendMode,"options.blendMode",mh);var l=this.maybeEmbedGraphicsState({borderOpacity:e.opacity,blendMode:e.blendMode});"color"in e||(e.color=zr(0,0,0));var d=this.getContentStream();d.push.apply(d,Xde({start:e.start,end:e.end,thickness:(t=e.thickness)!==null&&t!==void 0?t:1,color:(r=e.color)!==null&&r!==void 0?r:void 0,dashArray:(i=e.dashArray)!==null&&i!==void 0?i:void 0,dashPhase:(o=e.dashPhase)!==null&&o!==void 0?o:void 0,lineCap:(a=e.lineCap)!==null&&a!==void 0?a:void 0,graphicsState:l}))},n.prototype.drawRectangle=function(e){var t,r,i,o,a,l,d,c,u,f,p,g,m;e===void 0&&(e={}),mt(e.x,"options.x",["number"]),mt(e.y,"options.y",["number"]),mt(e.width,"options.width",["number"]),mt(e.height,"options.height",["number"]),mt(e.rotate,"options.rotate",[[Object,"Rotation"]]),mt(e.xSkew,"options.xSkew",[[Object,"Rotation"]]),mt(e.ySkew,"options.ySkew",[[Object,"Rotation"]]),mt(e.borderWidth,"options.borderWidth",["number"]),mt(e.color,"options.color",[[Object,"Color"]]),nc(e.opacity,"opacity.opacity",0,1),mt(e.borderColor,"options.borderColor",[[Object,"Color"]]),mt(e.borderDashArray,"options.borderDashArray",[Array]),mt(e.borderDashPhase,"options.borderDashPhase",["number"]),ld(e.borderLineCap,"options.borderLineCap",Kx),nc(e.borderOpacity,"options.borderOpacity",0,1),ld(e.blendMode,"options.blendMode",mh);var y=this.maybeEmbedGraphicsState({opacity:e.opacity,borderOpacity:e.borderOpacity,blendMode:e.blendMode});!("color"in e)&&!("borderColor"in e)&&(e.color=zr(0,0,0));var v=this.getContentStream();v.push.apply(v,l1({x:(t=e.x)!==null&&t!==void 0?t:this.x,y:(r=e.y)!==null&&r!==void 0?r:this.y,width:(i=e.width)!==null&&i!==void 0?i:150,height:(o=e.height)!==null&&o!==void 0?o:100,rotate:(a=e.rotate)!==null&&a!==void 0?a:cn(0),xSkew:(l=e.xSkew)!==null&&l!==void 0?l:cn(0),ySkew:(d=e.ySkew)!==null&&d!==void 0?d:cn(0),borderWidth:(c=e.borderWidth)!==null&&c!==void 0?c:0,color:(u=e.color)!==null&&u!==void 0?u:void 0,borderColor:(f=e.borderColor)!==null&&f!==void 0?f:void 0,borderDashArray:(p=e.borderDashArray)!==null&&p!==void 0?p:void 0,borderDashPhase:(g=e.borderDashPhase)!==null&&g!==void 0?g:void 0,graphicsState:y,borderLineCap:(m=e.borderLineCap)!==null&&m!==void 0?m:void 0}))},n.prototype.drawSquare=function(e){e===void 0&&(e={});var t=e.size;mt(t,"size",["number"]),this.drawRectangle(wn(wn({},e),{width:t,height:t}))},n.prototype.drawEllipse=function(e){var t,r,i,o,a,l,d,c,u,f,p;e===void 0&&(e={}),mt(e.x,"options.x",["number"]),mt(e.y,"options.y",["number"]),mt(e.xScale,"options.xScale",["number"]),mt(e.yScale,"options.yScale",["number"]),mt(e.rotate,"options.rotate",[[Object,"Rotation"]]),mt(e.color,"options.color",[[Object,"Color"]]),nc(e.opacity,"opacity.opacity",0,1),mt(e.borderColor,"options.borderColor",[[Object,"Color"]]),nc(e.borderOpacity,"options.borderOpacity",0,1),mt(e.borderWidth,"options.borderWidth",["number"]),mt(e.borderDashArray,"options.borderDashArray",[Array]),mt(e.borderDashPhase,"options.borderDashPhase",["number"]),ld(e.borderLineCap,"options.borderLineCap",Kx),ld(e.blendMode,"options.blendMode",mh);var g=this.maybeEmbedGraphicsState({opacity:e.opacity,borderOpacity:e.borderOpacity,blendMode:e.blendMode});!("color"in e)&&!("borderColor"in e)&&(e.color=zr(0,0,0));var m=this.getContentStream();m.push.apply(m,UB({x:(t=e.x)!==null&&t!==void 0?t:this.x,y:(r=e.y)!==null&&r!==void 0?r:this.y,xScale:(i=e.xScale)!==null&&i!==void 0?i:100,yScale:(o=e.yScale)!==null&&o!==void 0?o:100,rotate:(a=e.rotate)!==null&&a!==void 0?a:void 0,color:(l=e.color)!==null&&l!==void 0?l:void 0,borderColor:(d=e.borderColor)!==null&&d!==void 0?d:void 0,borderWidth:(c=e.borderWidth)!==null&&c!==void 0?c:0,borderDashArray:(u=e.borderDashArray)!==null&&u!==void 0?u:void 0,borderDashPhase:(f=e.borderDashPhase)!==null&&f!==void 0?f:void 0,borderLineCap:(p=e.borderLineCap)!==null&&p!==void 0?p:void 0,graphicsState:g}))},n.prototype.drawCircle=function(e){e===void 0&&(e={});var t=e.size,r=t===void 0?100:t;mt(r,"size",["number"]),this.drawEllipse(wn(wn({},e),{xScale:r,yScale:r}))},n.prototype.setOrEmbedFont=function(e){var t=this.font,r=this.fontKey;e?this.setFont(e):this.getFont();var i=this.font,o=this.fontKey;return{oldFont:t,oldFontKey:r,newFont:i,newFontKey:o}},n.prototype.getFont=function(){if(!this.font||!this.fontKey){var e=this.doc.embedStandardFont(fT.Helvetica);this.setFont(e)}return[this.font,this.fontKey]},n.prototype.resetFont=function(){this.font=void 0,this.fontKey=void 0},n.prototype.getContentStream=function(e){return e===void 0&&(e=!0),e&&this.contentStream?this.contentStream:(this.contentStream=this.createContentStream(),this.contentStreamRef=this.doc.context.register(this.contentStream),this.node.addContentStream(this.contentStreamRef),this.contentStream)},n.prototype.createContentStream=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=this.doc.context.obj({}),i=ZS.of(r,e);return i},n.prototype.maybeEmbedGraphicsState=function(e){var t=e.opacity,r=e.borderOpacity,i=e.blendMode;if(!(t===void 0&&r===void 0&&i===void 0)){var o=this.doc.context.obj({Type:"ExtGState",ca:t,CA:r,BM:i}),a=this.node.newExtGState("GS",o);return a}},n.prototype.scaleAnnot=function(e,t,r){for(var i=["RD","CL","Vertices","QuadPoints","L","Rect"],o=0,a=i.length;o<a;o++){var l=e.lookup(se.of(i[o]));l instanceof Sr&&l.scalePDFNumbers(t,r)}var d=e.lookup(se.of("InkList"));if(d instanceof Sr)for(var o=0,a=d.size();o<a;o++){var c=d.lookup(o);c instanceof Sr&&c.scalePDFNumbers(t,r)}},n.of=function(e,t,r){return new n(e,t,r)},n.create=function(e){Ie(e,"doc",[[Af,"PDFDocument"]]);var t=Mr.of(-1),r=yf.withContextAndParent(e.context,t),i=e.context.register(r);return new n(r,i,e)},n}(),F5=function(n){xt(e,n);function e(t,r,i){var o=n.call(this,t,r,i)||this;return Ie(t,"acroButton",[[qF,"PDFAcroPushButton"]]),o.acroField=t,o}return e.prototype.setImage=function(t,r){r===void 0&&(r=Pg.Center);for(var i=this.acroField.getWidgets(),o=0,a=i.length;o<a;o++){var l=i[o],d=this.createImageAppearanceStream(l,t,r);this.updateWidgetAppearances(l,{normal:d})}this.markAsClean()},e.prototype.setFontSize=function(t){LF(t,"fontSize"),this.acroField.setFontSize(t),this.markAsDirty()},e.prototype.addToPage=function(t,r,i){var o,a,l,d,c,u,f,p,g,m,y;mt(t,"text",["string"]),mt(r,"page",[[Ad,"PDFPage"]]),C1(i);var v=this.createWidget({x:((o=i==null?void 0:i.x)!==null&&o!==void 0?o:0)-((a=i==null?void 0:i.borderWidth)!==null&&a!==void 0?a:0)/2,y:((l=i==null?void 0:i.y)!==null&&l!==void 0?l:0)-((d=i==null?void 0:i.borderWidth)!==null&&d!==void 0?d:0)/2,width:(c=i==null?void 0:i.width)!==null&&c!==void 0?c:100,height:(u=i==null?void 0:i.height)!==null&&u!==void 0?u:50,textColor:(f=i==null?void 0:i.textColor)!==null&&f!==void 0?f:zr(0,0,0),backgroundColor:(p=i==null?void 0:i.backgroundColor)!==null&&p!==void 0?p:zr(.75,.75,.75),borderColor:i==null?void 0:i.borderColor,borderWidth:(g=i==null?void 0:i.borderWidth)!==null&&g!==void 0?g:0,rotate:(m=i==null?void 0:i.rotate)!==null&&m!==void 0?m:cn(0),caption:t,hidden:i==null?void 0:i.hidden,page:r.ref}),x=this.doc.context.register(v.dict);this.acroField.addWidget(x);var w=(y=i==null?void 0:i.font)!==null&&y!==void 0?y:this.doc.getForm().getDefaultFont();this.updateWidgetAppearance(v,w),r.node.addAnnot(x)},e.prototype.needsAppearancesUpdate=function(){var t;if(this.isDirty())return!0;for(var r=this.acroField.getWidgets(),i=0,o=r.length;i<o;i++){var a=r[i],l=((t=a.getAppearances())===null||t===void 0?void 0:t.normal)instanceof Gl;if(!l)return!0}return!1},e.prototype.defaultUpdateAppearances=function(t){Ie(t,"font",[[Yl,"PDFFont"]]),this.updateAppearances(t)},e.prototype.updateAppearances=function(t,r){Ie(t,"font",[[Yl,"PDFFont"]]),mt(r,"provider",[Function]);for(var i=this.acroField.getWidgets(),o=0,a=i.length;o<a;o++){var l=i[o];this.updateWidgetAppearance(l,t,r)}},e.prototype.updateWidgetAppearance=function(t,r,i){var o=i??xce,a=_1(o(this,t,r));this.updateWidgetAppearanceWithFont(t,r,a)},e.of=function(t,r,i){return new e(t,r,i)},e}(N0);function Tce(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(r){if(r!=="default"&&!(r in n)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}})}),Object.freeze(n)}function Qq(n,e){return new Promise(function(t,r){let i;return Fce(n).then(function(o){try{return i=o,t(new Blob([e.slice(0,2),i,e.slice(2)],{type:"image/jpeg"}))}catch(a){return r(a)}},r)})}const Fce=n=>new 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<p;g+=12)if(o.getUint16(g,u)==274){if(o.getUint16(g+2,u)!==3)return t("Orientation data type is invalid");if(o.getUint32(g+4,u)!==1)return t("Orientation data count is invalid");o.setUint16(g+8,1,u);break}return e(i.slice(a,a+2+d))}a+=2+d}return e(new Blob)}),r.readAsArrayBuffer(n)});var pT={},Dce={get exports(){return pT},set exports(n){pT=n}};(function(n){var e,t,r={};Dce.exports=r,r.parse=function(i,o){for(var a=r.bin.readUshort,l=r.bin.readUint,d=0,c={},u=new Uint8Array(i),f=u.length-4;l(u,f)!=101010256;)f--;d=f,d+=4;var p=a(u,d+=4);a(u,d+=2);var g=l(u,d+=2),m=l(u,d+=4);d+=4,d=m;for(var y=0;y<p;y++){l(u,d),d+=4,d+=4,d+=4,l(u,d+=4),g=l(u,d+=4);var v=l(u,d+=4),x=a(u,d+=4),w=a(u,d+2),S=a(u,d+4);d+=6;var _=l(u,d+=8);d+=4,d+=x+w+S,r._readLocal(u,_,c,g,v,o)}return c},r._readLocal=function(i,o,a,l,d,c){var u=r.bin.readUshort,f=r.bin.readUint;f(i,o),u(i,o+=4),u(i,o+=2);var p=u(i,o+=2);f(i,o+=2),f(i,o+=4),o+=4;var g=u(i,o+=8),m=u(i,o+=2);o+=2;var y=r.bin.readUTF8(i,o,g);if(o+=g,o+=m,c)a[y]={size:d,csize:l};else{var v=new Uint8Array(i.buffer,o);if(p==0)a[y]=new Uint8Array(v.buffer.slice(o,o+l));else{if(p!=8)throw"unknown compression method: "+p;var x=new Uint8Array(d);r.inflateRaw(v,x),a[y]=x}}},r.inflateRaw=function(i,o){return r.F.inflate(i,o)},r.inflate=function(i,o){return i[0],i[1],r.inflateRaw(new Uint8Array(i.buffer,i.byteOffset+2,i.length-6),o)},r.deflate=function(i,o){o==null&&(o={level:6});var a=0,l=new Uint8Array(50+Math.floor(1.1*i.length));l[a]=120,l[a+1]=156,a+=2,a=r.F.deflateRaw(i,l,a,o.level);var d=r.adler(i,0,i.length);return l[a+0]=d>>>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<l;d++)i=r.crc.table[255&(i^o[a+d])]^i>>>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<u;){for(var f=Math.min(c+5552,u);c<f;)d+=l+=i[c++];l%=65521,d%=65521}return d<<16|l},r.bin={readUshort:function(i,o){return i[o]|i[o+1]<<8},writeUshort:function(i,o,a){i[o]=255&a,i[o+1]=a>>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<a;d++)l+=String.fromCharCode(i[o+d]);return l},writeASCII:function(i,o,a){for(var l=0;l<a.length;l++)i[o+l]=a.charCodeAt(l)},pad:function(i){return i.length<2?"0"+i:i},readUTF8:function(i,o,a){for(var l,d="",c=0;c<a;c++)d+="%"+r.bin.pad(i[o+c].toString(16));try{l=decodeURIComponent(d)}catch{return r.bin.readASCII(i,o,a)}return l},writeUTF8:function(i,o,a){for(var l=a.length,d=0,c=0;c<l;c++){var u=a.charCodeAt(c);if(!(4294967168&u))i[o+d]=u,d++;else if(!(4294965248&u))i[o+d]=192|u>>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<o;l++){var d=i.charCodeAt(l);if(!(4294967168&d))a++;else if(!(4294965248&d))a+=2;else if(!(4294901760&d))a+=3;else{if(4292870144&d)throw"e";a+=4}}return a}},r.F={},r.F.deflateRaw=function(i,o,a,l){var d=[[0,0,0,0,0],[4,4,8,4,0],[4,5,16,8,0],[4,6,16,16,0],[4,10,16,32,0],[8,16,32,32,0],[8,16,128,128,0],[8,32,128,256,0],[32,128,258,1024,1],[32,258,258,4096,1]][l],c=r.F.U,u=r.F._goodIndex;r.F._hash;var f=r.F._putsE,p=0,g=a<<3,m=0,y=i.length;if(l==0){for(;p<y;)f(o,g,p+(P=Math.min(65535,y-p))==y?1:0),g=r.F._copyExact(i,p,P,o,g+8),p+=P;return g>>>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;p<y;p++){if(T=F,p+1<y-2){F=r.F._hash(i,p+1);var A=p+1&32767;w[A]=x[F],x[F]=A}if(m<=p){(S>14e3||_>26697)&&y-p>100&&(m<p&&(v[S]=p-m,S+=2,m=p),g=r.F._writeBlock(p==y-1||m==y?1:0,v,S,C,i,b,p-b,o,g),S=_=C=0,b=p);var D=0;p<y-2&&(D=r.F._bestMatch(i,p,w,T,Math.min(d[2],y-p),d[3]));var P=D>>>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<p&&(v[S]=p-m,S+=2,m=p),g=r.F._writeBlock(1,v,S,C,i,b,p-b,o,g),S=0,_=0,S=_=C=0,b=p);7&g;)g++;return g>>>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+2<v&&(v=p+2);for(var x=0,w=0;w<v-2;w++){var S=o-p+w+32768&32767,_=S-a[S]+32768&32767;_>x&&(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<d&&i[o]==i[o-a];)o++;return o-l},r.F._hash=function(i,o){return(i[o]<<8|i[o+1])+(i[o+2]<<4)&65535},r.saved=0,r.F._writeBlock=function(i,o,a,l,d,c,u,f,p){var g,m,y,v,x,w,S,_,b,C=r.F.U,T=r.F._putsF,F=r.F._putsE;C.lhst[256]++,m=(g=r.F.getTrees())[0],y=g[1],v=g[2],x=g[3],w=g[4],S=g[5],_=g[6],b=g[7];var A=32+(p+3&7?8-(p+3&7):0)+(u<<3),D=l+r.F.contSize(C.fltree,C.lhst)+r.F.contSize(C.fdtree,C.dhst),P=l+r.F.contSize(C.ltree,C.lhst)+r.F.contSize(C.dtree,C.dhst);P+=14+3*S+r.F.contSize(C.itree,C.ihst)+(2*C.ihst[16]+3*C.ihst[17]+7*C.ihst[18]);for(var L=0;L<286;L++)C.lhst[L]=0;for(L=0;L<30;L++)C.dhst[L]=0;for(L=0;L<19;L++)C.ihst[L]=0;var W=A<D&&A<P?0:D<P?1:2;if(T(f,p,i),T(f,p+1,W),p+=3,W==0){for(;7&p;)p++;p=r.F._copyExact(d,c,u,f,p)}else{var O,U;if(W==1&&(O=C.fltree,U=C.fdtree),W==2){r.F.makeCodes(C.ltree,m),r.F.revCodes(C.ltree,m),r.F.makeCodes(C.dtree,y),r.F.revCodes(C.dtree,y),r.F.makeCodes(C.itree,v),r.F.revCodes(C.itree,v),O=C.ltree,U=C.dtree,F(f,p,x-257),F(f,p+=5,w-1),F(f,p+=5,S-4),p+=4;for(var M=0;M<S;M++)F(f,p+3*M,C.itree[1+(C.ordr[M]<<1)]);p+=3*S,p=r.F._codeTiny(_,C.itree,f,p),p=r.F._codeTiny(b,C.itree,f,p)}for(var I=c,H=0;H<a;H+=2){for(var z=o[H],G=z>>>23,te=I+(8388607&z);I<te;)p=r.F._writeLit(d[I++],O,f,p);if(G!=0){var re=o[H+1],me=re>>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;f<l.length;f+=2)i.ihst[l[f]]++;for(f=0;f<c.length;f+=2)i.ihst[c[f]]++;for(var p=r.F._hufTree(i.ihst,i.itree,7),g=19;g>4&&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<i.length;a+=2)o.push(i[a+1]);return o},r.F.nonZero=function(i){for(var o="",a=0;a<i.length;a+=2)i[a+1]!=0&&(o+=(a>>1)+",");return o},r.F.contSize=function(i,o){for(var a=0,l=0;l<o.length;l++)a+=o[l]*i[1+(l<<1)];return a},r.F._codeTiny=function(i,o,a,l){for(var d=0;d<i.length;d+=2){var c=i[d],u=i[d+1];l=r.F._writeLit(c,o,a,l);var f=c==16?2:c==17?3:7;c>15&&(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<a;l+=2){var d=i[l+1],c=l+3<a?i[l+3]:-1,u=l+5<a?i[l+5]:-1,f=l==0?-1:i[l-1];if(d==0&&c==d&&u==d){for(var p=l+5;p+2<a&&i[p+2]==d;)p+=2;(g=Math.min(p+1-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<a&&i[p+2]==d;)p+=2;var g=Math.min(p+1-l>>>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;u<c;u+=2)o[u]=0,o[u+1]=0;for(u=0;u<d;u++)i[u]!=0&&l.push({lit:u,f:i[u]});var f=l.length,p=l.slice(0);if(f==0)return 0;if(f==1){var g=l[0].lit;return p=g==0?1:0,o[1+(g<<1)]=1,o[1+(p<<1)]=1,1}l.sort(function(_,b){return _.f-b.f});var m=l[0],y=l[1],v=0,x=1,w=2;for(l[0]={lit:-1,f:m.f+y.f,l:m,r:y,d:0};x!=f-1;)m=v!=x&&(w==f||l[v].f<l[w].f)?l[v++]:l[w++],y=v!=x&&(w==f||l[v].f<l[w].f)?l[v++]:l[w++],l[x++]={lit:-1,f:m.f+y.f,l:m,r:y};var S=r.F.setDepth(l[x-1],0);for(S>a&&(r.F.restrictDepth(p,a,S),S=a),u=0;u<f;u++)o[1+(p[u].lit<<1)]=p[u].d;return S},r.F.setDepth=function(i,o){return i.lit!=-1?(i.d=o,o):Math.max(r.F.setDepth(i.l,o+1),r.F.setDepth(i.r,o+1))},r.F.restrictDepth=function(i,o,a){var l=0,d=1<<a-o,c=0;for(i.sort(function(f,p){return p.d==f.d?f.f-p.f:p.d-f.d}),l=0;l<i.length&&i[l].d>o;l++){var u=i[l].d;i[l].d=o,c+=d-(1<<a-u)}for(c>>>=a-o;c>0;)(u=i[l].d)<o?(i[l].d++,c-=1<<o-u-1):l++;for(;l>=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;P<C;P++){var W=c(i,D+3*P,3);m.itree[1+(m.ordr[P]<<1)]=W,W>L&&(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<<L)-1,_+b,i,D,m.ttree);var O=l._copyOut(m.ttree,0,_,m.ltree);T=(1<<O)-1;var U=l._copyOut(m.ttree,_,b,m.dtree);F=(1<<U)-1,f(m.ltree,O),p(m.ltree,O,v),f(m.dtree,U),p(m.dtree,U,x)}for(;;){var M=v[g(i,D)&T];D+=15&M;var I=M>>>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<H;)o[A]=o[A++-me],o[A]=o[A++-me],o[A]=o[A++-me],o[A]=o[A++-me];A=H}}}else{7&D&&(D+=8-(7&D));var J=4+(D>>>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<a;){var g=i[f(l,d)&o];d+=15&g;var m=g>>>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<x;)c[p]=y,p++}}return d},r.F._copyOut=function(i,o,a,l){for(var d=0,c=0,u=l.length>>>1;c<a;){var f=i[c+o];l[c<<1]=0,l[1+(c<<1)]=f,f>d&&(d=f),c++}for(;c<u;)l[c<<1]=0,l[1+(c<<1)]=0,c++;return d},r.F.makeCodes=function(i,o){for(var a,l,d,c,u=r.F.U,f=i.length,p=u.bl_count,g=0;g<=o;g++)p[g]=0;for(g=1;g<f;g+=2)p[i[g]]++;var m=u.next_code;for(a=0,p[0]=0,l=1;l<=o;l++)a=a+p[l-1]<<1,m[l]=a;for(d=0;d<f;d+=2)(c=i[d+1])!=0&&(i[d]=m[c],m[c]++)},r.F.codes2map=function(i,o,a){for(var l=i.length,d=r.F.U.rev15,c=0;c<l;c+=2)if(i[c+1]!=0)for(var u=c>>1,f=i[c+1],p=u<<4|f,g=o-f,m=i[c]<<g,y=m+(1<<g);m!=y;)a[d[m]>>>15-o]=p,m++},r.F.revCodes=function(i,o){for(var a=r.F.U.rev15,l=15-o,d=0;d<i.length;d+=2){var c=i[d]<<o-i[d+1];i[d]=a[c]>>>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<<a)-1},r.F._bitsF=function(i,o,a){return(i[o>>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16)>>>(7&o)&(1<<a)-1},r.F._get17=function(i,o){return(i[o>>>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;m<p;m++)g+=String.fromCharCode(u[f+m]);return g},writeASCII(u,f,p){for(let g=0;g<p.length;g++)u[f+g]=p.charCodeAt(g)},readBytes(u,f,p){const g=[];for(let m=0;m<p;m++)g.push(u[f+m]);return g},pad:u=>u.length<2?`0${u}`:u,readUTF8(u,f,p){let g,m="";for(let y=0;y<p;y++)m+=`%${n.pad(u[f+y].toString(16))}`;try{g=decodeURIComponent(m)}catch{return n.readASCII(u,f,p)}return g}};function e(u,f,p,g){const m=f*p,y=o(g),v=Math.ceil(f*y/8),x=new Uint8Array(4*m),w=new Uint32Array(x.buffer),{ctype:S}=g,{depth:_}=g,b=n.readUshort;if(S==6){const z=m<<2;if(_==8)for(var C=0;C<z;C+=4)x[C]=u[C],x[C+1]=u[C+1],x[C+2]=u[C+2],x[C+3]=u[C+3];if(_==16)for(C=0;C<z;C++)x[C]=u[C<<1]}else if(S==2){const z=g.tabs.tRNS;if(z==null){if(_==8)for(C=0;C<m;C++){var T=3*C;w[C]=255<<24|u[T+2]<<16|u[T+1]<<8|u[T]}if(_==16)for(C=0;C<m;C++)T=6*C,w[C]=255<<24|u[T+4]<<16|u[T+2]<<8|u[T]}else{var F=z[0];const G=z[1],te=z[2];if(_==8)for(C=0;C<m;C++){var A=C<<2;T=3*C,w[C]=255<<24|u[T+2]<<16|u[T+1]<<8|u[T],u[T]==F&&u[T+1]==G&&u[T+2]==te&&(x[A+3]=0)}if(_==16)for(C=0;C<m;C++)A=C<<2,T=6*C,w[C]=255<<24|u[T+4]<<16|u[T+2]<<8|u[T],b(u,T)==F&&b(u,T+2)==G&&b(u,T+4)==te&&(x[A+3]=0)}}else if(S==3){const z=g.tabs.PLTE,G=g.tabs.tRNS,te=G?G.length:0;if(_==1)for(var D=0;D<p;D++){var P=D*v,L=D*f;for(C=0;C<f;C++){A=L+C<<2;var W=3*(O=u[P+(C>>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<te?G[O]:255}}if(_==2)for(D=0;D<p;D++)for(P=D*v,L=D*f,C=0;C<f;C++)A=L+C<<2,W=3*(O=u[P+(C>>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<te?G[O]:255;if(_==4)for(D=0;D<p;D++)for(P=D*v,L=D*f,C=0;C<f;C++)A=L+C<<2,W=3*(O=u[P+(C>>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<te?G[O]:255;if(_==8)for(C=0;C<m;C++){var O;A=C<<2,W=3*(O=u[C]),x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O<te?G[O]:255}}else if(S==4){if(_==8)for(C=0;C<m;C++){A=C<<2;var U=u[M=C<<1];x[A]=U,x[A+1]=U,x[A+2]=U,x[A+3]=u[M+1]}if(_==16)for(C=0;C<m;C++){var M;A=C<<2,U=u[M=C<<2],x[A]=U,x[A+1]=U,x[A+2]=U,x[A+3]=u[M+2]}}else if(S==0)for(F=g.tabs.tRNS?g.tabs.tRNS:-1,D=0;D<p;D++){const z=D*v,G=D*f;if(_==1)for(var I=0;I<f;I++){var H=(U=255*(u[z+(I>>>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<f;I++)H=(U=85*(u[z+(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<f;I++)H=(U=17*(u[z+(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<f;I++)H=(U=u[z+I])==F?0:255,w[G+I]=H<<24|U<<16|U<<8|U;else if(_==16)for(I=0;I<f;I++)U=u[z+(I<<1)],H=b(u,z+(I<<1))==F?0:255,w[G+I]=H<<24|U<<16|U<<8|U}return x}function t(u,f,p,g){const m=o(u),y=Math.ceil(p*m/8),v=new Uint8Array((y+1+u.interlace)*g);return f=u.tabs.CgBI?i(f,v):r(f,v),u.interlace==0?f=a(f,u,0,p,g):u.interlace==1&&(f=function(w,S){const _=S.width,b=S.height,C=o(S),T=C>>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<b;)te+=I,G++;let re=L[U];for(;re<_;)re+=H,z++;const me=Math.ceil(z*C/8);a(w,S,D,z,G);let J=0,ne=P[U];for(;ne<b;){let ye=L[U],ke=D+J*me<<3;for(;ye<_;){var M;if(C==1&&(M=(M=w[ke>>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<T;De++)A[Ye+De]=w[(ke>>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<<z)-1,w+S,f,F,M.v);const G=A.V(M.v,0,w,M.C);b=(1<<G)-1;const te=A.V(M.v,w,S,M.D);C=(1<<te)-1,W(M.C,G),O(M.C,G,m),W(M.D,te),O(M.D,te,y)}for(;;){const z=m[U(f,F)&b];F+=15&z;const G=z>>>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<te;)p[T]=p[T++-ne],p[T]=p[T++-ne],p[T]=p[T++-ne],p[T]=p[T++-ne];T=te}}}}else{7&F&&(F+=8-(7&F));const z=4+(F>>>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<g;){const _=f[w(m,y)&p];y+=15&_;const b=_>>>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<F;)v[S]=C,S++}}return y},u.H.V=function(f,p,g,m){let y=0,v=0;const x=m.length>>>1;for(;v<g;){const w=f[v+p];m[v<<1]=0,m[1+(v<<1)]=w,w>y&&(y=w),v++}for(;v<x;)m[v<<1]=0,m[1+(v<<1)]=0,v++;return y},u.H.n=function(f,p){const g=u.H.m,m=f.length;let y,v,x,w;const S=g.j;for(var _=0;_<=p;_++)S[_]=0;for(_=1;_<m;_+=2)S[f[_]]++;const b=g.K;for(y=0,S[0]=0,v=1;v<=p;v++)y=y+S[v-1]<<1,b[v]=y;for(x=0;x<m;x+=2)w=f[x+1],w!=0&&(f[x]=b[w],b[w]++)},u.H.A=function(f,p,g){const m=f.length,y=u.H.m.r;for(let v=0;v<m;v+=2)if(f[v+1]!=0){const x=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<f.length;y+=2){const v=f[y]<<p-f[y+1];f[y]=g[v]>>>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<<g)-1},u.H.b=function(f,p,g){return(f[p>>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16)>>>(7&p)&(1<<g)-1},u.H.Z=function(f,p){return(f[p>>>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;_<v;_++)u[_+1]=u[_+1]+(u[_+1-y]>>>1)&255;for(let b=0;b<m;b++)if(x=p+b*v,w=x+b+1,S=u[w-1],_=0,S==0)for(;_<v;_++)u[x+_]=u[w+_];else if(S==1){for(;_<y;_++)u[x+_]=u[w+_];for(;_<v;_++)u[x+_]=u[w+_]+u[x+_-y]}else if(S==2)for(;_<v;_++)u[x+_]=u[w+_]+u[x+_-v];else if(S==3){for(;_<y;_++)u[x+_]=u[w+_]+(u[x+_-v]>>>1);for(;_<v;_++)u[x+_]=u[w+_]+(u[x+_-v]+u[x+_-y]>>>1)}else{for(;_<y;_++)u[x+_]=u[w+_]+l(0,u[x+_-v],0);for(;_<v;_++)u[x+_]=u[w+_]+l(u[x+_-y],u[x+_-v],u[x+_-y-v])}return u}function l(u,f,p){const g=u+f-p,m=g-u,y=g-f,v=g-p;return m*m<=y*y&&m*m<=v*v?u:y*y<=v*v?f:p}function d(u,f,p){p.width=n.readUint(u,f),f+=4,p.height=n.readUint(u,f),f+=4,p.depth=u[f],f++,p.ctype=u[f],f++,p.compress=u[f],f++,p.filter=u[f],f++,p.interlace=u[f],f++}function c(u,f,p,g,m,y,v,x,w){const S=Math.min(f,m),_=Math.min(p,y);let b=0,C=0;for(let U=0;U<_;U++)for(let M=0;M<S;M++)if(v>=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<p.length;){const U=m.readUint(p,g);g+=4;const M=m.readASCII(p,g,4);if(g+=4,M=="IHDR")d(p,g,x);else if(M=="iCCP"){for(var F=g;p[F]!=0;)F++;m.readASCII(p,g,F-g),p[F+1];const I=p.slice(F+2,g+U);let H=null;try{H=r(I)}catch{H=i(I)}x.tabs[M]=H}else if(M=="CgBI")x.tabs[M]=p.slice(g,g+4);else if(M=="IDAT"){for(T=0;T<U;T++)w[_+T]=p[g+T];_+=U}else if(M=="acTL")x.tabs[M]={num_frames:v(p,g),num_plays:v(p,g+4)},S=new Uint8Array(p.length);else if(M=="fcTL"){b!=0&&((O=x.frames[x.frames.length-1]).data=t(x,S.slice(0,b),O.rect.width,O.rect.height),b=0);const I={x:v(p,g+12),y:v(p,g+16),width:v(p,g+4),height:v(p,g+8)};let H=y(p,g+22);H=y(p,g+20)/(H==0?100:H);const z={rect:I,delay:Math.round(1e3*H),dispose:p[g+24],blend:p[g+25]};x.frames.push(z)}else if(M=="fdAT"){for(T=0;T<U-4;T++)S[b+T]=p[g+T+4];b+=U-4}else if(M=="pHYs")x.tabs[M]=[m.readUint(p,g),m.readUint(p,g+4),p[g+8]];else if(M=="cHRM")for(x.tabs[M]=[],T=0;T<8;T++)x.tabs[M].push(m.readUint(p,g+4*T));else if(M=="tEXt"||M=="zTXt"){x.tabs[M]==null&&(x.tabs[M]={});var A=m.nextZero(p,g),D=m.readASCII(p,g,A-g),P=g+U-A-1;if(M=="tEXt")W=m.readASCII(p,A+1,P);else{var L=r(p.slice(A+2,A+2+P));W=m.readUTF8(L,0,L.length)}x.tabs[M][D]=W}else if(M=="iTXt"){x.tabs[M]==null&&(x.tabs[M]={}),A=0,F=g,A=m.nextZero(p,F),D=m.readASCII(p,F,A-F);const I=p[F=A+1];var W;p[F+1],F+=2,A=m.nextZero(p,F),m.readASCII(p,F,A-F),F=A+1,A=m.nextZero(p,F),m.readUTF8(p,F,A-F),P=U-((F=A+1)-g),I==0?W=m.readUTF8(p,F,P):(L=r(p.slice(F,F+P)),W=m.readUTF8(L,0,L.length)),x.tabs[M][D]=W}else if(M=="PLTE")x.tabs[M]=m.readBytes(p,g,U);else if(M=="hIST"){const I=x.tabs.PLTE.length/3;for(x.tabs[M]=[],T=0;T<I;T++)x.tabs[M].push(y(p,g+2*T))}else if(M=="tRNS")x.ctype==3?x.tabs[M]=m.readBytes(p,g,U):x.ctype==0?x.tabs[M]=y(p,g):x.ctype==2&&(x.tabs[M]=[y(p,g),y(p,g+2),y(p,g+4)]);else if(M=="gAMA")x.tabs[M]=m.readUint(p,g)/1e5;else if(M=="sRGB")x.tabs[M]=p[g];else if(M=="bKGD")x.ctype==0||x.ctype==4?x.tabs[M]=[y(p,g)]:x.ctype==2||x.ctype==6?x.tabs[M]=[y(p,g),y(p,g+2),y(p,g+4)]:x.ctype==3&&(x.tabs[M]=p[g]);else if(M=="IEND")break;g+=U,m.readUint(p,g),g+=4}var O;return b!=0&&((O=x.frames[x.frames.length-1]).data=t(x,S.slice(0,b),O.rect.width,O.rect.height)),x.data=t(x,w,x.width,x.height),delete x.compress,delete x.interlace,delete x.filter,x},toRGBA8:function(f){const p=f.width,g=f.height;if(f.tabs.acTL==null)return[e(f.data,p,g,f).buffer];const m=[];f.frames[0].data==null&&(f.frames[0].data=f.data);const y=p*g*4,v=new Uint8Array(y),x=new Uint8Array(y),w=new Uint8Array(y);for(let _=0;_<f.frames.length;_++){const b=f.frames[_],C=b.rect.x,T=b.rect.y,F=b.rect.width,A=b.rect.height,D=e(b.data,F,A,f);if(_!=0)for(var S=0;S<y;S++)w[S]=v[S];if(b.blend==0?c(D,F,A,v,p,g,C,T,0):b.blend==1&&c(D,F,A,v,p,g,C,T,1),m.push(v.buffer.slice(0)),b.dispose!=0){if(b.dispose==1)c(x,F,A,v,p,g,C,T,0);else if(b.dispose==2)for(S=0;S<y;S++)v[S]=w[S]}}return m},_paeth:l,_copyTile:c,_bin:n}}();(function(){const{_copyTile:n}=rc,{_bin:e}=rc,t=rc._paeth;var r={table:function(){const F=new Uint32Array(256);for(let A=0;A<256;A++){let D=A;for(let P=0;P<8;P++)1&D?D=3988292384^D>>>1:D>>>=1;F[A]=D}return F}(),update(F,A,D,P){for(let L=0;L<P;L++)F=r.table[255&(F^A[D+L])]^F>>>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<U;I++){const ne=P[I];M.push([ne>>>0&255,ne>>>8&255,ne>>>16&255,ne>>>24&255])}for(I=0;I<U;I++){let ne=4294967295;for(var H=0,z=0;z<U;z++){var G=a(M[I],M[z]);z!=I&&G<ne&&(ne=G,H=z)}}const te=new Uint32Array(L.buffer),re=new Int16Array(A*D*4),me=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5];for(I=0;I<me.length;I++)me[I]=255*((me[I]+.5)/16-.5);for(let ne=0;ne<D;ne++)for(let ye=0;ye<A;ye++){var J;I=4*(ne*A+ye),O!=2?J=[o(F[I]+re[I]),o(F[I+1]+re[I+1]),o(F[I+2]+re[I+2]),o(F[I+3]+re[I+3])]:(G=me[4*(3&ne)+(3&ye)],J=[o(F[I]+G),o(F[I+1]+G),o(F[I+2]+G),o(F[I+3]+G)]),H=0;let ke=16777215;for(z=0;z<U;z++){const qe=a(J,M[z]);qe<ke&&(ke=qe,H=z)}const Ye=M[H],De=[J[0]-Ye[0],J[1]-Ye[1],J[2]-Ye[2],J[3]-Ye[3]];O==1&&(ye!=A-1&&i(De,re,I+4,7),ne!=D-1&&(ye!=0&&i(De,re,I+4*A-4,3),i(De,re,I+4*A,5),ye!=A-1&&i(De,re,I+4*A+4,1))),W[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<re;me++)F.plte[me]>>>24!=255&&(G=!0);te+=8+3*re+4+(G?8+1*re+4:0)}for(var J=0;J<F.frames.length;J++)H&&(te+=38),te+=(Ye=F.frames[J]).cimg.length+12,J!=0&&(te+=4);te+=12;const ne=new Uint8Array(te),ye=[137,80,78,71,13,10,26,10];for(me=0;me<8;me++)ne[me]=ye[me];if(O(ne,I,13),I+=4,M(ne,I,"IHDR"),I+=4,O(ne,I,A),I+=4,O(ne,I,D),I+=4,ne[I]=F.depth,I++,ne[I]=F.ctype,I++,ne[I]=0,I++,ne[I]=0,I++,ne[I]=0,I++,O(ne,I,W(ne,I-17,17)),I+=4,L.sRGB!=null&&(O(ne,I,1),I+=4,M(ne,I,"sRGB"),I+=4,ne[I]=L.sRGB,I++,O(ne,I,W(ne,I-5,5)),I+=4),L.iCCP!=null){const De=13+z.length;O(ne,I,De),I+=4,M(ne,I,"iCCP"),I+=4,M(ne,I,"ICC profile"),I+=11,I+=2,ne.set(z,I),I+=z.length,O(ne,I,W(ne,I-(De+4),De+4)),I+=4}if(L.pHYs!=null&&(O(ne,I,9),I+=4,M(ne,I,"pHYs"),I+=4,O(ne,I,L.pHYs[0]),I+=4,O(ne,I,L.pHYs[1]),I+=4,ne[I]=L.pHYs[2],I++,O(ne,I,W(ne,I-13,13)),I+=4),H&&(O(ne,I,8),I+=4,M(ne,I,"acTL"),I+=4,O(ne,I,F.frames.length),I+=4,O(ne,I,L.loop!=null?L.loop:0),I+=4,O(ne,I,W(ne,I-12,12)),I+=4),F.ctype==3){for(O(ne,I,3*(re=F.plte.length)),I+=4,M(ne,I,"PLTE"),I+=4,me=0;me<re;me++){const De=3*me,qe=F.plte[me],ue=255&qe,Ze=qe>>>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<re;me++)ne[I+me]=F.plte[me]>>>24&255;I+=re,O(ne,I,W(ne,I-re-4,re+4)),I+=4}}let ke=0;for(J=0;J<F.frames.length;J++){var Ye=F.frames[J];H&&(O(ne,I,26),I+=4,M(ne,I,"fcTL"),I+=4,O(ne,I,ke++),I+=4,O(ne,I,Ye.rect.width),I+=4,O(ne,I,Ye.rect.height),I+=4,O(ne,I,Ye.rect.x),I+=4,O(ne,I,Ye.rect.y),I+=4,U(ne,I,P[J]),I+=2,U(ne,I,1e3),I+=2,ne[I]=Ye.dispose,I++,ne[I]=Ye.blend,I++,O(ne,I,W(ne,I-30,30)),I+=4);const De=Ye.cimg;O(ne,I,(re=De.length)+(J==0?0:4)),I+=4;const qe=I;M(ne,I,J==0?"IDAT":"fdAT"),I+=4,J!=0&&(O(ne,I,ke++),I+=4),ne.set(De,I),I+=re,O(ne,I,W(ne,qe,I-qe)),I+=4}return O(ne,I,0),I+=4,M(ne,I,"IEND"),I+=4,O(ne,I,W(ne,I-4,4)),I+=4,ne.buffer}function c(F,A,D){for(let P=0;P<F.frames.length;P++){const L=F.frames[P];L.rect.width;const W=L.rect.height,O=new Uint8Array(W*L.bpl+W);L.cimg=g(L.img,W,L.bpp,L.bpl,O,A,D)}}function u(F,A,D,P,L){const W=L[0],O=L[1],U=L[2],M=L[3],I=L[4],H=L[5];let z=6,G=8,te=255;for(var re=0;re<F.length;re++){const Te=new Uint8Array(F[re]);for(var me=Te.length,J=0;J<me;J+=4)te&=Te[J+3]}const ne=te!=255,ye=function(Be,he,He,Ge,ae,K){const de=[];for(var Y=0;Y<Be.length;Y++){const st=new Uint8Array(Be[Y]),Ve=new Uint32Array(st.buffer);var Q;let Re=0,Le=0,rt=he,$e=He,ce=Ge?1:0;if(Y!=0){const Je=K||Ge||Y==1||de[Y-2].dispose!=0?1:2;let jt=0,ct=1e9;for(let Se=0;Se<Je;Se++){var X=new Uint8Array(Be[Y-1-Se]);const ot=new Uint32Array(Be[Y-1-Se]);let ut=he,Ot=He,An=-1,on=-1;for(let Rt=0;Rt<He;Rt++)for(let vt=0;vt<he;vt++)Ve[we=Rt*he+vt]!=ot[we]&&(vt<ut&&(ut=vt),vt>An&&(An=vt),Rt<Ot&&(Ot=Rt),Rt>on&&(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<ct&&(ct=Ke,jt=Se,Re=ut,Le=Ot,rt=An-ut+1,$e=on-Ot+1)}X=new Uint8Array(Be[Y-1-jt]),jt==1&&(de[Y-1].dispose=2),Q=new Uint8Array(rt*$e*4),n(X,he,He,Q,rt,$e,-Re,-Le,0),ce=n(st,he,He,Q,rt,$e,-Re,-Le,3)?1:0,ce==1?p(st,he,He,Q,{x:Re,y:Le,width:rt,height:$e}):n(st,he,He,Q,rt,$e,-Re,-Le,0)}else Q=st.slice(0);de.push({rect:{x:Re,y:Le,width:rt,height:$e},img:Q,blend:ce,dispose:0})}if(Ge)for(Y=0;Y<de.length;Y++){if((Ne=de[Y]).blend==1)continue;const st=Ne.rect,Ve=de[Y-1].rect,Re=Math.min(st.x,Ve.x),Le=Math.min(st.y,Ve.y),rt={x:Re,y:Le,width:Math.max(st.x+st.width,Ve.x+Ve.width)-Re,height:Math.max(st.y+st.height,Ve.y+Ve.height)-Le};de[Y-1].dispose=1,Y-1!=0&&f(Be,he,He,de,Y-1,rt,ae),f(Be,he,He,de,Y,rt,ae)}let pe=0;if(Be.length!=1)for(var we=0;we<de.length;we++){var Ne;pe+=(Ne=de[we]).rect.width*Ne.rect.height}return de}(F,A,D,W,O,U),ke={},Ye=[],De=[];if(P!=0){const Te=[];for(J=0;J<ye.length;J++)Te.push(ye[J].img.buffer);const Be=function(ae){let K=0;for(var de=0;de<ae.length;de++)K+=ae[de].byteLength;const Y=new Uint8Array(K);let Q=0;for(de=0;de<ae.length;de++){const X=new Uint8Array(ae[de]),pe=X.length;for(let we=0;we<pe;we+=4){let Ne=X[we],st=X[we+1],Ve=X[we+2];const Re=X[we+3];Re==0&&(Ne=st=Ve=0),Y[Q+we]=Ne,Y[Q+we+1]=st,Y[Q+we+2]=Ve,Y[Q+we+3]=Re}Q+=pe}return Y.buffer}(Te),he=y(Be,P);for(J=0;J<he.plte.length;J++)Ye.push(he.plte[J].est.rgba);let He=0;for(J=0;J<ye.length;J++){const Ge=(ue=ye[J]).img.length;var qe=new Uint8Array(he.inds.buffer,He>>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;re<ye.length;re++){var ue=ye[re];const Te=new Uint32Array(ue.img.buffer);var Ze=ue.rect.width;for(me=Te.length,qe=new Uint8Array(me),De.push(qe),J=0;J<me;J++){const Be=Te[J];if(J!=0&&Be==Te[J-1])qe[J]=qe[J-1];else if(J>Ze&&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<ye.length;re++){(ue=ye[re]).rect.x,ue.rect.y,Ze=ue.rect.width;const Te=ue.rect.height;let Be=ue.img;new Uint32Array(Be.buffer);let he=4*Ze,He=4;if(ee<=256&&I==0){he=Math.ceil(G*Ze/8);var Z=new Uint8Array(he*Te);const Ge=De[re];for(let ae=0;ae<Te;ae++){J=ae*he;const K=ae*Ze;if(G==8)for(var ge=0;ge<Ze;ge++)Z[J+ge]=Ge[K+ge];else if(G==4)for(ge=0;ge<Ze;ge++)Z[J+(ge>>1)]|=Ge[K+ge]<<4-4*(1&ge);else if(G==2)for(ge=0;ge<Ze;ge++)Z[J+(ge>>2)]|=Ge[K+ge]<<6-2*(3&ge);else if(G==1)for(ge=0;ge<Ze;ge++)Z[J+(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;J<Ge;J++){const ae=3*J,K=4*J;Z[ae]=Be[K],Z[ae+1]=Be[K+1],Z[ae+2]=Be[K+2]}Be=Z,z=2,He=3,he=3*Ze}ue.img=Be,ue.bpl=he,ue.bpp=He}return{ctype:z,depth:G,plte:Ye,frames:ye}}function f(F,A,D,P,L,W,O){const U=Uint8Array,M=Uint32Array,I=new U(F[L-1]),H=new M(F[L-1]),z=L+1<F.length?new U(F[L+1]):null,G=new U(F[L]),te=new M(G.buffer);let re=A,me=D,J=-1,ne=-1;for(let ke=0;ke<W.height;ke++)for(let Ye=0;Ye<W.width;Ye++){const De=W.x+Ye,qe=W.y+ke,ue=qe*A+De,Ze=te[ue];Ze==0||P[L-1].dispose==0&&H[ue]==Ze&&(z==null||z[4*ue+3]!=0)||(De<re&&(re=De),De>J&&(J=De),qe<me&&(me=qe),qe>ne&&(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<I.length;z++){for(let re=0;re<A;re++)m(L,F,re,P,D,I[z]);U.push(H.deflate(L,M))}let G,te=1e9;for(z=0;z<U.length;z++)U[z].length<te&&(G=z,te=U[z].length);return U[G]}function m(F,A,D,P,L,W){const O=D*P;let U=O+D;if(F[U]=W,U++,W==0)if(P<500)for(var M=0;M<P;M++)F[U+M]=A[O+M];else F.set(new Uint8Array(A.buffer,O,P),U);else if(W==1){for(M=0;M<L;M++)F[U+M]=A[O+M];for(M=L;M<P;M++)F[U+M]=A[O+M]-A[O+M-L]+256&255}else if(D==0){for(M=0;M<L;M++)F[U+M]=A[O+M];if(W==2)for(M=L;M<P;M++)F[U+M]=A[O+M];if(W==3)for(M=L;M<P;M++)F[U+M]=A[O+M]-(A[O+M-L]>>1)+256&255;if(W==4)for(M=L;M<P;M++)F[U+M]=A[O+M]-t(A[O+M-L],0,0)+256&255}else{if(W==2)for(M=0;M<P;M++)F[U+M]=A[O+M]+256-A[O+M-P]&255;if(W==3){for(M=0;M<L;M++)F[U+M]=A[O+M]+256-(A[O+M-P]>>1)&255;for(M=L;M<P;M++)F[U+M]=A[O+M]+256-(A[O+M-P]+A[O+M-L]>>1)&255}if(W==4){for(M=0;M<L;M++)F[U+M]=A[O+M]+256-t(0,A[O+M-P],0)&255;for(M=L;M<P;M++)F[U+M]=A[O+M]+256-t(A[O+M-L],A[O+M-P],A[O+M-L-P])&255}}}function y(F,A){const D=new Uint8Array(F),P=D.slice(0),L=new Uint32Array(P.buffer),W=v(P,A),O=W[0],U=W[1],M=D.length,I=new Uint8Array(M>>2);let H;if(D.length<2e7)for(var z=0;z<M;z+=4)H=x(O,G=D[z]*(1/255),te=D[z+1]*(1/255),re=D[z+2]*(1/255),me=D[z+3]*(1/255)),I[z>>2]=H.ind,L[z>>2]=H.est.rgba;else for(z=0;z<M;z+=4){var G=D[z]*.00392156862745098,te=D[z+1]*(1/255),re=D[z+2]*(1/255),me=D[z+3]*(1/255);for(H=O;H.left;)H=w(H.est,G,te,re,me)<=0?H.left:H.right;I[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.length<A;){let U=0,M=0;for(var O=0;O<W.length;O++)W[O].est.L>U&&(U=W[O].est.L,M=O);if(U<D)break;const I=W[M],H=S(F,P,I.i0,I.i1,I.est.e,I.est.eMq255);if(I.i0>=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;O<W.length;O++)W[O].ind=O;return[L,W]}function x(F,A,D,P,L){if(F.left==null)return F.tdst=function(z,G,te,re,me){const J=G-z[0],ne=te-z[1],ye=re-z[2],ke=me-z[3];return J*J+ne*ne+ye*ye+ke*ke}(F.est.q,A,D,P,L),F;const W=w(F.est,A,D,P,L);let O=F.left,U=F.right;W>0&&(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.tdst<M.tdst?I:M}function w(F,A,D,P,L){const{e:W}=F;return W[0]*A+W[1]*D+W[2]*P+W[3]*L-F.eMq}function S(F,A,D,P,L,W){for(P-=4;D<P;){for(;_(F,D,L)<=W;)D+=4;for(;_(F,P,L)>W;)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<D;O+=4){const U=F[O]*.00392156862745098,M=F[O+1]*(1/255),I=F[O+2]*(1/255),H=F[O+3]*(1/255);L[0]+=U,L[1]+=M,L[2]+=I,L[3]+=H,P[0]+=U*U,P[1]+=U*M,P[2]+=U*I,P[3]+=U*H,P[5]+=M*M,P[6]+=M*I,P[7]+=M*H,P[10]+=I*I,P[11]+=I*H,P[15]+=H*H}return P[4]=P[1],P[8]=P[2],P[9]=P[6],P[12]=P[3],P[13]=P[7],P[14]=P[11],{R:P,m:L,N:W}}function C(F){const{R:A}=F,{m:D}=F,{N:P}=F,L=D[0],W=D[1],O=D[2],U=D[3],M=P==0?0:1/P,I=[A[0]-L*L*M,A[1]-L*W*M,A[2]-L*O*M,A[3]-L*U*M,A[4]-W*L*M,A[5]-W*W*M,A[6]-W*O*M,A[7]-W*U*M,A[8]-O*L*M,A[9]-O*W*M,A[10]-O*O*M,A[11]-O*U*M,A[12]-U*L*M,A[13]-U*W*M,A[14]-U*O*M,A[15]-U*U*M],H=I,z=T;let G=[Math.random(),Math.random(),Math.random(),Math.random()],te=0,re=0;if(P!=0)for(let J=0;J<16&&(G=z.multVec(H,G),re=Math.sqrt(z.dot(G,G)),G=z.sml(1/re,G),!(J!=0&&Math.abs(re-te)<1e-9));J++)te=re;const me=[L*M,W*M,O*M,U*M];return{Cov:I,q:me,e:G,L:te,eMq255:z.dot(z.sml(255,me),G),eMq:z.dot(G,me),rgba:(Math.round(255*me[3])<<24|Math.round(255*me[2])<<16|Math.round(255*me[1])<<8|Math.round(255*me[0])<<0)>>>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<A.length;G++)I.frames.push({rect:{x:0,y:0,width:D,height:P},img:new Uint8Array(A[G]),blend:0,dispose:1,bpp:Math.ceil(H/8),bpl:Math.ceil(z/8)});return c(I,0,!0),d(I,D,P,U,M)},rc.encode.compress=u,rc.encode.dither=l,rc.quantize=y,rc.quantize.getKDtree=v,rc.quantize.getNearest=x})();const $q={toArrayBuffer(n,e){const t=n.width,r=n.height,i=t<<2,o=n.getContext("2d").getImageData(0,0,t,r),a=new Uint32Array(o.data.buffer),l=(32*t+31)/32<<2,d=l*r,c=122+d,u=new ArrayBuffer(c),f=new DataView(u),p=1<<20;let g,m,y,v,x=p,w=0,S=0,_=0;function b(F){f.setUint16(S,F,!0),S+=2}function C(F){f.setUint32(S,F,!0),S+=4}function T(F){S+=F}b(19778),C(c),T(4),C(122),C(108),C(t),C(-r>>>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(;w<r&&x>0;){for(v=122+w*l,g=0;g<i;)x--,m=a[_++],y=m>>>24,f.setUint32(v+g,m<<8|y),g+=4;w++}_<a.length?(x=p,setTimeout(F,$q._dly)):e(u)}()},toBlob(n,e){this.toArrayBuffer(n,t=>{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<c?(o=c,i=c*l):(o=d*l,i=d),a=i*o}return{width:i,height:o}}function JF(n,e){let t,r;try{if(t=new OffscreenCanvas(n,e),r=t.getContext("2d"),r===null)throw new Error("getContext of OffscreenCanvas returns null")}catch{t=document.createElement("canvas"),r=t.getContext("2d")}return t.width=n,t.height=e,[t,r]}function rV(n,e){const{width:t,height:r}=nV(n.width,n.height),[i,o]=JF(t,r);return e&&/jpe?g/.test(e)&&(o.fillStyle="white",o.fillRect(0,0,i.width,i.height)),o.drawImage(n,0,0,i.width,i.height),i}function D5(){return D5.cachedResult!==void 0||(D5.cachedResult=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&typeof document<"u"&&"ontouchend"in document),D5.cachedResult}function mT(n,e={}){return new Promise(function(t,r){let i,o;var a=function(){try{return o=rV(i,e.fileType||n.type),t([i,o])}catch(d){return r(d)}},l=function(d){try{var c=function(u){try{throw u}catch(f){return r(f)}};try{let u;return eV(n).then(function(f){try{return u=f,tV(u).then(function(p){try{return i=p,function(){try{return a()}catch(g){return r(g)}}()}catch(g){return c(g)}},c)}catch(p){return c(p)}},c)}catch(u){c(u)}}catch(u){return r(u)}};try{if(D5()||[$a.DESKTOP_SAFARI,$a.MOBILE_SAFARI].includes(km()))throw new Error("Skip createImageBitmap on IOS and Safari");return createImageBitmap(n).then(function(d){try{return i=d,a()}catch{return l()}},l)}catch{l()}})}function yT(n,e,t,r,i=1){return new Promise(function(o,a){let l;if(e==="image/png"){let c,u,f;return c=n.getContext("2d"),{data:u}=c.getImageData(0,0,n.width,n.height),f=rc.encode([u.buffer],n.width,n.height,4096*i),l=new Blob([f],{type:e}),l.name=t,l.lastModified=r,d.call(this)}{let c=function(){return d.call(this)};if(e==="image/bmp")return new Promise(u=>$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(;l<a;){if(o.getUint16(l+2,!1)<=8)return e(-1);const d=o.getUint16(l,!1);if(l+=2,d==65505){if(o.getUint32(l+=2,!1)!=1165519206)return e(-1);const c=o.getUint16(l+=6,!1)==18761;l+=o.getUint32(l+4,c);const u=o.getUint16(l,c);l+=2;for(let f=0;f<u;f++)if(o.getUint16(l+12*f,c)==274)return e(o.getUint16(l+12*f+8,c))}else{if((65280&d)!=65280)break;l+=o.getUint16(l,!1)}}return e(-1)},r.onerror=i=>t(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<a.length;me++){y(`Compressing page ${me+1} of ${a.length}...`);const J=await bo(a[me].file,_),ne=new Image,ye=URL.createObjectURL(J);await new Promise(Ye=>{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<H.length;me++){y(`Adding page ${me+1} to PDF...`);const{data:J,width:ne,height:ye}=H[me],ke=await z.embedJpg(J);z.addPage([ne,ye]).drawImage(ke,{x:0,y:0,width:ne,height:ye})}y("Finalizing PDF...");const G=await z.save(),te=new Blob([G],{type:"application/pdf"}),re=new File([te],`invoice-${a.length}pages.pdf`,{type:"application/pdf"});L(re,!0)}catch(H){console.error("Processing error:",H),g(H instanceof Error?H.message:"Failed to process images"),f(!1),y("")}},M=()=>{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<t)return String.fromCharCode.apply(null,n);const r=[];for(let i=0;i<e;i+=t){const o=Math.min(i+t,e),a=n.subarray(i,o);r.push(String.fromCharCode.apply(null,a))}return r.join("")}function rD(n){typeof n!="string"&&Hr("Invalid argument for stringToBytes");const e=n.length,t=new Uint8Array(e);for(let r=0;r<e;++r)t[r]=n.charCodeAt(r)&255;return t}function Xce(){const n=new Uint8Array(4);return n[0]=1,new Uint32Array(n.buffer,0,1)[0]===1}class Ds{static get isLittleEndian(){return Cn(this,"isLittleEndian",Xce())}static get isOffscreenCanvasSupported(){return Cn(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Cn(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get isFloat16ArraySupported(){return Cn(this,"isFloat16ArraySupported",typeof Float16Array<"u")}static get isSanitizerSupported(){return Cn(this,"isSanitizerSupported",typeof Sanitizer<"u")}static get platform(){const{platform:e,userAgent:t}=navigator;return Cn(this,"platform",{isAndroid:t.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:t.includes("Firefox")})}static get isCSSRoundSupported(){var e,t;return Cn(this,"isCSSRoundSupported",(t=(e=globalThis.CSS)==null?void 0:e.supports)==null?void 0:t.call(e,"width: round(1.5px, 1px)"))}static get isAlphaColorInputSupported(){return Cn(this,"isAlphaColorInputSupported",(()=>{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<e&&n[t].trim()==="";)t++;return n.substring(t,t+5).toLowerCase()==="data:"}function R3(n){return typeof n=="string"&&/\.pdf$/i.test(n)}function Zce(n){return[n]=n.split(/[#?]/,1),KB(n)}function Jce(n,e="document.pdf"){if(typeof n!="string")return e;if(iD(n))return Bn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),e;const r=(l=>{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+(r<i?6:0))*60;break;case r:e[0]=((i-t)/d+2)*60;break;case i:e[0]=((t-r)/d+4)*60;break}}e[2]=l}function ZB(n,e){const t=n[0],r=n[1],i=n[2],o=(1-Math.abs(2*i-1))*r,a=o*(1-Math.abs(t/60%2-1)),l=i-o/2;switch(Math.floor(t/60)){case 0:e[0]=o+l,e[1]=a+l,e[2]=l;break;case 1:e[0]=a+l,e[1]=o+l,e[2]=l;break;case 2:e[0]=l,e[1]=o+l,e[2]=a+l;break;case 3:e[0]=l,e[1]=a+l,e[2]=o+l;break;case 4:e[0]=a+l,e[1]=l,e[2]=o+l;break;case 5:case 6:e[0]=o+l,e[1]=l,e[2]=a+l;break}}function fN(n){return n<=.03928?n/12.92:((n+.055)/1.055)**2.4}function pN(n,e,t){ZB(n,t),t.map(fN);const r=.2126*t[0]+.7152*t[1]+.0722*t[2];ZB(e,t),t.map(fN);const i=.2126*t[0]+.7152*t[1]+.0722*t[2];return r>i?(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)<c){let u,f;d?(u=a[2],f=1):(u=0,f=a[2]);const p=.005;for(;f-u>p;){const g=a[2]=(u+f)/2;d===pN(a,l,o)<c?u=g:f=g}a[2]=d?f:u}return ZB(a,o),r=yt.makeHexColor(Math.round(o[0]*255),Math.round(o[1]*255),Math.round(o[2]*255)),gN.set(t,r),r}function uV({html:n,dir:e,className:t},r){const i=document.createDocumentFragment();if(typeof n=="string"){const o=document.createElement("p");o.dir=e||"auto";const a=n.split(/(?:\r\n?|\n)/);for(let l=0,d=a.length;l<d;++l){const c=a[l];o.append(document.createTextNode(c)),l<d-1&&o.append(document.createElement("br"))}i.append(o)}else cV.render({xfaHtml:n,div:i,intent:"richText"});i.firstElementChild.classList.add("richText",t),r.append(i)}function hV(n){const e=new Path2D;if(!n)return e;for(let t=0,r=n.length;t<r;)switch(n[t++]){case Hw.moveTo:e.moveTo(n[t++],n[t++]);break;case Hw.lineTo:e.lineTo(n[t++],n[t++]);break;case Hw.curveTo:e.bezierCurveTo(n[t++],n[t++],n[t++],n[t++],n[t++],n[t++]);break;case Hw.quadraticCurveTo:e.quadraticCurveTo(n[t++],n[t++],n[t++],n[t++]);break;case Hw.closePath:e.closePath();break;default:Bn(`Unrecognized drawing path operator: ${n[t-1]}`);break}return e}var mp,yp,cd,ud,ik,xp,jb,kb,sk,FT,fV,Do,pV,gV,jx,uS;const yh=class yh{constructor(e){N(this,Do);N(this,mp,null);N(this,yp,null);N(this,cd);N(this,ud,null);N(this,ik,null);N(this,xp,null);N(this,jb,null);N(this,kb,null);R(this,cd,e),h(yh,sk)||R(yh,sk,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button",signature:"pdfjs-editor-remove-signature-button"}))}render(){const e=R(this,mp,document.createElement("div"));e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");const t=h(this,cd)._uiManager._signal;t instanceof AbortSignal&&!t.aborted&&(e.addEventListener("contextmenu",Hd,{signal:t}),e.addEventListener("pointerdown",q(yh,FT,fV),{signal:t}));const r=R(this,ud,document.createElement("div"));r.className="buttons",e.append(r);const i=h(this,cd).toolbarPosition;if(i){const{style:o}=e,a=h(this,cd)._uiManager.direction==="ltr"?1-i[0]:i[0];o.insetInlineEnd=`${100*a}%`,o.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return e}get div(){return h(this,mp)}hide(){var e;h(this,mp).classList.add("hidden"),(e=h(this,yp))==null||e.hideDropdown()}show(){var e,t;h(this,mp).classList.remove("hidden"),(e=h(this,ik))==null||e.shown(),(t=h(this,xp))==null||t.shown()}addDeleteButton(){const{editorType:e,_uiManager:t}=h(this,cd),r=document.createElement("button");r.classList.add("basic","deleteButton"),r.tabIndex=0,r.setAttribute("data-l10n-id",h(yh,sk)[e]),q(this,Do,jx).call(this,r)&&r.addEventListener("click",i=>{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(a<r)continue;const l=o.x+(t?o.width:0);if(a>r){i=l,r=a;continue}t?l>i&&(i=l):l<i&&(i=l)}return[t?1-i:i,r]},eI=function(e,t,r,i){const o=document.createElement("button");o.classList.add("basic",e),o.tabIndex=0,o.setAttribute("data-l10n-id",t);const a=document.createElement("span");o.append(a),a.className="visuallyHidden",a.setAttribute("data-l10n-id",r);const l=h(this,Ah)._signal;l instanceof AbortSignal&&!l.aborted&&(o.addEventListener("contextmenu",Hd,{signal:l}),o.addEventListener("click",i,{signal:l})),h(this,ok).append(o)};function xV(n,e,t){for(const r of t)e.addEventListener(r,n[r].bind(n))}var zm,Om,_b,Lm;const ni=class ni{static initializeAndAddPointerId(e){(h(ni,Om)||R(ni,Om,new Set)).add(e)}static setPointer(e,t){h(ni,zm)||R(ni,zm,t),h(ni,Lm)??R(ni,Lm,e)}static setTimeStamp(e){R(ni,_b,e)}static isSamePointerId(e){return h(ni,zm)===e}static isSamePointerIdOrRemove(e){var t;return h(ni,zm)===e?!0:((t=h(ni,Om))==null||t.delete(e),!1)}static isSamePointerType(e){return h(ni,Lm)===e}static isInitializedAndDifferentPointerType(e){return h(ni,Lm)!==null&&!ni.isSamePointerType(e)}static isSameTimeStamp(e){return h(ni,_b)===e}static isUsingMultiplePointers(){var e;return((e=h(ni,Om))==null?void 0:e.size)>=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,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',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<h(this,ys).length&&h(this,ys).splice(c)),h(this,ys).push(d)}undo(){if(h(this,Xi)===-1)return;R(this,bp,!0);const{undo:e,post:t}=h(this,ys)[h(this,Xi)];e(),t==null||t(),R(this,bp,!1),R(this,Xi,h(this,Xi)-1)}redo(){if(h(this,Xi)<h(this,ys).length-1){R(this,Xi,h(this,Xi)+1),R(this,bp,!0);const{cmd:e,post:t}=h(this,ys)[h(this,Xi)];e(),t==null||t(),R(this,bp,!1)}}hasSomethingToUndo(){return h(this,Xi)!==-1}hasSomethingToRedo(){return h(this,Xi)<h(this,ys).length-1}cleanType(e){if(h(this,Xi)!==-1){for(let t=h(this,Xi);t>=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<u;c++)if(!e.contains(t.getRangeAt(c).commonAncestorContainer))return null;const{x:r,y:i,width:o,height:a}=e.getBoundingClientRect();let l;switch(e.getAttribute("data-main-rotation")){case"90":l=(c,u,f,p)=>({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<u;c++){const f=t.getRangeAt(c);if(!f.collapsed)for(const{x:p,y:g,width:m,height:y}of f.getClientRects())m===0||y===0||d.push(l(p,g,m,y))}return d.length===0?null:d}addChangedExistingAnnotation({annotationElementId:e,id:t}){(h(this,Pb)||R(this,Pb,new Map)).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){var t;(t=h(this,Pb))==null||t.delete(e)}renderAnnotationElement(e){var i;const t=(i=h(this,Pb))==null?void 0:i.get(e.data.id);if(!t)return;const r=h(this,pa).getRawValue(t);r&&(h(this,As)===jn.NONE&&!r.hasBeenModified||r.renderAnnotationElement(e))}setMissingCanvas(e,t,r){var o;const i=(o=h(this,Ap))==null?void 0:o.get(e);i&&(i.setCanvas(t,r),h(this,Ap).delete(e))}addMissingCanvas(e,t){(h(this,Ap)||R(this,Ap,new Map)).set(e,t)}};Tb=new WeakMap,ml=new WeakMap,Fb=new WeakMap,as=new WeakMap,Yi=new WeakMap,Db=new WeakMap,Eb=new WeakMap,pa=new WeakMap,Pb=new WeakMap,hd=new WeakMap,to=new WeakMap,vp=new WeakMap,wp=new WeakMap,Sp=new WeakMap,jp=new WeakMap,ru=new WeakMap,fd=new WeakMap,Nm=new WeakMap,dk=new WeakMap,ck=new WeakMap,Rb=new WeakMap,uk=new WeakMap,iu=new WeakMap,kp=new WeakMap,Bb=new WeakMap,_p=new WeakMap,su=new WeakMap,RT=new WeakMap,Th=new WeakMap,Ib=new WeakMap,hk=new WeakMap,Cp=new WeakMap,Wm=new WeakMap,Mb=new WeakMap,Ap=new WeakMap,fk=new WeakMap,As=new WeakMap,Kr=new WeakMap,Fh=new WeakMap,Tp=new WeakMap,Fp=new WeakMap,pk=new WeakMap,zb=new WeakMap,gk=new WeakMap,Dp=new WeakMap,ou=new WeakMap,Dh=new WeakMap,mk=new WeakMap,yk=new WeakMap,pd=new WeakMap,Tt=new WeakSet,B5=function({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e},rI=function(e){const{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(const r of h(this,Yi).values())if(r.hasTextLayer(e))return r;return null},vV=function(e){var t;this.commitOrRemove(),(t=this.currentLayer)==null||t.endDrawingSession(!1)},wV=function(){const e=document.getSelection();if(!e||e.isCollapsed)return;const r=q(this,Tt,B5).call(this,e).closest(".textLayer"),i=this.getSelectionBoxes(r);i&&(h(this,su)||R(this,su,new aue(this)),h(this,su).show(r,i,this.direction==="ltr"))},SV=function(){var o,a,l;const e=document.getSelection();if(!e||e.isCollapsed){h(this,Fh)&&((o=h(this,su))==null||o.hide(),R(this,Fh,null),q(this,Tt,ua).call(this,{hasSelectedText:!1}));return}const{anchorNode:t}=e;if(t===h(this,Fh))return;const i=q(this,Tt,B5).call(this,e).closest(".textLayer");if(!i){h(this,Fh)&&((a=h(this,su))==null||a.hide(),R(this,Fh,null),q(this,Tt,ua).call(this,{hasSelectedText:!1}));return}if((l=h(this,su))==null||l.hide(),R(this,Fh,t),q(this,Tt,ua).call(this,{hasSelectedText:!0}),!(h(this,As)!==jn.HIGHLIGHT&&h(this,As)!==jn.NONE)&&(h(this,As)===jn.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),R(this,_p,this.isShiftKeyDown),!this.isShiftKeyDown)){const d=h(this,As)===jn.HIGHLIGHT?q(this,Tt,rI).call(this,i):null;if(d==null||d.toggleDrawing(),h(this,Ib)){const c=new AbortController,u=this.combinedSignal(c),f=p=>{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 t<a&&i>0&&e<o&&r>0}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(o<i)for(let l=0;l<i-o;l++)h(this,So).append(h(this,So).firstElementChild);else if(o>i)for(let l=0;l<o-i;l++)h(this,So).firstElementChild.before(h(this,So).lastElementChild);let a=0;for(const l of t){const c=h(this,cc)[a++].getAttribute("data-resizer-name");l.setAttribute("data-l10n-id",En._l10nResizer[c])}}q(this,ln,pI).call(this,0),R(this,zh,!0),h(this,So).firstElementChild.focus({focusVisible:!0}),e.preventDefault(),e.stopImmediatePropagation()}_resizeWithKeyboard(e,t){h(this,zh)&&q(this,ln,uI).call(this,h(this,Ck),{deltaX:e,deltaY:t,fromKeyboard:!0})}_stopResizingWithKeyboard(){q(this,ln,gS).call(this),this.div.focus()}select(){var e,t,r;if(this.isSelected&&this._editToolbar){this._editToolbar.show();return}if(this.isSelected=!0,this.makeResizable(),(e=this.div)==null||e.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{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<v;y++){const x=e.charCodeAt(y);x<=255?t[r++]=x:(t[r++]=x>>>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<i;y++)y&1?(l=a[y],l=l*f&rd|l*g&Xc,l=l<<15|l>>>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<l;a+=4)x=x-v+r(p,a)|0;a<p.length&&(x=x-v+r(p+"XXX",a)|0),g=o(g,y,4,i(x));const w=`url(data:font/opentype;base64,${btoa(g)});`,S=`@font-face {font-family:"${p}";src:${w}}`;this.insertRule(S);const _=this._document.createElement("div");_.style.visibility="hidden",_.style.width=_.style.height="10px",_.style.position="absolute",_.style.top=_.style.left="0px";for(const b of[e.loadedName,p]){const C=this._document.createElement("span");C.textContent="Hi",C.style.fontFamily=b,_.append(C)}this._document.body.append(_),f(p,()=>{_.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<KV.strings.length,"Invalid string index");let t=0;for(let i=0;i<e;i++)t+=h(this,Yb).getUint32(t)+4;const r=h(this,Yb).getUint32(t);return h(this,MT).decode(new Uint8Array(h(this,Rk),t+4,r))};var cy,$b,hu,uy,mS;class yue{constructor(e){N(this,uy);N(this,cy);N(this,$b,new TextDecoder);N(this,hu);R(this,cy,e),R(this,hu,new DataView(e))}get guessFallback(){return h(this,hu).getUint8(0)!==0}get css(){return q(this,uy,mS).call(this,0)}get loadedName(){return q(this,uy,mS).call(this,1)}get baseFontName(){return q(this,uy,mS).call(this,2)}get src(){return q(this,uy,mS).call(this,3)}get style(){let e=1;e+=4+h(this,hu).getUint32(e);const t=h(this,hu).getUint32(e),r=h(this,$b).decode(new Uint8Array(h(this,cy),e+4,t));e+=4+t;const i=h(this,hu).getUint32(e),o=h(this,$b).decode(new Uint8Array(h(this,cy),e+4,i));return{style:r,weight:o}}}cy=new WeakMap,$b=new WeakMap,hu=new WeakMap,uy=new WeakSet,mS=function(e){Zi(e<XV.strings.length,"Invalid string index");let t=5;for(let i=0;i<e;i++)t+=h(this,hu).getUint32(t)+4;const r=h(this,hu).getUint32(t);return h(this,$b).decode(new Uint8Array(h(this,cy),t+4,r))};var fc,zT,xs,Qr,ic,L5,N5,yS,bI;class xue{constructor({buffer:e,extra:t}){N(this,Qr);N(this,fc);N(this,zT,new TextDecoder);N(this,xs);R(this,fc,e),R(this,xs,new DataView(e)),t&&Object.assign(this,t)}get black(){return q(this,Qr,ic).call(this,0)}get bold(){return q(this,Qr,ic).call(this,1)}get disableFontFace(){return q(this,Qr,ic).call(this,2)}get fontExtraProperties(){return q(this,Qr,ic).call(this,3)}get isInvalidPDFjsFont(){return q(this,Qr,ic).call(this,4)}get isType3Font(){return q(this,Qr,ic).call(this,5)}get italic(){return q(this,Qr,ic).call(this,6)}get missingFile(){return q(this,Qr,ic).call(this,7)}get remeasure(){return q(this,Qr,ic).call(this,8)}get vertical(){return q(this,Qr,ic).call(this,9)}get ascent(){return q(this,Qr,L5).call(this,0)}get defaultWidth(){return q(this,Qr,L5).call(this,1)}get descent(){return q(this,Qr,L5).call(this,2)}get bbox(){return q(this,Qr,N5).call(this,pl.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return q(this,Qr,N5).call(this,pl.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return q(this,Qr,N5).call(this,pl.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}get fallbackName(){return q(this,Qr,yS).call(this,0)}get loadedName(){return q(this,Qr,yS).call(this,1)}get mimetype(){return q(this,Qr,yS).call(this,2)}get name(){return q(this,Qr,yS).call(this,3)}get data(){const{offset:e,length:t}=q(this,Qr,bI).call(this);return t===0?void 0:new Uint8Array(h(this,fc),e+4,t)}clearData(){const{offset:e,length:t}=q(this,Qr,bI).call(this);t!==0&&(h(this,xs).setUint32(e,0),R(this,fc,new Uint8Array(h(this,fc),0,e+4).slice().buffer),R(this,xs,new DataView(h(this,fc))))}get cssFontInfo(){let e=pl.OFFSET_STRINGS;const t=h(this,xs).getUint32(e);e+=4+t;const r=h(this,xs).getUint32(e);e+=4+r;const i=h(this,xs).getUint32(e);if(i===0)return null;const o=new Uint8Array(i);return o.set(new Uint8Array(h(this,fc),e+4,i)),new mue(o.buffer)}get systemFontInfo(){let e=pl.OFFSET_STRINGS;const t=h(this,xs).getUint32(e);e+=4+t;const r=h(this,xs).getUint32(e);if(r===0)return null;const i=new Uint8Array(r);return i.set(new Uint8Array(h(this,fc),e+4,r)),new yue(i.buffer)}}fc=new WeakMap,zT=new WeakMap,xs=new WeakMap,Qr=new WeakSet,ic=function(e){Zi(e<pl.bools.length,"Invalid boolean index");const t=Math.floor(e/4),r=e*2%8,i=h(this,xs).getUint8(t)>>r&3;return i===0?void 0:i===2},L5=function(e){return Zi(e<pl.numbers.length,"Invalid number index"),h(this,xs).getFloat64(pl.OFFSET_NUMBERS+e*8)},N5=function(e,t,r,i){const o=h(this,xs).getUint8(e);if(o===0)return;Zi(o===t,"Invalid array length."),e+=1;const a=new Array(o);for(let l=0;l<o;l++)a[l]=h(this,xs)[r](e,!0),e+=i;return a},yS=function(e){Zi(e<pl.strings.length,"Invalid string index");let t=pl.OFFSET_STRINGS+4;for(let i=0;i<e;i++)t+=h(this,xs).getUint32(t)+4;const r=h(this,xs).getUint32(t);return h(this,zT).decode(new Uint8Array(h(this,fc),t+4,r))},bI=function(){let e=pl.OFFSET_STRINGS;const t=h(this,xs).getUint32(e);e+=4+t;const r=h(this,xs).getUint32(e);e+=4+r;const i=h(this,xs).getUint32(e);e+=4+i;const o=h(this,xs).getUint32(e);return{offset:e,length:o}};class bue{constructor(e){this.buffer=e,this.view=new DataView(e),this.data=new Uint8Array(e)}getIR(){const e=this.view,t=this.data[Sa.KIND],r=!!this.data[Sa.HAS_BBOX],i=!!this.data[Sa.HAS_BACKGROUND],o=e.getUint32(Sa.N_COORD,!0),a=e.getUint32(Sa.N_COLOR,!0),l=e.getUint32(Sa.N_STOP,!0);let d=20;const c=new Float32Array(this.buffer,d,o*2);d+=o*8;const u=new Uint8Array(this.buffer,d,a*4);d+=a*4;const f=[];for(let m=0;m<l;++m){const y=e.getFloat32(d,!0);d+=4;const v=e.getUint32(d,!0);d+=4,f.push([y,`#${v.toString(16).padStart(6,"0")}`])}let p=null;if(r){p=[];for(let m=0;m<4;++m)p.push(e.getFloat32(d,!0)),d+=4}let g=null;if(i&&(g=new Uint8Array(this.buffer,d,3),d+=3),t===1)return["RadialAxial","axial",p,f,Array.from(c.slice(0,2)),Array.from(c.slice(2,4)),null,null];if(t===2)return["RadialAxial","radial",p,f,[c[0],c[1]],[c[3],c[4]],c[2],c[5]];if(t===3){const m=this.data[Sa.SHADING_TYPE];let y=null;if(c.length>0){y=hf.slice();for(let v=0,x=c.length;v<x;v+=2)yt.pointBoundingBox(c[v],c[v+1],y)}return["Mesh",m,c,u,o,y,p,g]}throw new Error(`Unsupported pattern kind: ${t}`)}}var Zb;class vue{constructor(e){N(this,Zb);R(this,Zb,e)}get path(){return Ds.isFloat16ArraySupported?new Float16Array(h(this,Zb)):new Float32Array(h(this,Zb))}}Zb=new WeakMap;function wue(n){if(n instanceof URL)return n;if(typeof n=="string"){if(zl){if(/^[a-z][a-z0-9\-+.]+:/i.test(n))return new URL(n);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(n))}const e=URL.parse(n,window.location);if(e)return e}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Sue(n){if(zl&&typeof Buffer<"u"&&n instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength)return n;if(typeof n=="string")return rD(n);if(n instanceof ArrayBuffer||ArrayBuffer.isView(n)||typeof n=="object"&&!isNaN(n==null?void 0:n.length))return new Uint8Array(n);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function G2(n){if(typeof n!="string")return null;if(n.endsWith("/"))return n;throw new Error(`Invalid factory url: "${n}" must include trailing slash.`)}const vI=n=>typeof 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<f&&([f,p,g,m]=[p,f,m,g]),h(this,zt,kx).style.color="";const y=(S,_,b)=>{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<uniform> u : Uniforms;
struct VertexInput {
@location(0) position : vec2<f32>,
@location(1) color : vec4<f32>,
};
struct VertexOutput {
@builtin(position) position : vec4<f32>,
@location(0) color : vec3<f32>,
};
@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<f32>(
((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<f32> {
return vec4<f32>(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)<g)if(this.isRadial()){if(Math.abs(m-y)<g)return this._createGradient(e,p)}else return this._createGradient(e,p)}const a=t.current.getClippedPathBoundingBox(i,ji(e))||[0,0,0,0],l=Math.ceil(a[2]-a[0])||1,d=Math.ceil(a[3]-a[1])||1,c=t.canvasFactory.create(l,d),u=c.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-a[0],-a[1]),r=yt.transform(r,[1,0,0,1,a[0],a[1]]),u.transform(...t.baseTransform),this.matrix&&u.transform(...this.matrix),H5(u,this._bbox),this.areConic()&&(u.fillStyle=this._createReversedGradient(u),u.fill()),u.fillStyle=this._createGradient(u),u.fill(),o=e.createPattern(c.canvas,"no-repeat"),t.canvasFactory.destroy(c);const f=new DOMMatrix(r);o.setTransform(f)}else this.areConic()&&(e.save(),H5(e,this._bbox),e.fillStyle=this._createReversedGradient(e),e.fillRect(-1e10,-1e10,2e10,2e10),e.restore()),H5(e,this._bbox),o=this._createGradient(e);return o}}function Lue(n,e,t,r,i,o,a,l){const d=e.coords,c=e.colors,u=n.data,f=n.width*4;let p;d[t*2+1]>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(re<v){const ke=re<m?0:(m-re)/(m-v);O=g-(g-y)*ke,U=S-(S-C)*ke,M=_-(_-T)*ke,I=b-(b-F)*ke}else{let ke;re>w?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;re<m?me=0:re>w?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;b<C;b+=4)_[b]=t[0],_[b+1]=t[1],_[b+2]=t[2],_[b+3]=255}for(let _=0,b=this._vertexCount;_<b;_+=3)Lue(S,y,_,_+1,_+2,_,_+1,_+2);w.context.putImageData(S,2,2)}return{canvas:w.canvas,offsetX:l-2*g,offsetY:d-2*m,scaleX:g,scaleY:m}}isModifyingCurrentTransform(){return!0}getPattern(e,t,r,i){H5(e,this._bbox);const o=new Float32Array(2);if(i===To.SHADING)yt.singularValueDecompose2dScale(ji(e),o);else if(this.matrix){yt.singularValueDecompose2dScale(this.matrix,o);const[d,c]=o;yt.singularValueDecompose2dScale(t.baseTransform,o),o[0]*=d,o[1]*=c}else yt.singularValueDecompose2dScale(t.baseTransform,o);const a=this._createMeshCanvas(o,i===To.SHADING?null:this._background,t.canvasFactory);i!==To.SHADING&&(e.setTransform(...t.baseTransform),this.matrix&&e.transform(...this.matrix)),e.translate(a.offsetX,a.offsetY),e.scale(a.scaleX,a.scaleY);const l=e.createPattern(a.canvas,"no-repeat");return t.canvasFactory.destroy(a),l}}class Wue extends M3{getPattern(){return"hotpink"}}function Uue(n){switch(n[0]){case"RadialAxial":return new Oue(n);case"Mesh":return new Nue(n);case"Dummy":return new Wue}throw new Error(`Unknown IR type: ${n[0]}`)}const jN={COLORED:1,UNCOLORED:2},UT=class UT{constructor(e,t,r,i){this.color=e[1],this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.needsIsolation=e[9]??!0,this.ctx=t,this.canvasGraphicsFactory=r,this.baseTransform=i,this.patternBaseMatrix=this.matrix?yt.transform(i,this.matrix):i}canSkipPatternCanvas([e,t,r,i]){const[o,a,l,d]=this.bbox,c=Math.abs(this.xstep),u=Math.abs(this.ystep);if(e>c+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<i;++y){for(const x=e+u;e<x;++e,m+=8){const w=n[e];t[m]=d^-(w>>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<g?n[e++]:255;for(let x=0;x<f;++x,++m)t[m]=d^-(v>>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;p<a;p++){for(m=p<o?Xa:i,c=0,g=0;g<m;g++){const C=v-d;let T=0;const F=C>S?r:C*8-7,A=F&-8;let D=0,P=0;for(;T<A;T+=8)P=u[d++],x[c++]=P&128?_:b,x[c++]=P&64?_:b,x[c++]=P&32?_:b,x[c++]=P&16?_:b,x[c++]=P&8?_:b,x[c++]=P&4?_:b,x[c++]=P&2?_:b,x[c++]=P&1?_:b;for(;T<F;T++)D===0&&(P=u[d++],D=128),x[c++]=P&D?_:b,D>>=1}for(;c<w;)x[c++]=0;n.putImageData(l,0,p*Xa)}}else if(e.kind===E5.RGBA_32BPP){for(g=0,y=r*Xa*4,p=0;p<o;p++)f.set(u.subarray(d,d+y)),d+=y,n.putImageData(l,0,g),g+=Xa;p<a&&(y=r*i*4,f.set(u.subarray(d,d+y)),n.putImageData(l,0,g))}else if(e.kind===E5.RGB_24BPP)for(m=Xa,y=r*m,p=0;p<a;p++){for(p>=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;f<a;f++){const p=f<o?Xa:i;({srcPos:d}=Hue({src:c,srcPos:d,dest:u,width:r,height:p,nonBlackColor:0})),n.putImageData(l,0,f*Xa)}}function qw(n,e){const t=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const r of t)n[r]!==void 0&&(e[r]=n[r]);n.setLineDash!==void 0&&(e.setLineDash(n.getLineDash()),e.lineDashOffset=n.lineDashOffset)}function Y2(n){n.strokeStyle=n.fillStyle="#000000",n.fillRule="nonzero",n.globalAlpha=1,n.lineWidth=1,n.lineCap="butt",n.lineJoin="miter",n.miterLimit=10,n.globalCompositeOperation="source-over",n.font="10px sans-serif",n.setLineDash!==void 0&&(n.setLineDash([]),n.lineDashOffset=0);const{filter:e}=n;e!=="none"&&e!==""&&(n.filter="none")}function DN(n,e){if(e)return!0;yt.singularValueDecompose2dScale(n,Ol);const t=Math.fround(Lu.pixelRatio*Wg.PDF_TO_CSS_UNITS);return Ol[0]<=t&&Ol[1]<=t}const Gue=["butt","round","square"],Kue=["miter","round","bevel"],Xue={},EN={};var Pc,jI,kI,_I;const q3=class q3{constructor(e,t,r,i,o,{optionalContentConfig:a,markedContentStack:l=null},d,c,u,f){N(this,Pc);this.ctx=e,this.current=new AN(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.commonObjs=t,this.objs=r,this.canvasFactory=i,this.filterFactory=o,this.groupStack=[],this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.tempSMask=null,this.smaskGroupCanvases=[],this.smaskPreparedEntry=null,this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=l||[],this.optionalContentConfig=a,this.cachedPatterns=new Map,this.annotationCanvasMap=d,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map,this.dependencyTracker=u??null,this.imagesTracker=f??null}getObject(e,t,r=null){var i;return typeof t=="string"?((i=this.dependencyTracker)==null||i.recordNamedDependency(e,t),t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t)):r}beginDrawing({transform:e,viewport:t,transparency:r=!1,background:i=null}){const o=this.ctx.canvas.width,a=this.ctx.canvas.height,l=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,o,a),this.ctx.fillStyle=l,r){const d=this.transparentCanvasEntry=this.canvasFactory.create(o,a);this.compositeCtx=this.ctx,{canvas:this.transparentCanvas,context:this.ctx}=d,this.ctx.save(),this.ctx.transform(...ji(this.compositeCtx))}this.ctx.save(),Y2(this.ctx),e&&(this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[3]),this.ctx.transform(...t.transform),this.viewportScale=t.scale,this.baseTransform=ji(this.ctx)}executeOperatorList(e,t,r,i,o){var x;const a=e.argsArray,l=e.fnArray;let d=t||0;const c=a.length;if(c===d)return d;const u=c-d>CN&&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<kN?u=kN: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;o<r.length;o+=4)if(r[o]>0&&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;D<p;++D){const U=t[D];if(typeof U=="number"){A+=m*U*o/1e3;continue}let M=!1;const I=(U.isSpace?c:0)+d,H=U.fontChar,z=U.accent;let G,te,re=U.width;if(g){const ne=U.vmetric||y,ye=-(U.vmetric?ne[1]:re*.5)*v,ke=ne[2]*v;re=ne?-ne[0]:re,G=ye/l,te=(A+ke)/l}else G=A/l,te=0;let me;if(i.remeasure&&re>0){me=a.measureText(H);const ne=me.width*1e3/o*l;if(re<ne&&this.isFontSubpixelAAEnabled){const ye=re/ne;M=!0,a.save(),a.scale(ye,1),G/=ye}else re!==ne&&(G+=(re-ne)/2e3*o/l)}if(this.contentVisible&&(U.isInFont||i.missingFile)){if(x&&!z)a.fillText(H,G,te),(W=this.dependencyTracker)==null||W.recordCharacterBBox(e,a,me?{bbox:null}:i,o/l,G,te,()=>me??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;y<g;++y){if(v=t[y],typeof v=="number"){w=d*v*a/1e3,this.ctx.translate(w,0),i.x+=w*f;continue}const _=(v.isSpace?u:0)+c,b=o.charProcOperatorList[v.operatorListId];b?this.contentVisible&&(this.save(),r.scale(a,a),r.transform(...p),this.executeOperatorList(b),this.restore()):Bn(`Type3 character "${v.operatorListId}" is not available.`);const C=[v.width,0];yt.applyTransform(C,p),x=C[0]*a+_,r.translate(x,0),i.x+=x*f}r.restore(),S&&(this.dependencyTracker=S)}setCharWidth(e,t,r){}setCharWidthAndBounds(e,t,r,i,o,a,l){var c;const d=new Path2D;d.rect(i,o,a-i,l-o),this.ctx.clip(d),(c=this.dependencyTracker)==null||c.recordBBox(e,this.ctx,i,a,o,l).recordClipBox(e,this.ctx,i,a,o,l),this.endPath(e)}getColorN_Pattern(e,t){let r;if(t[0]==="TilingPattern"){const i=this.baseTransform||ji(this.ctx),o={createCanvasGraphics:(a,l)=>new 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;m<y;m+=2){const v=yt.transform(c,[r,i,o,a,l[m],l[m+1]]);d.drawImage(u.canvas,v[4],v[5]),(p=this.dependencyTracker)==null||p.recordBBox(e,this.ctx,v[4],v[4]+u.canvas.width,v[5],v[5]+u.canvas.height)}d.restore(),u.canvasEntry&&this.canvasFactory.destroy(u.canvasEntry),this.compose(),(g=this.dependencyTracker)==null||g.recordOperation(e)}paintImageMaskXObjectGroup(e,t){var a,l,d;if(!this.contentVisible)return;const r=this.ctx,i=this.current.fillColor,o=this.current.patternFill;(a=this.dependencyTracker)==null||a.resetBBox(e).recordDependencies(e,id.transformAndFill);for(const c of t){const{data:u,width:f,height:p,transform:g}=c,m=this.canvasFactory.create(f,p),y=m.context;y.save();const v=this.getObject(e,u,c);FN(y,v),y.globalCompositeOperation="source-in",y.fillStyle=o?i.getPattern(y,this,Kc(r),To.FILL,e):i,y.fillRect(0,0,f,p),y.restore(),r.save(),r.transform(...g),r.scale(1,-1),X2(r,m.canvas,0,0,f,p,0,-1,1,1),this.canvasFactory.destroy(m),(l=this.dependencyTracker)==null||l.recordBBox(e,r,0,f,0,p),r.restore()}this.compose(),(d=this.dependencyTracker)==null||d.recordOperation(e)}paintImageXObject(e,t){if(!this.contentVisible)return;const r=this.getObject(e,t);if(!r){Bn("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e,r)}paintImageXObjectRepeat(e,t,r,i,o){if(!this.contentVisible)return;const a=this.getObject(e,t);if(!a){Bn("Dependent image isn't ready yet");return}const l=a.width,d=a.height,c=[];for(let u=0,f=o.length;u<f;u+=2)c.push({transform:[r,0,0,i,o[u],o[u+1]],x:0,y:0,w:l,h:d});this.paintInlineImageXObjectGroup(e,a,c)}applyTransferMapsToCanvas(e){return this.current.transferMaps!=="none"&&(e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter="none"),e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps==="none")return{img:e.bitmap,canvasEntry:null};const{bitmap:t,width:r,height:i}=e,o=this.canvasFactory.create(r,i),a=o.context;return a.filter=this.current.transferMaps,a.drawImage(t,0,0),a.filter="none",{img:o.canvas,canvasEntry:o}}paintInlineImageXObject(e,t){var u;if(!this.contentVisible)return;const r=t.width,i=t.height,o=this.ctx;this.save(e);const{filter:a}=o;a!=="none"&&a!==""&&(o.filter="none"),o.scale(1/r,-1/i);let l,d=null;if(t.bitmap){const f=this.applyTransferMapsToBitmap(t);l=f.img,d=f.canvasEntry}else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)l=t;else{const f=this.canvasFactory.create(r,i);TN(f.context,t),l=this.applyTransferMapsToCanvas(f.context),d=f}const c=this._scaleImage(l,Kc(o));o.imageSmoothingEnabled=DN(ji(o),t.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(e).recordBBox(e,o,0,r,-i,0).recordDependencies(e,id.imageXObject).recordOperation(e),(u=this.imagesTracker)==null||u.record(o,r,i,this.dependencyTracker.clipBox)),X2(o,c.img,0,0,c.paintWidth,c.paintHeight,0,-i,r,i),c.tmpCanvas&&this.canvasFactory.destroy(c.tmpCanvas),d&&this.canvasFactory.destroy(d),this.compose(),this.restore(e)}paintInlineImageXObjectGroup(e,t,r){var l,d,c;if(!this.contentVisible)return;const i=this.ctx;let o,a=null;if(t.bitmap)o=t.bitmap;else{const u=t.width,f=t.height,p=this.canvasFactory.create(u,f);TN(p.context,t),o=this.applyTransferMapsToCanvas(p.context),a=p}(l=this.dependencyTracker)==null||l.resetBBox(e);for(const u of r)i.save(),i.transform(...u.transform),i.scale(1,-1),X2(i,o,u.x,u.y,u.w,u.h,0,-1,1,1),(d=this.dependencyTracker)==null||d.recordBBox(e,i,0,1,-1,0),i.restore();a&&this.canvasFactory.destroy(a),(c=this.dependencyTracker)==null||c.recordOperation(e),this.compose()}paintSolidColorImageMask(e){var t;this.contentVisible&&((t=this.dependencyTracker)==null||t.resetBBox(e).recordBBox(e,this.ctx,0,1,0,1).recordDependencies(e,id.fill).recordOperation(e),this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(e,t){}markPointProps(e,t,r){}beginMarkedContent(e,t){var r;(r=this.dependencyTracker)==null||r.beginMarkedContent(e),this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,t,r){var i;(i=this.dependencyTracker)==null||i.beginMarkedContent(e),t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(r)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(e){var t;(t=this.dependencyTracker)==null||t.endMarkedContent(e),this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(e){}endCompat(e){}consumePath(e,t,r){var a,l;const i=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(r);const o=this.ctx;this.pendingClip?(i||(this.pendingClip===EN?o.clip(t,"evenodd"):o.clip(t)),this.pendingClip=null,(a=this.dependencyTracker)==null||a.bboxToClipBoxDropOperation(e).recordFutureForcedDependency("clipPath",e)):(l=this.dependencyTracker)==null||l.recordOperation(e),this.current.startNewPathAndClipBox(this.current.clipBox)}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const e=ji(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{const t=Math.abs(e[0]*e[3]-e[2]*e[1]),r=Math.hypot(e[0],e[2]),i=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(r,i)/t}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:e}=this.current,{a:t,b:r,c:i,d:o}=this.ctx.getTransform();let a,l;if(r===0&&i===0){const d=Math.abs(t),c=Math.abs(o);if(d===c)if(e===0)a=l=1/d;else{const u=d*e;a=l=u<1?1/u:1}else if(e===0)a=1/d,l=1/c;else{const u=d*e,f=c*e;a=u<1?1/u:1,l=f<1?1/f:1}}else{const d=Math.abs(t*o-r*i),c=Math.hypot(t,r),u=Math.hypot(i,o);if(e===0)a=u/d,l=c/d;else{const f=e*d;a=u>f?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<f.length&&y in f;++y){let[v,x]=f[y];x=l(x),v&&(x=unescape(x),y===0&&(x=d(x))),m.push(x)}return m.join("")}function l(u){if(u.startsWith('"')){const f=u.slice(1).split('\\"');for(let p=0;p<f.length;++p){const g=f[p].indexOf('"');g!==-1&&(f[p]=f[p].slice(0,g),f.length=p+1),f[p]=f[p].replaceAll(/\\(.)/g,"$1")}u=f.join('"')}return u}function d(u){const f=u.indexOf("'");if(f===-1)return u;const p=u.slice(0,f),m=u.slice(f+1).replace(/^[^']*'/,"");return i(p,m)}function c(u){return!u.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(u)?u:u.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(f,p,g,m){if(g==="q"||g==="Q")return m=m.replaceAll("_"," "),m=m.replaceAll(/=([0-9a-fA-F]{2})/g,function(y,v){return String.fromCharCode(parseInt(v,16))}),i(p,m);try{m=atob(m)}catch{}return i(p,m)})}return""}function rG(n,e){const t=new Headers;if(!n||!e||typeof e!="object")return t;for(const r in e){const i=e[r];i!==void 0&&t.append(r,i)}return t}function dD(n){var e;return((e=URL.parse(n))==null?void 0:e.origin)??null}function iG({responseHeaders:n,isHttp:e,rangeChunkSize:t,disableRange:r}){const i={contentLength:0,isRangeSupported:!1},o=parseInt(n.get("Content-Length"),10);return!Number.isInteger(o)||(i.contentLength=o,o<=2*t)||r||!e||n.get("Accept-Ranges")!=="bytes"||(n.get("Content-Encoding")||"identity")==="identity"&&(i.isRangeSupported=!0),i}function sG(n){const e=n.get("Content-Disposition");if(e){let t=Yue(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(R3(t))return t}return null}function cD(n,e){return new xT(`Unexpected server response (${n}) while retrieving PDF "${e.href}".`,n,n===404||n===0&&e.protocol==="file:")}function oG(n,e){if(n!==e)throw new Error(`Expected range response-origin "${n}" to match "${e}".`)}function aG(n,e,t,r){return fetch(n,{method:"GET",headers:e,signal:r.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"})}function lG(n,e){if(n!==200&&n!==206)throw cD(n,e)}function uD(n){if(n instanceof Uint8Array)return n.buffer;if(n instanceof ArrayBuffer)return n;throw new Error(`getArrayBuffer - unexpected data: ${n}`)}class Que extends oD{constructor(t){super(t,$ue,Zue);ve(this,"_responseOrigin",null);const{httpHeaders:r,url:i}=t;Zi(/https?:/.test(i.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=rG(!0,r)}}class $ue extends aD{constructor(t){super(t);ve(this,"_abortController",new AbortController);ve(this,"_reader",null);const{disableRange:r,disableStream:i,rangeChunkSize:o,url:a,withCredentials:l}=t._source;this._isStreamingSupported=!i;const d=new Headers(t.headers);aG(a,d,l,this._abortController).then(c=>{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;i<t;i++){const o=e[i];let a;if(Array.isArray(o))a=q(this,Kk,AI).call(this,o);else if(h(this,oi).has(o))a=h(this,oi).get(o).visible;else return Bn(`Optional content group not found: ${o}`),!0;switch(r){case"And":if(!a)return!1;break;case"Or":if(a)return!0;break;case"Not":return!a;default:return!0}}return r==="And"};var bs,pc,ko,my,pu,ra,jS,kS,q5;class fhe{constructor(){N(this,ra);N(this,bs,null);N(this,pc,null);N(this,ko,0);N(this,my,null);N(this,pu,null)}get pagesNumber(){return h(this,ko)}set pagesNumber(e){h(this,ko)!==e&&(R(this,ko,e),R(this,bs,null),R(this,pc,null))}movePages(e,t,r){q(this,ra,jS).call(this);const i=h(this,bs),o=q(this,ra,kS).call(this),a=t.length,l=new Uint32Array(a);let d=0;for(let p=0;p<a;p++){const g=t[p]-1;l[p]=i[g],g<r&&d++}const c=h(this,ko),u=c-a,f=Bi(r-d,0,u);for(let p=0,g=0;p<c;p++)e.has(p+1)||(i[g++]=i[p]);i.copyWithin(f+a,f,u),i.set(l,f),q(this,ra,q5).call(this,o),i.every((p,g)=>p===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}a<t.length&&o.set(t.subarray(a),l),q(this,ra,q5).call(this,r,new Set(e))}cancelDelete(){h(this,pu)&&(R(this,bs,h(this,pu).pageNumberToId),R(this,ko,h(this,pu).pagesNumber),R(this,pc,h(this,pu).prevPageNumbers),R(this,pu,null))}cleanSavedData(){R(this,pu,null)}copyPages(e){q(this,ra,jS).call(this),R(this,my,{pageNumbers:e,pageIds:e.map(t=>h(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;i<t;i++)r[i]={document:null,pageIndices:[],includePages:[]};for(const[i,o]of e)for(let a=0,l=o.length;a<l;a++)r[a].includePages.push([i-1,o[a]-1]);for(const{includePages:i,pageIndices:o}of r){i.sort((a,l)=>a[0]-l[0]);for(let a=0,l=i.length;a<l;a++)o.push(i[a][1]),i[a]=i[a][0]}return r}extractPages(e){e=Array.from(e).sort((r,i)=>r-i);const t=new Map;for(let r=0,i=e.length;r<i;r++){const o=this.getPageId(e[r]);t.getOrInsertComputed(o,F3).push(r+1)}return this.getPageMappingForSaving(t)}getPrevPageNumber(e){var t;return((t=h(this,pc))==null?void 0:t[e-1])??0}getPageNumber(e){if(!h(this,bs))return e;const t=h(this,bs);for(let r=0,i=h(this,ko);r<i;r++)if(t[r]===e)return r+1;return 0}getPageId(e){var t;return((t=h(this,bs))==null?void 0:t[e-1])??e}getMapping(){var e;return(e=h(this,bs))==null?void 0:e.subarray(0,this.pagesNumber)}}bs=new WeakMap,pc=new WeakMap,ko=new WeakMap,my=new WeakMap,pu=new WeakMap,ra=new WeakSet,jS=function(){if(h(this,bs))return;const e=h(this,ko),t=R(this,bs,new Uint32Array(e));for(let r=0;r<e;r++)t[r]=r+1;R(this,pc,new Int32Array(t))},kS=function(){const e=new Map,t=h(this,bs);for(let r=0,i=h(this,ko);r<i;r++){const o=t[r],a=e.get(o);a?a.push(r+1):e.set(o,[r+1])}return e},q5=function(e,t=null,r=-1,i=null){const o=h(this,pc),a=h(this,bs),l=r+((i==null?void 0:i.length)??0),d=new Map;for(let c=0,u=h(this,ko);c<u;c++){if(c>=r&&c<l){o[c]=-i[c-r];continue}const f=a[c],p=e.get(f);let g=d.get(f)||0;if(t&&p)for(;g<p.length&&t.has(p[g]);)g++;o[c]=p==null?void 0:p[g],d.set(f,g+1)}};const Tx=Symbol("INITIAL_DATA"),BN=()=>({...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<i;r++)t.operatorList.fnArray.push(e.fnArray[r]),t.operatorList.argsArray.push(e.argsArray[r]);t.operatorList.lastChunk=e.lastChunk,t.operatorList.separateAnnots=e.separateAnnots;for(const r of t.renderTasks)r.operatorListChanged();e.lastChunk&&q(this,jy,_S).call(this)}_pumpOperatorList({renderingIntent:e,cacheKey:t,annotationStorageSerializable:r,modifiedIds:i}){const{map:o,transfer:a}=r,d=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageId:h(this,Sy).getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,intent:e,cacheKey:t,annotationStorage:o,modifiedIds:i},void 0,a).getReader(),c=this._intentStates.get(t);c.streamReader=d;const u=()=>{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;d<t.length;d+=8)t[d+1]>a?(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;c<u;c+=2)d[c+1]>a?(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,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${y}" stroke-width="${v}">`],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<v;y+=8){const x=e[y],w=e[y+1],S=e[y+2],_=e[y+3],b=u.createElement("rect"),C=(S-t)/d,T=(o-w)/c,F=(x-S)/d,A=(w-_)/c;b.setAttribute("x",C),b.setAttribute("y",T),b.setAttribute("width",F),b.setAttribute("height",A),g.append(b),l==null||l.push(`<rect vector-effect="non-scaling-stroke" x="${C}" y="${T}" width="${F}" height="${A}"/>`)}h(this,bv)&&(l.push("</g></svg>')"),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<p;f+=2){const g=r[f]-t[0],m=t[3]-r[f+1];c.push(`${g},${m}`)}c=c.join(" ");const u=R(this,f_,this.svgFactory.createElement(this.svgElementName));return u.setAttribute("points",c),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),d.append(u),this.container.append(d),!o&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,f_)}addHighlightArea(){this.container.classList.add("highlightArea")}}f_=new WeakMap;class Ihe extends zG{constructor(e){super(e),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Mhe extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}}var p_,Iy,g_,qI;class O3 extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,g_);N(this,p_,null);N(this,Iy,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?jn.HIGHLIGHT:jn.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:r,inkLists:i,borderStyle:o,popupRef:a}}=this,{transform:l,width:d,height:c}=q(this,g_,qI).call(this,r,t),u=this.svgFactory.create(d,c,!0),f=R(this,p_,this.svgFactory.createElement("svg:g"));u.append(f),f.setAttribute("stroke-width",o.width||1),f.setAttribute("stroke-linecap","round"),f.setAttribute("stroke-linejoin","round"),f.setAttribute("stroke-miterlimit",10),f.setAttribute("stroke","transparent"),f.setAttribute("fill","transparent"),f.setAttribute("transform",l);for(let p=0,g=i.length;p<g;p++){const m=this.svgFactory.createElement(this.svgElementName);h(this,Iy).push(m),m.setAttribute("points",i[p].join(",")),f.append(m)}return!a&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(u),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:r,points:i,rect:o}=t,a=h(this,p_);if(r>=0&&a.setAttribute("stroke-width",r||1),i)for(let l=0,d=h(this,Iy).length;l<d;l++)h(this,Iy)[l].setAttribute("points",i[l].join(","));if(o){const{transform:l,width:d,height:c}=q(this,g_,qI).call(this,this.data.rotation,o);a.parentElement.setAttribute("viewBox",`0 0 ${d} ${c}`),a.setAttribute("transform",l)}}getElementsToTriggerPopup(){return h(this,Iy)}addHighlightArea(){this.container.classList.add("highlightArea")}}p_=new WeakMap,Iy=new WeakMap,g_=new WeakSet,qI=function(t,r){switch(t){case 90:return{transform:`rotate(90) translate(${-r[0]},${r[1]}) scale(1,-1)`,width:r[3]-r[1],height:r[2]-r[0]};case 180:return{transform:`rotate(180) translate(${-r[2]},${r[1]}) scale(1,-1)`,width:r[2]-r[0],height:r[3]-r[1]};case 270:return{transform:`rotate(270) translate(${-r[2]},${r[3]}) scale(1,-1)`,width:r[3]-r[1],height:r[2]-r[0]};default:return{transform:`translate(${-r[0]},${r[3]}) scale(1,-1)`,width:r[2]-r[0],height:r[3]-r[1]}}};class OG extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=jn.HIGHLIGHT}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),e){const r=document.createElement("mark");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}}class zhe extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("underlineAnnotation"),e){const r=document.createElement("u");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}}class Ohe extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("squigglyAnnotation"),e){const r=document.createElement("u");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}}class Lhe extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){const{data:{overlaidText:e,popupRef:t}}=this;if(!t&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.classList.add("strikeoutAnnotation"),e){const r=document.createElement("s");r.classList.add("overlaidText"),r.textContent=e,this.container.append(r)}return this.container}}class LG extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=jn.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}var m_,y_,VI;class Nhe extends ts{constructor(t){var i;super(t,{isRenderable:!0});N(this,y_);N(this,m_,null);const{file:r}=this.data;this.filename=r.filename,this.content=r.content,(i=this.linkService.eventBus)==null||i.dispatch("fileattachmentannotation",{source:this,...r})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:r}=this;let i;r.hasAppearance||r.fillAlpha===0?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(r.name)?"paperclip":"pushpin"}.svg`,r.fillAlpha&&r.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(r.fillAlpha*100)}%);`)),i.addEventListener("dblclick",q(this,y_,VI).bind(this)),R(this,m_,i);const{isMac:o}=Ds.platform;return t.addEventListener("keydown",a=>{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<d;l+=2)a[l]=t+e[l]*i,a[l+1]=r+e[l+1]*o;return a}static _rescaleAndSwap(e,t,r,i,o,a){a||(a=new Float32Array(e.length));for(let l=0,d=e.length;l<d;l+=2)a[l]=t+e[l+1]*i,a[l+1]=r+e[l]*o;return a}static _translate(e,t,r,i){i||(i=new Float32Array(e.length));for(let o=0,a=e.length;o<a;o+=2)i[o]=t+e[o],i[o+1]=r+e[o+1];return i}static svgRound(e){return Math.round(e*1e4)}static _normalizePoint(e,t,r,i,o){switch(o){case 90:return[1-t/r,e/i];case 180:return[1-e/r,1-t/i];case 270:return[t/r,1-e/i];default:return[e/r,t/i]}}static _normalizePagePoint(e,t,r){switch(r){case 90:return[1-t,e];case 180:return[1-e,1-t];case 270:return[t,1-e];default:return[e,t]}}static createBezierPoints(e,t,r,i,o,a){return[(e+5*r)/6,(t+5*i)/6,(5*r+o)/6,(5*i+a)/6,(r+o)/2,(i+a)/2]}}ve(Wt,"PRECISION",1e-4);var Al,xc,Cv,Av,yu,Jn,Ny,Wy,w_,S_,Tv,Fv,Zp,j_,YT,QT,Hs,TS,VG,GG,KG,XG,YG,QG;const xh=class xh{constructor({x:e,y:t},r,i,o,a,l=0){N(this,Hs);N(this,Al);N(this,xc,[]);N(this,Cv);N(this,Av);N(this,yu,[]);N(this,Jn,new Float32Array(18));N(this,Ny);N(this,Wy);N(this,w_);N(this,S_);N(this,Tv);N(this,Fv);N(this,Zp,[]);R(this,Al,r),R(this,Fv,o*i),R(this,Av,a),h(this,Jn).set([NaN,NaN,NaN,NaN,e,t],6),R(this,Cv,l),R(this,S_,h(xh,j_)*i),R(this,w_,h(xh,QT)*i),R(this,Tv,i),h(this,Zp).push(e,t)}isEmpty(){return isNaN(h(this,Jn)[8])}add({x:e,y:t}){var A;R(this,Ny,e),R(this,Wy,t);const[r,i,o,a]=h(this,Al);let[l,d,c,u]=h(this,Jn).subarray(8,12);const f=e-c,p=t-u,g=Math.hypot(f,p);if(g<h(this,w_))return!1;const m=g-h(this,S_),y=m/g,v=y*f,x=y*p;let w=l,S=d;l=c,d=u,c+=v,u+=x,(A=h(this,Zp))==null||A.push(e,t);const _=-x/m,b=v/m,C=_*h(this,Fv),T=b*h(this,Fv);return h(this,Jn).set(h(this,Jn).subarray(2,8),0),h(this,Jn).set([c+C,u+T],4),h(this,Jn).set(h(this,Jn).subarray(14,18),12),h(this,Jn).set([c-C,u-T],16),isNaN(h(this,Jn)[6])?(h(this,yu).length===0&&(h(this,Jn).set([l+C,d+T],2),h(this,yu).push(NaN,NaN,NaN,NaN,(l+C-r)/o,(d+T-i)/a),h(this,Jn).set([l-C,d-T],14),h(this,xc).push(NaN,NaN,NaN,NaN,(l-C-r)/o,(d-T-i)/a)),h(this,Jn).set([w,S,l,d,c,u],6),!this.isEmpty()):(h(this,Jn).set([w,S,l,d,c,u],6),Math.abs(Math.atan2(S-d,w-l)-Math.atan2(x,v))<Math.PI/2?([l,d,c,u]=h(this,Jn).subarray(2,6),h(this,yu).push(NaN,NaN,NaN,NaN,((l+c)/2-r)/o,((d+u)/2-i)/a),[l,d,w,S]=h(this,Jn).subarray(14,18),h(this,xc).push(NaN,NaN,NaN,NaN,((w+l)/2-r)/o,((S+d)/2-i)/a),!0):([w,S,l,d,c,u]=h(this,Jn).subarray(0,6),h(this,yu).push(((w+5*l)/6-r)/o,((S+5*d)/6-i)/a,((5*l+c)/6-r)/o,((5*d+u)/6-i)/a,((l+c)/2-r)/o,((d+u)/2-i)/a),[c,u,l,d,w,S]=h(this,Jn).subarray(12,18),h(this,xc).push(((w+5*l)/6-r)/o,((S+5*d)/6-i)/a,((5*l+c)/6-r)/o,((5*d+u)/6-i)/a,((l+c)/2-r)/o,((d+u)/2-i)/a),!0))}toSVGPath(){if(this.isEmpty())return"";const e=h(this,yu),t=h(this,xc);if(isNaN(h(this,Jn)[6])&&!this.isEmpty())return q(this,Hs,VG).call(this);const r=[];r.push(`M${e[4]} ${e[5]}`);for(let i=6;i<e.length;i+=6)isNaN(e[i])?r.push(`L${e[i+4]} ${e[i+5]}`):r.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);q(this,Hs,KG).call(this,r);for(let i=t.length-6;i>=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<g;p+=2)d[p]=(h(this,Zp)[p]-i)/a,d[p+1]=(h(this,Zp)[p+1]-o)/l;if(d[d.length-2]=(h(this,Ny)-i)/a,d[d.length-1]=(h(this,Wy)-o)/l,isNaN(r[6])&&!this.isEmpty())return q(this,Hs,XG).call(this,d);const c=new Float32Array(h(this,yu).length+24+h(this,xc).length);let u=e.length;for(let p=0;p<u;p+=2){if(isNaN(e[p])){c[p]=c[p+1]=NaN;continue}c[p]=e[p],c[p+1]=e[p+1]}u=q(this,Hs,QG).call(this,c,u);for(let p=t.length-6;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;p<g;p+=2)t[p]=(t[p]-d)/u,t[p+1]=(t[p+1]-c)/f;for(let p=0,g=r.length;p<g;p+=2)r[p]=(r[p]-d)/u,r[p+1]=(r[p+1]-c)/f}toSVGPath(){const t=[`M${h(this,vs)[4]} ${h(this,vs)[5]}`];for(let r=6,i=h(this,vs).length;r<i;r+=6){if(isNaN(h(this,vs)[r])){t.push(`L${h(this,vs)[r+4]} ${h(this,vs)[r+5]}`);continue}t.push(`C${h(this,vs)[r]} ${h(this,vs)[r+1]} ${h(this,vs)[r+2]} ${h(this,vs)[r+3]} ${h(this,vs)[r+4]} ${h(this,vs)[r+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,r,i,o],a){const l=i-t,d=o-r;let c,u;switch(a){case 0:c=Wt._rescale(h(this,vs),t,o,l,-d),u=Wt._rescale(h(this,Tl),t,o,l,-d);break;case 90:c=Wt._rescaleAndSwap(h(this,vs),t,r,l,d),u=Wt._rescaleAndSwap(h(this,Tl),t,r,l,d);break;case 180:c=Wt._rescale(h(this,vs),i,r,-l,d),u=Wt._rescale(h(this,Tl),i,r,-l,d);break;case 270:c=Wt._rescaleAndSwap(h(this,vs),i,o,-l,-d),u=Wt._rescaleAndSwap(h(this,Tl),i,o,-l,-d);break}return{outline:Array.from(c),points:[Array.from(u)]}}get box(){return h(this,Uy)}newOutliner(t,r,i,o,a,l=0){return new _T(t,r,i,o,a,l)}getNewOutline(t,r){const[i,o,a,l]=h(this,Uy),[d,c,u,f]=h(this,Dv),p=a*u,g=l*f,m=i*u+d,y=o*f+c,v=this.newOutliner({x:h(this,Tl)[0]*p+m,y:h(this,Tl)[1]*g+y},h(this,Dv),h(this,__),t,h(this,k_),r??h(this,tf));for(let x=2;x<h(this,Tl).length;x+=2)v.add({x:h(this,Tl)[x]*p+m,y:h(this,Tl)[x+1]*g+y});return v.getOutlines()}}Dv=new WeakMap,Uy=new WeakMap,tf=new WeakMap,k_=new WeakMap,Tl=new WeakMap,__=new WeakMap,vs=new WeakMap,$T=new WeakSet,ZG=function(t){const r=h(this,vs);let i=r[4],o=r[5];const a=[i,o,i,o];let l=i,d=o,c=i,u=o;const f=t?Math.max:Math.min,p=new Float32Array(4);for(let m=6,y=r.length;m<y;m+=6){const v=r[m+4],x=r[m+5];isNaN(r[m])?(yt.pointBoundingBox(v,x,a),d>x?(l=v,d=x):d===x&&(l=f(l,v)),u<x?(c=v,u=x):u===x&&(c=f(c,v))):(p.set(hf,0),yt.bezierBoundingBox(i,o,...r.slice(m,m+6),p),yt.rectBoundingBox(...p,a),d>p[1]?(l=p[0],d=p[1]):d===p[1]&&(l=f(l,p[0])),u<p[3]?(c=p[2],u=p[3]):u===p[3]&&(c=f(c,p[2]))),i=v,o=x}const g=h(this,Uy);g[0]=a[0]-h(this,tf),g[1]=a[1]-h(this,tf),g[2]=a[2]-a[0]+2*h(this,tf),g[3]=a[3]-a[1]+2*h(this,tf),this.firstPoint=[l,d],this.lastPoint=[c,u]};var C_,A_,T_,Jp,bc,Ta,JG,rA,eK,tK,$I;class QI{constructor(e,t=0,r=0,i=!0){N(this,Ta);N(this,C_);N(this,A_);N(this,T_);N(this,Jp,[]);N(this,bc,[]);const o=hf.slice(),a=10**-4;for(const{x:y,y:v,width:x,height:w}of e){const S=Math.floor((y-t)/a)*a,_=Math.ceil((y+x+t)/a)*a,b=Math.floor((v-t)/a)*a,C=Math.ceil((v+w+t)/a)*a,T=[S,b,C,!0],F=[_,b,C,!1];h(this,Jp).push(T,F),yt.rectBoundingBox(S,b,_,C,o)}const l=o[2]-o[0]+2*r,d=o[3]-o[1]+2*r,c=o[0]-r,u=o[1]-r;let f=i?-1/0:1/0,p=1/0;const g=h(this,Jp).at(i?-1:-2),m=[g[0],g[2]];for(const y of h(this,Jp)){const[v,x,w,S]=y;!S&&i?x<p?(p=x,f=v):x===p&&(f=Math.max(f,v)):S&&!i&&(x<p?(p=x,f=v):x===p&&(f=Math.min(f,v))),y[0]=(v-c)/l,y[1]=(x-u)/d,y[2]=(w-u)/d}R(this,C_,new Float32Array([c,u,l,d])),R(this,A_,[f,p]),R(this,T_,m)}getOutlines(){h(this,Jp).sort((t,r)=>t[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;a<l;a+=2){const d=t[a][2],c=t[a+1][2];d.push(c),c.push(d),r.add(d),r.add(c)}const i=[];let o;for(;r.size>0;){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<e?r=o+1:i=o-1}return i+1},eK=function([,e,t]){const r=q(this,Ta,rA).call(this,e);h(this,bc).splice(r,0,[e,t])},tK=function([,e,t]){const r=q(this,Ta,rA).call(this,e);for(let i=r;i<h(this,bc).length;i++){const[o,a]=h(this,bc)[i];if(o!==e)break;if(o===e&&a===t){h(this,bc).splice(i,1);return}}for(let i=r-1;i>=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<a;l++){const[d,c]=h(this,bc)[l];for(let u=0,f=o.length;u<f;u++){const[,p,g]=o[u];if(!(c<=p||g<=d)){if(p>=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<r.length;a+=2){const l=r[a],d=r[a+1];l===i?(t.push(`V${d}`),o=d):d===o&&(t.push(`H${l}`),i=l)}t.push("Z")}return t.join(" ")}serialize([t,r,i,o],a){const l=[],d=i-t,c=o-r;for(const u of h(this,Ev)){const f=new Array(u.length);for(let p=0;p<u.length;p+=2)f[p]=t+u[p]*d,f[p+1]=o-u[p+1]*c;l.push(f)}return l}get box(){return h(this,F_)}get classNamesForOutlining(){return["highlightOutline"]}}F_=new WeakMap,Ev=new WeakMap;class ZI extends _T{newFreeDrawOutline(e,t,r,i,o,a){return new Uhe(e,t,r,i,o,a)}}class Uhe extends $G{newOutliner(e,t,r,i,o,a=0){return new ZI(e,t,r,i,o,a)}}var Pv,D_,nf,Hy,E_,Ga,P_,R_,qy,Fl,Dl,_o,Rv,Bv,ea,Iv,wd,B_,Un,JI,iA,nK,rK,iK,eM,cm,Fd,Fx,sK,sA,oA,oK,aK,lK,dK,cK;const Rr=class Rr extends xi{constructor(t){super({...t,name:"highlightEditor"});N(this,Un);N(this,Pv,null);N(this,D_,0);N(this,nf);N(this,Hy,null);N(this,E_,null);N(this,Ga,null);N(this,P_,null);N(this,R_,0);N(this,qy,null);N(this,Fl,null);N(this,Dl,null);N(this,_o,!1);N(this,Rv,null);N(this,Bv,null);N(this,ea,null);N(this,Iv,"");N(this,wd);N(this,B_,"");this.color=t.color||Rr._defaultColor,R(this,wd,t.thickness||Rr._defaultThickness),this.opacity=t.opacity||Rr._defaultOpacity,R(this,nf,t.boxes||null),R(this,B_,t.methodOfCreation||""),R(this,Iv,t.text||""),this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-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<l.length;b+=8)_.push({x:(l[b]-m)/p,y:1-(l[b+1]-y)/g,width:(l[b+2]-l[b])/p,height:(l[b+1]-l[b+5])/g});q(v=f,Un,JI).call(v),q(x=f,Un,cm).call(x),f.rotate(f.rotation)}else if(d||c){R(f,_o,!0);const _=(d||c.points)[0],b={x:_[0]-m,y:g-(_[1]-y)},C=new ZI(b,[0,0,p,g],1,h(f,wd)/2,!0,.001);for(let A=0,D=_.length;A<D;A+=2)b.x=_[A]-m,b.y=g-(_[A+1]-y),C.add(b);const{id:T,clipPathId:F}=r.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:f.color,"fill-opacity":f._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:C.toSVGPath()}},!0,!0);q(w=f,Un,iA).call(w,{highlightOutlines:C.getOutlines(),highlightId:T,clipPathId:F}),q(S=f,Un,cm).call(S),f.rotate(f.parentRotation)}return f}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const r=xi._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:r,opacity:this.opacity,thickness:h(this,wd),quadPoints:q(this,Un,oK).call(this),outlines:q(this,Un,aK).call(this,i.rect)}),this.addComment(i),this.annotationElementId&&!q(this,Un,cK).call(this,i)?null:(i.id=this.annotationElementId,i)}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}static canCreateNewEmptyEditor(){return!1}};Pv=new WeakMap,D_=new WeakMap,nf=new WeakMap,Hy=new WeakMap,E_=new WeakMap,Ga=new WeakMap,P_=new WeakMap,R_=new WeakMap,qy=new WeakMap,Fl=new WeakMap,Dl=new WeakMap,_o=new WeakMap,Rv=new WeakMap,Bv=new WeakMap,ea=new WeakMap,Iv=new WeakMap,wd=new WeakMap,B_=new WeakMap,Un=new WeakSet,JI=function(){const t=new QI(h(this,nf),.001);R(this,Fl,t.getOutlines()),[this.x,this.y,this.width,this.height]=h(this,Fl).box;const r=new QI(h(this,nf),.0025,.001,this._uiManager.direction==="ltr");R(this,Ga,r.getOutlines());const{firstPoint:i}=h(this,Fl);R(this,Rv,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]);const{lastPoint:o}=h(this,Ga);R(this,Bv,[(o[0]-this.x)/this.width,(o[1]-this.y)/this.height])},iA=function({highlightOutlines:t,highlightId:r,clipPathId:i}){var p,g;if(R(this,Fl,t),R(this,Ga,t.getNewOutline(h(this,wd)/2+1.5,.0025)),r>=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<t;e++){const{line:r,points:i}=h(this,oo)[e];R(this,so,r),R(this,ya,i),R(this,Sd,0),this.toSVGPath()}return{path:{d:h(this,Co)}}}toSVGPath(){const e=Wt.svgRound(h(this,so)[4]),t=Wt.svgRound(h(this,so)[5]);if(h(this,ya).length===2)return R(this,Co,`${h(this,Co)} M ${e} ${t} Z`),h(this,Co);if(h(this,ya).length<=6){const i=h(this,Co).lastIndexOf("M");R(this,Co,`${h(this,Co).slice(0,i)} M ${e} ${t}`),R(this,Sd,6)}if(h(this,ya).length===4){const i=Wt.svgRound(h(this,so)[10]),o=Wt.svgRound(h(this,so)[11]);return R(this,Co,`${h(this,Co)} L ${i} ${o}`),R(this,Sd,12),h(this,Co)}const r=[];h(this,Sd)===0&&(r.push(`M ${e} ${t}`),R(this,Sd,6));for(let i=h(this,Sd),o=h(this,so).length;i<o;i+=6){const[a,l,d,c,u,f]=h(this,so).slice(i,i+6).map(Wt.svgRound);r.push(`C${a} ${l} ${d} ${c} ${u} ${f}`)}return R(this,Co,h(this,Co)+r.join(" ")),R(this,Sd,h(this,so).length),h(this,Co)}getOutlines(e,t,r,i){const o=h(this,oo).at(-1);return o.line=new Float32Array(o.line),o.points=new Float32Array(o.points),h(this,Yy).build(h(this,oo),e,t,r,h(this,Xy),h(this,zv),i),R(this,xu,null),R(this,so,null),R(this,oo,null),R(this,Co,null),h(this,Yy)}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}xu=new WeakMap,so=new WeakMap,oo=new WeakMap,Xy=new WeakMap,zv=new WeakMap,ya=new WeakMap,Co=new WeakMap,Sd=new WeakMap,Yy=new WeakMap,Qy=new WeakMap,$y=new WeakMap,Ov=new WeakSet,lA=function(e,t){return Wt._normalizePoint(e,t,h(this,Qy),h(this,$y),h(this,Xy))};var xa,I_,M_,El,bu,vu,Lv,Nv,Zy,Fo,ph,fK,pK,gK;class hC extends Wt{constructor(){super(...arguments);N(this,Fo);N(this,xa);N(this,I_,0);N(this,M_);N(this,El);N(this,bu);N(this,vu);N(this,Lv);N(this,Nv);N(this,Zy)}build(t,r,i,o,a,l,d){R(this,bu,r),R(this,vu,i),R(this,Lv,o),R(this,Nv,a),R(this,Zy,l),R(this,M_,d??0),R(this,El,t),q(this,Fo,pK).call(this)}get thickness(){return h(this,Zy)}setLastElement(t){return h(this,El).push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return h(this,El).pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:r}of h(this,El)){if(t.push(`M${Wt.svgRound(r[4])} ${Wt.svgRound(r[5])}`),r.length===6){t.push("Z");continue}if(r.length===12&&isNaN(r[6])){t.push(`L${Wt.svgRound(r[10])} ${Wt.svgRound(r[11])}`);continue}for(let i=6,o=r.length;i<o;i+=6){const[a,l,d,c,u,f]=r.subarray(i,i+6).map(Wt.svgRound);t.push(`C${a} ${l} ${d} ${c} ${u} ${f}`)}}return t.join("")}serialize([t,r,i,o],a){const l=[],d=[],[c,u,f,p]=q(this,Fo,fK).call(this);let g,m,y,v,x,w,S,_,b;switch(h(this,Nv)){case 0:b=Wt._rescale,g=t,m=r+o,y=i,v=-o,x=t+c*i,w=r+(1-u-p)*o,S=t+(c+f)*i,_=r+(1-u)*o;break;case 90:b=Wt._rescaleAndSwap,g=t,m=r,y=i,v=o,x=t+u*i,w=r+c*o,S=t+(u+p)*i,_=r+(c+f)*o;break;case 180:b=Wt._rescale,g=t+i,m=r,y=-i,v=o,x=t+(1-c-f)*i,w=r+u*o,S=t+(1-c)*i,_=r+(u+p)*o;break;case 270:b=Wt._rescaleAndSwap,g=t+i,m=r+o,y=-i,v=-o,x=t+(1-u-p)*i,w=r+(1-c-f)*o,S=t+(1-u)*i,_=r+(1-c)*o;break}for(const{line:C,points:T}of h(this,El))l.push(b(C,g,m,y,v,a?new Array(C.length):null)),d.push(b(T,g,m,y,v,a?new Array(T.length):null));return{lines:l,points:d,rect:[x,w,S,_]}}static deserialize(t,r,i,o,a,{paths:{lines:l,points:d},rotation:c,thickness:u}){const f=[];let p,g,m,y,v;switch(c){case 0:v=Wt._rescale,p=-t/i,g=r/o+1,m=1/i,y=-1/o;break;case 90:v=Wt._rescaleAndSwap,p=-r/o,g=-t/i,m=1/o,y=1/i;break;case 180:v=Wt._rescale,p=t/i+1,g=-r/o,m=-1/i,y=1/o;break;case 270:v=Wt._rescaleAndSwap,p=r/o+1,g=t/i+1,m=-1/o,y=-1/i;break}if(!l){l=[];for(const w of d){const S=w.length;if(S===2){l.push(new Float32Array([NaN,NaN,NaN,NaN,w[0],w[1]]));continue}if(S===4){l.push(new Float32Array([NaN,NaN,NaN,NaN,w[0],w[1],NaN,NaN,NaN,NaN,w[2],w[3]]));continue}const _=new Float32Array(3*(S-2));l.push(_);let[b,C,T,F]=w.subarray(0,4);_.set([NaN,NaN,NaN,NaN,b,C],0);for(let A=4;A<S;A+=2){const D=w[A],P=w[A+1];_.set(Wt.createBezierPoints(b,C,T,F,D,P),(A-2)*3),[b,C,T,F]=[T,F,D,P]}}}for(let w=0,S=l.length;w<S;w++)f.push({line:v(l[w].map(_=>_??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;d<c;d+=6)yt.pointBoundingBox(o[d],o[d+1],t);continue}let a=o[4],l=o[5];for(let d=6,c=o.length;d<c;d+=6){const[u,f,p,g,m,y]=o.subarray(d,d+6);yt.bezierBoundingBox(a,l,u,f,p,g,m,y,t),a=m,l=y}}const[r,i]=q(this,Fo,ph).call(this);t[0]=Bi(t[0]-r,0,1),t[1]=Bi(t[1]-i,0,1),t[2]=Bi(t[2]+r,0,1),t[3]=Bi(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]},gK=function(t){const[r,i]=q(this,Fo,ph).call(this);R(this,Zy,t);const[o,a]=q(this,Fo,ph).call(this),[l,d]=[o-r,a-i],c=h(this,xa);return c[0]-=l,c[1]-=d,c[2]+=2*l,c[3]+=2*d,c};class fD extends uK{constructor(e){super(),this._viewParameters=e,super.updateProperties({fill:"none",stroke:xi._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(e,t){e==="stroke-width"&&(t??(t=this["stroke-width"]),t*=this._viewParameters.realScale),super.updateSVGProperty(e,t)}clone(){const e=new fD(this._viewParameters);return e.updateAll(this),e}}var ZT,mK;const $x=class $x extends AT{constructor(t){super({...t,name:"inkEditor"});N(this,ZT);this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,r){xi.initialize(t,r),this._defaultDrawingOptions=new fD(r.viewParameters)}static getDefaultDrawingOptions(t){const r=this._defaultDrawingOptions.clone();return r.updateProperties(t),r}static get supportMultipleDrawings(){return!0}static get typesMap(){return Cn(this,"typesMap",new Map([[Wn.INK_THICKNESS,"stroke-width"],[Wn.INK_COLOR,"stroke"],[Wn.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,r,i,o,a){return new Hhe(t,r,i,o,a,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,r,i,o,a,l){return hC.deserialize(t,r,i,o,a,l)}static async deserialize(t,r,i){let o=null;if(t instanceof O3){const{data:{inkLists:l,rect:d,rotation:c,id:u,color:f,opacity:p,borderStyle:{rawWidth:g},popupRef:m,richText:y,contentsObj:v,creationDate:x,modificationDate:w},parent:{page:{pageNumber:S}}}=t;o=t={annotationType:jn.INK,color:Array.from(f),thickness:g,opacity:p,paths:{points:l},boxes:null,pageIndex:S-1,rect:d.slice(0),rotation:c,annotationElementId:u,id:u,deleted:!1,popupRef:m,richText:y,comment:(v==null?void 0:v.str)||null,creationDate:x,modificationDate:w}}const a=await super.deserialize(t,r,i);return a._initialData=o,t.comment&&a.setCommentData(t),a}get toolbarButtons(){return this._colorPicker||(this._colorPicker=new jT(this)),[["colorPicker",this._colorPicker]]}get colorType(){return Wn.INK_COLOR}get colorAndOpacityType(){return Wn.INK_COLOR_AND_OPACITY}get opacityType(){return Wn.INK_OPACITY}updateParams(t,r){if(t===Wn.INK_COLOR_AND_OPACITY){this._updateColorAndOpacity(r.color,r.opacity);return}super.updateParams(t,r)}static updateDefaultParams(t,r){if(t===Wn.INK_COLOR_AND_OPACITY){super.updateDefaultParams(Wn.INK_COLOR,r.color),super.updateDefaultParams(Wn.INK_OPACITY,r.opacity);return}super.updateDefaultParams(t,r)}get color(){return this._drawingOptions.stroke}get opacity(){return this._drawingOptions["stroke-opacity"]}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:r,parent:i}=this;r.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(t,r.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:r,opacity:i}){this._drawingOptions=$x.getDefaultDrawingOptions({stroke:yt.makeHexColor(...t),"stroke-width":r,"stroke-opacity":i})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:r,points:i}=this.serializeDraw(t),{_drawingOptions:{stroke:o,"stroke-opacity":a,"stroke-width":l}}=this,d=Object.assign(super.serialize(t),{color:xi._colorManager.convert(o),opacity:a,thickness:l,paths:{lines:r,points:i}});return this.addComment(d),t?(d.isCopy=!0,d):this.annotationElementId&&!q(this,ZT,mK).call(this,d)?null:(d.id=this.annotationElementId,d)}renderAnnotationElement(t){if(this.deleted)return t.hide(),null;const{points:r,rect:i}=this.serializeDraw(!1);return t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:r,popup:this.comment}),null}};ZT=new WeakSet,mK=function(t){const{color:r,thickness:i,opacity:o,pageIndex:a}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized||t.color.some((l,d)=>l!==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;_<b;_++)S[_-2]=w[_]-w[_-2];y.write(S)}return y.close(),(await new Response(m.readable).bytes()).toBase64()}static async decompressSignature(e){try{const t=Uint8Array.fromBase64(e),{readable:r,writable:i}=new DecompressionStream("deflate-raw"),o=i.getWriter();await o.ready,o.write(t).then(async()=>{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;S<m;S++){const _=d[Gw*S+$2],b=new Float32Array(_+2);v.push(b);for(let C=0;C<Gw-1;C++)b[C]=d[Gw*S+$2+C+1];for(let C=0;C<_;C++)b[C+2]=b[C]+w[l++]}return{areContours:p,thickness:g,outlines:v,width:u,height:f}}catch(t){return Bn(`decompressSignature: ${t}`),null}}}Jy=new WeakMap,Vr=new WeakSet,oM=function(e,t,r,i){return r-=e,i-=t,r===0?i>0?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<o;u++)a[u]=e[u]<=i?1:0;for(let u=1;u<r-1;u++)a[u*t]=a[u*t+t-1]=0;for(let u=0;u<t;u++)a[u]=a[t*r-1-u]=0;let l=1,d;const c=[];for(let u=1;u<r-1;u++){d=1;for(let f=1;f<t-1;f++){const p=u*t+f,g=a[p];if(g===0)continue;let m=u,y=f;if(g===1&&a[p-1]===0)l+=1,y-=1;else if(g>=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;T<r-2;T+=2)i.push(e[T],e[T+1]);return}const o=e[t],a=e[t+1],l=e[r-4]-o,d=e[r-3]-a,c=Math.hypot(l,d),u=l/c,f=d/c,p=u*a-f*o,g=d/l,m=1/c,y=Math.atan(g),v=Math.cos(y),x=Math.sin(y),w=m*(Math.abs(v)+Math.abs(x)),S=m*(1-w+w**2),_=Math.max(Math.atan(Math.abs(x+v)*S),Math.atan(Math.abs(x-v)*S));let b=0,C=t;for(let T=t+2;T<r-2;T+=2){const F=Math.abs(p-u*e[T+1]+f*e[T]);F>b&&(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<a;y++){const v=(y-c)**2;for(let x=0;x<a;x++)l[y*a+x]=Math.exp((v+(x-c)**2)/d)}const u=new Float32Array(256),f=-2*o**2;for(let y=0;y<256;y++)u[y]=Math.exp(y**2/f);const p=e.length,g=new Uint8Array(p),m=new Uint32Array(256);for(let y=0;y<r;y++)for(let v=0;v<t;v++){const x=y*t+v,w=e[x];let S=0,_=0;for(let C=0;C<a;C++){const T=y+C-c;if(!(T<0||T>=r))for(let F=0;F<a;F++){const A=v+F-c;if(A<0||A>=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;l<d;l++){const c=r[l]=e[l<<2];i=Math.max(i,c),o=Math.min(o,c)}const a=255/(i-o);for(let l=0,d=r.length;l<d;l++)r[l]=(r[l]-o)*a;return r},dM=function(e){let t,r=-1/0,i=-1/0;const o=e.findIndex(d=>d!==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<m;x++){a=Math.ceil(p/2),l=Math.ceil(g/2);const w=new OffscreenCanvas(a,l);w.getContext("2d").drawImage(e,0,0,p,g,0,0,a,l),p=a,g=l,e!==t&&e.close(),e=w.transferToImageBitmap()}const v=Math.min(o/a,o/l);a=Math.round(a*v),l=Math.round(l*v)}const c=new OffscreenCanvas(a,l).getContext("2d",{willReadFrequently:!0});c.fillStyle="white",c.fillRect(0,0,a,l),c.filter="grayscale(1)",c.drawImage(e,0,0,e.width,e.height,0,0,a,l);const u=c.getImageData(0,0,a,l).data;return[q(this,Vr,lM).call(this,u),a,l]},N(df,Vr),N(df,Jy,{maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16}),N(df,vc,new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]));class L3 extends uK{constructor(){super(),super.updateProperties({fill:xi._defaultLineColor,"stroke-width":0})}clone(){const e=new L3;return e.updateAll(this),e}}class N3 extends fD{constructor(e){super(e),super.updateProperties({stroke:xi._defaultLineColor,"stroke-width":1})}clone(){const e=new N3(this._viewParameters);return e.updateAll(this),e}}var eg,wu,tg,e0;const gl=class gl extends AT{constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"});N(this,eg,!1);N(this,wu,null);N(this,tg,null);N(this,e0,null);this._willKeepAspectRatio=!0,R(this,tg,t.signatureData||null),R(this,wu,null),this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,r){xi.initialize(t,r),this._defaultDrawingOptions=new L3,this._defaultDrawnSignatureOptions=new N3(r.viewParameters)}static getDefaultDrawingOptions(t){const r=this._defaultDrawingOptions.clone();return r.updateProperties(t),r}static get supportMultipleDrawings(){return!1}static get typesMap(){return Cn(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!h(this,wu)}}static computeTelemetryFinalData(t){const r=t.get("hasDescription");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}get isResizable(){return!0}onScaleChanging(){this._drawId!==null&&super.onScaleChanging()}render(){if(this.div)return this.div;let t,r;const{_isCopy:i}=this;if(i&&(this._isCopy=!1,t=this.x,r=this.y),super.render(),this._drawId===null)if(h(this,tg)){const{lines:o,mustSmooth:a,areContours:l,description:d,uuid:c,heightInPage:u}=h(this,tg),{rawDims:{pageWidth:f,pageHeight:p},rotation:g}=this.parent.viewport,m=df.processDrawnLines({lines:o,pageWidth:f,pageHeight:p,rotation:g,innerMargin:gl._INNER_MARGIN,mustSmooth:a,areContours:l});this.addSignature(m,u,d,c)}else this.div.setAttribute("data-l10n-args",JSON.stringify({description:""})),this.div.hidden=!0,this._uiManager.getSignature(this);else this.div.setAttribute("data-l10n-args",JSON.stringify({description:h(this,wu)||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,r)),this.div}setUuid(t){R(this,e0,t),this.addEditToolbar()}getUuid(){return h(this,e0)}get description(){return h(this,wu)}set description(t){R(this,wu,t),this.div&&(this.div.setAttribute("data-l10n-args",JSON.stringify({description:t})),super.addEditToolbar().then(r=>{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.width<t&&d.height<t)g=d.width,m=d.height;else if(d=h(this,Ri),o>t||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<h(this,Kv).length;t+=6){const r=q(this,eF,AK).call(this,h(this,Kv).subarray(t,t+6));r&&e.append(r)}return e.addEventListener("contextmenu",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<h(this,Xv)||d<h(this,Xv))return null;const c=[(o-e)*h(this,ju)/l,(a-t)*h(this,ku)/l,(r-e)*h(this,ju)/d,(i-t)*h(this,ku)/d,0,0],u=yt.inverseTransform(c),f=document.createElement("canvas");return f.className="textLayerImagePlaceholder",f.width=0,f.height=0,Object.assign(f.style,{opacity:0,position:"absolute",left:Z2(e),top:Z2(t),width:Z2(l/h(this,ju)),height:Z2(d/h(this,ku)),transformOrigin:"0% 0%",transform:`matrix(${c.join(",")})`}),h(this,O_).set(f,{inverseTransform:u,width:l,height:d,x1:e,y1:t}),f},N(oj,N_,null);let vM=oj;globalThis._pdfjsTestingUtils={HighlightOutliner:QI};globalThis.pdfjsLib={AbortException:Ng,AnnotationEditorLayer:fM,AnnotationEditorParamsType:Wn,AnnotationEditorType:jn,AnnotationEditorUIManager:_0,AnnotationLayer:GI,AnnotationMode:Ru,AnnotationType:Cs,applyOpacity:sue,build:vhe,ColorPicker:ST,createValidAbsoluteUrl:aV,CSSConstants:iue,DOMSVGFactory:kT,DrawLayer:yM,FeatureTest:Ds,fetchData:E3,findContrastColor:oue,getDocument:kG,getFilenameFromUrl:Zce,getPdfFilenameFromUrl:Jce,getRGB:cC,getRGBA:B3,getUuid:dV,getXfaPageViewport:tue,GlobalWorkerOptions:Bu,ImageKind:E5,InvalidPDFException:XB,isDataScheme:iD,isPdfFile:R3,isValidExplicitDest:kue,makeArr:F3,makeMap:D3,makeObj:QB,MathClamp:Bi,noContextMenu:Hd,normalizeUnicode:Qce,OPS:Sh,OutputScale:Lu,PasswordResponses:Uce,PDFDataRangeTransport:_G,PDFDateString:bT,PDFWorker:$j,PermissionFlag:Wce,PixelsPerInch:Wg,RenderingCancelledException:P3,renderRichText:uV,ResponseException:xT,setLayerDimensions:k0,shadow:Cn,SignatureExtractor:df,stopEvent:$i,SupportedImageMimeTypes:$B,TextLayer:Qj,TextLayerImages:vM,TouchManager:wT,updateUrlHash:lV,Util:yt,VerbosityLevel:eD,version:bhe,XfaLayer:cV};const TK={invoices:{query:"search-invoices-query",includeLineItems:"search-invoices-include-line-items",supplier:"search-invoices-supplier",status:"search-invoices-status",dateFrom:"search-invoices-from",dateTo:"search-invoices-to",groupBy:"search-invoices-group",sortColumn:"search-invoices-sort-column",sortDirection:"search-invoices-sort-direction"},lineItems:{query:"search-line-items-query",supplier:"search-line-items-supplier",dateFrom:"search-line-items-from",dateTo:"search-line-items-to",groupBy:"search-line-items-group",priceChangeFilter:"search-line-items-price-change",mappedFilter:"search-line-items-mapped",sortColumn:"search-line-items-sort-column",sortDirection:"search-line-items-sort-direction"}};function Rg(n,e){const[t,r]=k.useState(n);return k.useEffect(()=>{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)&&ne;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&&oe<be.length-1&&((rw=be[oe+1])==null?void 0:rw.page_number)!==B.page_number,Jr=en?"#fff8e1":Kt?"#fff0f3":void 0,ei=Jr?{backgroundColor:Jr}:void 0;let Ui=Nn?{...ei,border:"2px solid #ffc107"}:ei;Fn&&!Nn&&(Ui={...Ui,borderBottom:"2px dashed #adb5bd"});const Uo=lr?{borderLeft:"2px solid #dc3545",borderTop:"2px solid #dc3545",borderBottom:"2px solid #dc3545",backgroundColor:"#ffe6e6"}:{},da=lr?{borderTop:"2px solid #dc3545",borderBottom:"2px solid #dc3545",backgroundColor:"#ffe6e6"}:{},zf=lr?{borderRight:"2px solid #dc3545",borderTop:"2px solid #dc3545",borderBottom:"2px solid #dc3545",backgroundColor:"#ffe6e6"}:{};return s.jsxs(nF.Fragment,{children:[s.jsxs("tr",{style:Ui,"data-page":B.page_number||1,children:[s.jsx("td",{style:fe.td,children:Ae&&s.jsx("button",{type:"button",onClick:()=>fC(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:oe<Dr.length-1?"1px solid #f0c36d":"none",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"#333"},children:((be=B.description)==null?void 0:be.split(`
`)[0])||"(no description)"}),B.amount!=null&&s.jsxs("span",{style:{fontSize:"0.85rem",color:"#856404",fontWeight:600,whiteSpace:"nowrap"},children:["£",B.amount.toFixed(2)]})]},oe)})}),s.jsxs("p",{style:{fontSize:"0.8rem",color:"#888",marginBottom:"1.25rem"},children:["Confirming will include ",Dr.length!==1?"these items":"this item"," in the stock cost. Mark ",Dr.length!==1?"them":"it"," as non-stock first if that was not intended."]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>Gn(!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<it.length-1?"0.5rem":0},onMouseEnter:Nn=>{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<S;He++)for(let Ge=0;Ge<7;Ge++){const ae=new Date(ge);ae.setDate(ge.getDate()+He*7+Ge);const K=(ae.getDay()+6)%7;ee.includes(K)&&Z.push(ae.toISOString().slice(0,10))}const Te=[...new Set(Z)].sort();if(Te.length===0)return[];const Be=Math.round(ne/Te.length*100)/100;return Te.map((He,Ge)=>({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),we<pe},K=X=>X.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<t&&r(Se),l(""),c("custom")},b=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<t&&r(J),l(""),c("custom")},b=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<t&&r(z),l(""),c("custom")},S=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:we<Q.ingredient_changes.length-1?"1px solid #eee":"none",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#888",marginRight:"0.5rem",fontSize:"0.75rem"},children:pe.date}),pe.source_invoice_id&&s.jsx("span",{style:{cursor:"pointer",color:"#e94560",marginRight:"0.5rem",textDecoration:"underline",fontSize:"0.75rem"},onClick:()=>e(`/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:y<g.ingredient_changes.length-1?"1px solid #eee":"none",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#888",marginRight:"0.5rem"},children:m.date}),m.source_invoice_id&&s.jsx("span",{style:{cursor:"pointer",color:"#e94560",marginRight:"0.5rem",textDecoration:"underline"},onClick:()=>e(`/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,{})})})}));