diff --git a/frontend/dist/assets/index-Cs9AL0NS.css b/frontend/dist/assets/index-Cs9AL0NS.css deleted file mode 100644 index 7b56835..0000000 --- a/frontend/dist/assets/index-Cs9AL0NS.css +++ /dev/null @@ -1 +0,0 @@ -:root{--navy: #1a1a2e;--navy-dark: #0f0f20;--gold: #c9a84c;--gold-light: #e8c96d;--surface: rgba(255,255,255,.07);--surface-2: rgba(255,255,255,.08);--text: rgba(255,255,255,.88);--text-muted: rgba(255,255,255,.48);--body-bg: #f4f5f7;--card-bg: #ffffff;--card-border: #e4e8ee;--text-dark: #1e293b;--text-mid: #64748b;--shadow-sm: 0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.04);--shadow-md: 0 4px 12px rgba(0,0,0,.08);--danger: #dc2626;--success: #16a34a;--warning: #d97706;--radius: 10px;--font: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--app-primary: #0d9488}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}body{background:var(--body-bg);color:var(--text-dark);font-family:var(--font);font-size:14px;line-height:1.5}.app-shell{display:grid;grid-template-columns:220px 1fr;grid-template-rows:auto 1fr;min-height:100vh}.sidebar{grid-column:1;grid-row:1 / -1;background:var(--navy);display:flex;flex-direction:column;position:sticky;top:0;height:100vh;overflow-y:auto}.sidebar-logo{display:flex;align-items:center;gap:10px;padding:20px 16px 16px;font-size:15px;font-weight:600;color:var(--text);border-bottom:1px solid var(--surface)}.sidebar-nav{flex:1;padding:8px;display:flex;flex-direction:column}.sidebar-section{margin-top:4px}.sidebar-section-label{padding:8px 10px 4px;font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:var(--text-muted)}.sidebar-nav a{display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:7px;color:var(--text-muted);text-decoration:none;font-size:13px;transition:background .15s,color .15s}.sidebar-nav a:hover{background:var(--surface);color:var(--text)}.sidebar-nav a.active{background:#c9a84c26;color:var(--gold)}.sidebar-user{padding:12px 16px;font-size:11px;color:var(--text-muted);border-top:1px solid var(--surface);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.top-bar{display:none}.page-content{grid-column:2;grid-row:1 / -1;min-width:0;padding:24px;background:var(--body-bg)}.card{background:var(--card-bg);border:1px solid var(--card-border);border-radius:var(--radius);box-shadow:var(--shadow-sm)}.card-header{padding:16px 20px;border-bottom:1px solid var(--card-border);font-size:14px;font-weight:600;color:var(--text-dark);display:flex;align-items:center;justify-content:space-between}.card-body{padding:20px}.btn{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:7px;font-size:13px;font-weight:500;cursor:pointer;border:none;transition:background .15s,opacity .15s}.btn:disabled{opacity:.5;cursor:not-allowed}.btn-primary{background:var(--gold);color:var(--navy)}.btn-primary:hover:not(:disabled){background:var(--gold-light)}.btn-secondary{background:var(--navy);color:var(--text)}.btn-secondary:hover:not(:disabled){background:var(--navy-dark)}.btn-outline{background:transparent;color:var(--text-dark);border:1px solid var(--card-border)}.btn-outline:hover:not(:disabled){background:var(--body-bg)}.btn-danger{background:var(--danger);color:#fff}.btn-danger:hover:not(:disabled){opacity:.85}.btn-sm{padding:4px 10px;font-size:12px}input,select,textarea{background:var(--card-bg);border:1px solid var(--card-border);border-radius:7px;padding:7px 10px;font-size:13px;color:var(--text-dark);width:100%;outline:none;transition:border-color .15s}input:focus,select:focus,textarea:focus{border-color:var(--gold)}.badge{display:inline-flex;align-items:center;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:500}.badge-success{background:#dcfce7;color:#16a34a}.badge-warning{background:#fef3c7;color:#d97706}.badge-danger{background:#fee2e2;color:#dc2626}.badge-info{background:#dbeafe;color:#2563eb}.badge-neutral{background:#f1f5f9;color:#64748b}.table-wrap{overflow-x:auto}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;padding:8px 12px;background:#f8fafc;border-bottom:1px solid var(--card-border);font-weight:600;color:var(--text-mid);white-space:nowrap}td{padding:8px 12px;border-bottom:1px solid #f1f5f9;color:var(--text-dark)}tr:last-child td{border-bottom:none}tr:hover td{background:#f8fafc}.page-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;gap:16px}.page-title{font-size:20px;font-weight:700;color:var(--text-dark)}.page-subtitle{font-size:13px;color:var(--text-mid);margin-top:2px}.sub-nav{display:flex;gap:4px;border-bottom:1px solid var(--card-border);margin-bottom:24px;overflow-x:auto}.sub-nav-item{padding:8px 14px;font-size:13px;font-weight:500;color:var(--text-mid);cursor:pointer;border-bottom:2px solid transparent;white-space:nowrap;background:none;border-left:none;border-right:none;border-top:none;transition:color .15s,border-color .15s}.sub-nav-item:hover{color:var(--text-dark)}.sub-nav-item.active{color:var(--gold);border-bottom-color:var(--gold)}.status-dot{width:8px;height:8px;border-radius:50%;display:inline-block}.status-dot.green{background:var(--success)}.status-dot.yellow{background:var(--warning)}.status-dot.red{background:var(--danger)}.status-dot.grey{background:#94a3b8}.spinner{width:20px;height:20px;border:2px solid var(--card-border);border-top-color:var(--gold);border-radius:50%;animation:spin .7s linear infinite;display:inline-block}@keyframes spin{to{transform:rotate(360deg)}}.loading-state{display:flex;align-items:center;justify-content:center;gap:10px;padding:60px 20px;color:var(--text-mid);font-size:13px}.empty-state{text-align:center;padding:60px 20px;color:var(--text-mid);font-size:13px}.grid-2{display:grid;grid-template-columns:repeat(2,1fr);gap:16px}.grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}.grid-4{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.stat-card{background:var(--card-bg);border:1px solid var(--card-border);border-radius:var(--radius);padding:16px 20px;box-shadow:var(--shadow-sm)}.stat-label{font-size:12px;color:var(--text-mid);margin-bottom:4px}.stat-value{font-size:24px;font-weight:700;color:var(--text-dark)}.stat-delta{font-size:12px;margin-top:4px}.stat-delta.positive{color:var(--success)}.stat-delta.negative{color:var(--danger)}.stat-delta.neutral{color:var(--text-mid)}@media (max-width: 900px){.app-shell{grid-template-columns:1fr;grid-template-rows:auto 1fr}.sidebar{display:none}.top-bar{display:flex;align-items:center;gap:12px;background:var(--navy);padding:0 16px;height:52px;grid-column:1;grid-row:1;overflow-x:auto}.top-bar-title{font-size:14px;font-weight:600;color:var(--text);white-space:nowrap;margin-right:8px}.top-bar-nav{display:flex;gap:4px}.top-bar-nav a{color:var(--text-muted);text-decoration:none;font-size:12.5px;padding:6px 10px;border-radius:6px;white-space:nowrap}.top-bar-nav a:hover{color:var(--text);background:var(--surface)}.top-bar-nav a.active{color:var(--gold)}.page-content{grid-column:1;grid-row:2;padding:16px}}.sidebar::-webkit-scrollbar,.sidebar-nav::-webkit-scrollbar{width:4px}.sidebar::-webkit-scrollbar-track,.sidebar-nav::-webkit-scrollbar-track{background:transparent}.sidebar::-webkit-scrollbar-thumb,.sidebar-nav::-webkit-scrollbar-thumb{background:#c9a84c59;border-radius:2px}.sidebar::-webkit-scrollbar-thumb:hover,.sidebar-nav::-webkit-scrollbar-thumb:hover{background:#c9a84ca6}.sidebar,.sidebar-nav{scrollbar-width:thin;scrollbar-color:rgba(201,168,76,.35) transparent} diff --git a/frontend/dist/assets/index-DiXG3yPo.js b/frontend/dist/assets/index-DiXG3yPo.js deleted file mode 100644 index 6bcecba..0000000 --- a/frontend/dist/assets/index-DiXG3yPo.js +++ /dev/null @@ -1,445 +0,0 @@ -var MX=Object.defineProperty;var D8=n=>{throw TypeError(n)};var zX=(n,e,t)=>e in n?MX(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ve=(n,e,t)=>zX(n,typeof e!="symbol"?e+"":e,t),EE=(n,e,t)=>e.has(n)||D8("Cannot "+t);var h=(n,e,t)=>(EE(n,e,"read from private field"),t?t.call(n):e.get(n)),N=(n,e,t)=>e.has(n)?D8("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),R=(n,e,t,r)=>(EE(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),q=(n,e,t)=>(EE(n,e,"access private method"),t);var Gi=(n,e,t,r)=>({set _(i){R(n,e,i,t)},get _(){return h(n,e,r)}});function OX(n,e){for(var t=0;tr[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function t(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=t(i);fetch(i.href,o)}})();function a7(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var l7={exports:{}},tF={},d7={exports:{}},nr={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var W_=Symbol.for("react.element"),LX=Symbol.for("react.portal"),NX=Symbol.for("react.fragment"),WX=Symbol.for("react.strict_mode"),UX=Symbol.for("react.profiler"),HX=Symbol.for("react.provider"),qX=Symbol.for("react.context"),VX=Symbol.for("react.forward_ref"),GX=Symbol.for("react.suspense"),KX=Symbol.for("react.memo"),XX=Symbol.for("react.lazy"),E8=Symbol.iterator;function YX(n){return n===null||typeof n!="object"?null:(n=E8&&n[E8]||n["@@iterator"],typeof n=="function"?n:null)}var c7={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},u7=Object.assign,h7={};function c1(n,e,t){this.props=n,this.context=e,this.refs=h7,this.updater=t||c7}c1.prototype.isReactComponent={};c1.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,n,e,"setState")};c1.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function f7(){}f7.prototype=c1.prototype;function jM(n,e,t){this.props=n,this.context=e,this.refs=h7,this.updater=t||c7}var kM=jM.prototype=new f7;kM.constructor=jM;u7(kM,c1.prototype);kM.isPureReactComponent=!0;var P8=Array.isArray,p7=Object.prototype.hasOwnProperty,_M={current:null},g7={key:!0,ref:!0,__self:!0,__source:!0};function m7(n,e,t){var r,i={},o=null,a=null;if(e!=null)for(r in e.ref!==void 0&&(a=e.ref),e.key!==void 0&&(o=""+e.key),e)p7.call(e,r)&&!g7.hasOwnProperty(r)&&(i[r]=e[r]);var l=arguments.length-2;if(l===1)i.children=t;else if(1>>1,re=H[te];if(0>>1;tei(ne,G))yei(ke,ne)?(H[te]=ke,H[ye]=G,te=ye):(H[te]=ne,H[J]=G,te=J);else if(yei(ke,G))H[te]=ke,H[ye]=G,te=ye;else break e}}return z}function i(H,z){var G=H.sortIndex-z.sortIndex;return G!==0?G:H.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;n.unstable_now=function(){return o.now()}}else{var a=Date,l=a.now();n.unstable_now=function(){return a.now()-l}}var d=[],c=[],u=1,f=null,p=3,g=!1,m=!1,y=!1,v=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function S(H){for(var z=t(c);z!==null;){if(z.callback===null)r(c);else if(z.startTime<=H)r(c),z.sortIndex=z.expirationTime,e(d,z);else break;z=t(c)}}function _(H){if(y=!1,S(H),!m)if(t(d)!==null)m=!0,M(b);else{var z=t(c);z!==null&&I(_,z.startTime-H)}}function b(H,z){m=!1,y&&(y=!1,x(F),F=-1),g=!0;var G=p;try{for(S(z),f=t(d);f!==null&&(!(f.expirationTime>z)||H&&!P());){var te=f.callback;if(typeof te=="function"){f.callback=null,p=f.priorityLevel;var re=te(f.expirationTime<=z);z=n.unstable_now(),typeof re=="function"?f.callback=re:f===t(d)&&r(d),S(z)}else r(d);f=t(d)}if(f!==null)var me=!0;else{var J=t(c);J!==null&&I(_,J.startTime-z),me=!1}return me}finally{f=null,p=G,g=!1}}var C=!1,T=null,F=-1,A=5,D=-1;function P(){return!(n.unstable_now()-DH||125te?(H.sortIndex=G,e(c,H),t(d)===null&&H===t(c)&&(y?(x(F),F=-1):y=!0,I(_,G-te))):(H.sortIndex=re,e(d,H),m||g||(m=!0,M(b))),H},n.unstable_shouldYield=P,n.unstable_wrapCallback=function(H){var z=p;return function(){var G=p;p=z;try{return H.apply(this,arguments)}finally{p=G}}}})(w7);v7.exports=w7;var aY=v7.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var lY=k,Xl=aY;function ft(n){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+n,t=1;t"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),eR=Object.prototype.hasOwnProperty,dY=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,B8={},I8={};function cY(n){return eR.call(I8,n)?!0:eR.call(B8,n)?!1:dY.test(n)?I8[n]=!0:(B8[n]=!0,!1)}function uY(n,e,t,r){if(t!==null&&t.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:t!==null?!t.acceptsBooleans:(n=n.toLowerCase().slice(0,5),n!=="data-"&&n!=="aria-");default:return!1}}function hY(n,e,t,r){if(e===null||typeof e>"u"||uY(n,e,t,r))return!0;if(r)return!1;if(t!==null)switch(t.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Da(n,e,t,r,i,o,a){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=n,this.type=e,this.sanitizeURL=o,this.removeEmptyString=a}var zo={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(n){zo[n]=new Da(n,0,!1,n,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(n){var e=n[0];zo[e]=new Da(e,1,!1,n[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(n){zo[n]=new Da(n,2,!1,n.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(n){zo[n]=new Da(n,2,!1,n,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(n){zo[n]=new Da(n,3,!1,n.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(n){zo[n]=new Da(n,3,!0,n,null,!1,!1)});["capture","download"].forEach(function(n){zo[n]=new Da(n,4,!1,n,null,!1,!1)});["cols","rows","size","span"].forEach(function(n){zo[n]=new Da(n,6,!1,n,null,!1,!1)});["rowSpan","start"].forEach(function(n){zo[n]=new Da(n,5,!1,n.toLowerCase(),null,!1,!1)});var AM=/[\-:]([a-z])/g;function TM(n){return n[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(n){var e=n.replace(AM,TM);zo[e]=new Da(e,1,!1,n,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(n){var e=n.replace(AM,TM);zo[e]=new Da(e,1,!1,n,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(n){var e=n.replace(AM,TM);zo[e]=new Da(e,1,!1,n,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(n){zo[n]=new Da(n,1,!1,n.toLowerCase(),null,!1,!1)});zo.xlinkHref=new Da("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(n){zo[n]=new Da(n,1,!1,n.toLowerCase(),null,!0,!0)});function FM(n,e,t,r){var i=zo.hasOwnProperty(e)?zo[e]:null;(i!==null?i.type!==0:r||!(2l||i[a]!==o[l]){var d=` -`+i[a].replace(" at new "," at ");return n.displayName&&d.includes("")&&(d=d.replace("",n.displayName)),d}while(1<=a&&0<=l);break}}}finally{BE=!1,Error.prepareStackTrace=t}return(n=n?n.displayName||n.name:"")?Xw(n):""}function fY(n){switch(n.tag){case 5:return Xw(n.type);case 16:return Xw("Lazy");case 13:return Xw("Suspense");case 19:return Xw("SuspenseList");case 0:case 2:case 15:return n=IE(n.type,!1),n;case 11:return n=IE(n.type.render,!1),n;case 1:return n=IE(n.type,!0),n;default:return""}}function iR(n){if(n==null)return null;if(typeof n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n;switch(n){case Rx:return"Fragment";case Px:return"Portal";case tR:return"Profiler";case DM:return"StrictMode";case nR:return"Suspense";case rR:return"SuspenseList"}if(typeof n=="object")switch(n.$$typeof){case k7:return(n.displayName||"Context")+".Consumer";case j7:return(n._context.displayName||"Context")+".Provider";case EM:var e=n.render;return n=n.displayName,n||(n=e.displayName||e.name||"",n=n!==""?"ForwardRef("+n+")":"ForwardRef"),n;case PM:return e=n.displayName||null,e!==null?e:iR(n.type)||"Memo";case ep:e=n._payload,n=n._init;try{return iR(n(e))}catch{}}return null}function pY(n){var e=n.type;switch(n.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return n=e.render,n=n.displayName||n.name||"",e.displayName||(n!==""?"ForwardRef("+n+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return iR(e);case 8:return e===DM?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function Bg(n){switch(typeof n){case"boolean":case"number":case"string":case"undefined":return n;case"object":return n;default:return""}}function C7(n){var e=n.type;return(n=n.nodeName)&&n.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function gY(n){var e=C7(n)?"checked":"value",t=Object.getOwnPropertyDescriptor(n.constructor.prototype,e),r=""+n[e];if(!n.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var i=t.get,o=t.set;return Object.defineProperty(n,e,{configurable:!0,get:function(){return i.call(this)},set:function(a){r=""+a,o.call(this,a)}}),Object.defineProperty(n,e,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){n._valueTracker=null,delete n[e]}}}}function ZC(n){n._valueTracker||(n._valueTracker=gY(n))}function A7(n){if(!n)return!1;var e=n._valueTracker;if(!e)return!0;var t=e.getValue(),r="";return n&&(r=C7(n)?n.checked?"true":"false":n.value),n=r,n!==t?(e.setValue(n),!0):!1}function gA(n){if(n=n||(typeof document<"u"?document:void 0),typeof n>"u")return null;try{return n.activeElement||n.body}catch{return n.body}}function sR(n,e){var t=e.checked;return ns({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??n._wrapperState.initialChecked})}function z8(n,e){var t=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;t=Bg(e.value!=null?e.value:t),n._wrapperState={initialChecked:r,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function T7(n,e){e=e.checked,e!=null&&FM(n,"checked",e,!1)}function oR(n,e){T7(n,e);var t=Bg(e.value),r=e.type;if(t!=null)r==="number"?(t===0&&n.value===""||n.value!=t)&&(n.value=""+t):n.value!==""+t&&(n.value=""+t);else if(r==="submit"||r==="reset"){n.removeAttribute("value");return}e.hasOwnProperty("value")?aR(n,e.type,t):e.hasOwnProperty("defaultValue")&&aR(n,e.type,Bg(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(n.defaultChecked=!!e.defaultChecked)}function O8(n,e,t){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+n._wrapperState.initialValue,t||e===n.value||(n.value=e),n.defaultValue=e}t=n.name,t!==""&&(n.name=""),n.defaultChecked=!!n._wrapperState.initialChecked,t!==""&&(n.name=t)}function aR(n,e,t){(e!=="number"||gA(n.ownerDocument)!==n)&&(t==null?n.defaultValue=""+n._wrapperState.initialValue:n.defaultValue!==""+t&&(n.defaultValue=""+t))}var Yw=Array.isArray;function Zx(n,e,t,r){if(n=n.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=JC.firstChild;n.firstChild;)n.removeChild(n.firstChild);for(;e.firstChild;)n.appendChild(e.firstChild)}});function lj(n,e){if(e){var t=n.firstChild;if(t&&t===n.lastChild&&t.nodeType===3){t.nodeValue=e;return}}n.textContent=e}var RS={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},mY=["Webkit","ms","Moz","O"];Object.keys(RS).forEach(function(n){mY.forEach(function(e){e=e+n.charAt(0).toUpperCase()+n.substring(1),RS[e]=RS[n]})});function P7(n,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||RS.hasOwnProperty(n)&&RS[n]?(""+e).trim():e+"px"}function R7(n,e){n=n.style;for(var t in e)if(e.hasOwnProperty(t)){var r=t.indexOf("--")===0,i=P7(t,e[t],r);t==="float"&&(t="cssFloat"),r?n.setProperty(t,i):n[t]=i}}var yY=ns({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function cR(n,e){if(e){if(yY[n]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(ft(137,n));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(ft(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(ft(61))}if(e.style!=null&&typeof e.style!="object")throw Error(ft(62))}}function uR(n,e){if(n.indexOf("-")===-1)return typeof e.is=="string";switch(n){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var hR=null;function RM(n){return n=n.target||n.srcElement||window,n.correspondingUseElement&&(n=n.correspondingUseElement),n.nodeType===3?n.parentNode:n}var fR=null,Jx=null,eb=null;function W8(n){if(n=q_(n)){if(typeof fR!="function")throw Error(ft(280));var e=n.stateNode;e&&(e=aF(e),fR(n.stateNode,n.type,e))}}function B7(n){Jx?eb?eb.push(n):eb=[n]:Jx=n}function I7(){if(Jx){var n=Jx,e=eb;if(eb=Jx=null,W8(n),e)for(n=0;n>>=0,n===0?32:31-(TY(n)/FY|0)|0}var e2=64,t2=4194304;function Qw(n){switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return n&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return n}}function bA(n,e){var t=n.pendingLanes;if(t===0)return 0;var r=0,i=n.suspendedLanes,o=n.pingedLanes,a=t&268435455;if(a!==0){var l=a&~i;l!==0?r=Qw(l):(o&=a,o!==0&&(r=Qw(o)))}else a=t&~i,a!==0?r=Qw(a):o!==0&&(r=Qw(o));if(r===0)return 0;if(e!==0&&e!==r&&!(e&i)&&(i=r&-r,o=e&-e,i>=o||i===16&&(o&4194240)!==0))return e;if(r&4&&(r|=t&16),e=n.entangledLanes,e!==0)for(n=n.entanglements,e&=r;0t;t++)e.push(n);return e}function U_(n,e,t){n.pendingLanes|=e,e!==536870912&&(n.suspendedLanes=0,n.pingedLanes=0),n=n.eventTimes,e=31-Tc(e),n[e]=t}function RY(n,e){var t=n.pendingLanes&~e;n.pendingLanes=e,n.suspendedLanes=0,n.pingedLanes=0,n.expiredLanes&=e,n.mutableReadLanes&=e,n.entangledLanes&=e,e=n.entanglements;var r=n.eventTimes;for(n=n.expirationTimes;0=IS),Q8=" ",$8=!1;function tW(n,e){switch(n){case"keyup":return aQ.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function nW(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Bx=!1;function dQ(n,e){switch(n){case"compositionend":return nW(e);case"keypress":return e.which!==32?null:($8=!0,Q8);case"textInput":return n=e.data,n===Q8&&$8?null:n;default:return null}}function cQ(n,e){if(Bx)return n==="compositionend"||!WM&&tW(n,e)?(n=J7(),r5=OM=dg=null,Bx=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:t,offset:e-n};n=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=tz(t)}}function oW(n,e){return n&&e?n===e?!0:n&&n.nodeType===3?!1:e&&e.nodeType===3?oW(n,e.parentNode):"contains"in n?n.contains(e):n.compareDocumentPosition?!!(n.compareDocumentPosition(e)&16):!1:!1}function aW(){for(var n=window,e=gA();e instanceof n.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)n=e.contentWindow;else break;e=gA(n.document)}return e}function UM(n){var e=n&&n.nodeName&&n.nodeName.toLowerCase();return e&&(e==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||e==="textarea"||n.contentEditable==="true")}function bQ(n){var e=aW(),t=n.focusedElem,r=n.selectionRange;if(e!==t&&t&&t.ownerDocument&&oW(t.ownerDocument.documentElement,t)){if(r!==null&&UM(t)){if(e=r.start,n=r.end,n===void 0&&(n=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(n,t.value.length);else if(n=(e=t.ownerDocument||document)&&e.defaultView||window,n.getSelection){n=n.getSelection();var i=t.textContent.length,o=Math.min(r.start,i);r=r.end===void 0?o:Math.min(r.end,i),!n.extend&&o>r&&(i=r,r=o,o=i),i=nz(t,o);var a=nz(t,r);i&&a&&(n.rangeCount!==1||n.anchorNode!==i.node||n.anchorOffset!==i.offset||n.focusNode!==a.node||n.focusOffset!==a.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),n.removeAllRanges(),o>r?(n.addRange(e),n.extend(a.node,a.offset)):(e.setEnd(a.node,a.offset),n.addRange(e)))}}for(e=[],n=t;n=n.parentNode;)n.nodeType===1&&e.push({element:n,left:n.scrollLeft,top:n.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,Ix=null,bR=null,zS=null,vR=!1;function rz(n,e,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;vR||Ix==null||Ix!==gA(r)||(r=Ix,"selectionStart"in r&&UM(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),zS&&pj(zS,r)||(zS=r,r=SA(bR,"onSelect"),0Ox||(n.current=CR[Ox],CR[Ox]=null,Ox--)}function yi(n,e){Ox++,CR[Ox]=n.current,n.current=e}var Ig={},ia=qg(Ig),tl=qg(!1),d0=Ig;function Qv(n,e){var t=n.type.contextTypes;if(!t)return Ig;var r=n.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in t)i[o]=e[o];return r&&(n=n.stateNode,n.__reactInternalMemoizedUnmaskedChildContext=e,n.__reactInternalMemoizedMaskedChildContext=i),i}function nl(n){return n=n.childContextTypes,n!=null}function kA(){_i(tl),_i(ia)}function cz(n,e,t){if(ia.current!==Ig)throw Error(ft(168));yi(ia,e),yi(tl,t)}function mW(n,e,t){var r=n.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var i in r)if(!(i in e))throw Error(ft(108,pY(n)||"Unknown",i));return ns({},t,r)}function _A(n){return n=(n=n.stateNode)&&n.__reactInternalMemoizedMergedChildContext||Ig,d0=ia.current,yi(ia,n),yi(tl,tl.current),!0}function uz(n,e,t){var r=n.stateNode;if(!r)throw Error(ft(169));t?(n=mW(n,e,d0),r.__reactInternalMemoizedMergedChildContext=n,_i(tl),_i(ia),yi(ia,n)):_i(tl),yi(tl,t)}var bh=null,lF=!1,YE=!1;function yW(n){bh===null?bh=[n]:bh.push(n)}function EQ(n){lF=!0,yW(n)}function Vg(){if(!YE&&bh!==null){YE=!0;var n=0,e=$r;try{var t=bh;for($r=1;n>=a,i-=a,cf=1<<32-Tc(e)+i|t<F?(A=T,T=null):A=T.sibling;var D=p(x,T,S[F],_);if(D===null){T===null&&(T=A);break}n&&T&&D.alternate===null&&e(x,T),w=o(D,w,F),C===null?b=D:C.sibling=D,C=D,T=A}if(F===S.length)return t(x,T),Ii&&im(x,F),b;if(T===null){for(;FF?(A=T,T=null):A=T.sibling;var P=p(x,T,D.value,_);if(P===null){T===null&&(T=A);break}n&&T&&P.alternate===null&&e(x,T),w=o(P,w,F),C===null?b=P:C.sibling=P,C=P,T=A}if(D.done)return t(x,T),Ii&&im(x,F),b;if(T===null){for(;!D.done;F++,D=S.next())D=f(x,D.value,_),D!==null&&(w=o(D,w,F),C===null?b=D:C.sibling=D,C=D);return Ii&&im(x,F),b}for(T=r(x,T);!D.done;F++,D=S.next())D=g(T,x,F,D.value,_),D!==null&&(n&&D.alternate!==null&&T.delete(D.key===null?F:D.key),w=o(D,w,F),C===null?b=D:C.sibling=D,C=D);return n&&T.forEach(function(L){return e(x,L)}),Ii&&im(x,F),b}function v(x,w,S,_){if(typeof S=="object"&&S!==null&&S.type===Rx&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case $C:e:{for(var b=S.key,C=w;C!==null;){if(C.key===b){if(b=S.type,b===Rx){if(C.tag===7){t(x,C.sibling),w=i(C,S.props.children),w.return=x,x=w;break e}}else if(C.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===ep&&pz(b)===C.type){t(x,C.sibling),w=i(C,S.props),w.ref=_w(x,C,S),w.return=x,x=w;break e}t(x,C);break}else e(x,C);C=C.sibling}S.type===Rx?(w=s0(S.props.children,x.mode,_,S.key),w.return=x,x=w):(_=u5(S.type,S.key,S.props,null,x.mode,_),_.ref=_w(x,w,S),_.return=x,x=_)}return a(x);case Px:e:{for(C=S.key;w!==null;){if(w.key===C)if(w.tag===4&&w.stateNode.containerInfo===S.containerInfo&&w.stateNode.implementation===S.implementation){t(x,w.sibling),w=i(w,S.children||[]),w.return=x,x=w;break e}else{t(x,w);break}else e(x,w);w=w.sibling}w=rP(S,x.mode,_),w.return=x,x=w}return a(x);case ep:return C=S._init,v(x,w,C(S._payload),_)}if(Yw(S))return m(x,w,S,_);if(vw(S))return y(x,w,S,_);l2(x,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,w!==null&&w.tag===6?(t(x,w.sibling),w=i(w,S),w.return=x,x=w):(t(x,w),w=nP(S,x.mode,_),w.return=x,x=w),a(x)):t(x,w)}return v}var Zv=wW(!0),SW=wW(!1),TA=qg(null),FA=null,Wx=null,GM=null;function KM(){GM=Wx=FA=null}function XM(n){var e=TA.current;_i(TA),n._currentValue=e}function FR(n,e,t){for(;n!==null;){var r=n.alternate;if((n.childLanes&e)!==e?(n.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),n===t)break;n=n.return}}function nb(n,e){FA=n,GM=Wx=null,n=n.dependencies,n!==null&&n.firstContext!==null&&(n.lanes&e&&(Ja=!0),n.firstContext=null)}function Od(n){var e=n._currentValue;if(GM!==n)if(n={context:n,memoizedValue:e,next:null},Wx===null){if(FA===null)throw Error(ft(308));Wx=n,FA.dependencies={lanes:0,firstContext:n}}else Wx=Wx.next=n;return e}var mm=null;function YM(n){mm===null?mm=[n]:mm.push(n)}function jW(n,e,t,r){var i=e.interleaved;return i===null?(t.next=t,YM(e)):(t.next=i.next,i.next=t),e.interleaved=t,kf(n,r)}function kf(n,e){n.lanes|=e;var t=n.alternate;for(t!==null&&(t.lanes|=e),t=n,n=n.return;n!==null;)n.childLanes|=e,t=n.alternate,t!==null&&(t.childLanes|=e),t=n,n=n.return;return t.tag===3?t.stateNode:null}var tp=!1;function QM(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function kW(n,e){n=n.updateQueue,e.updateQueue===n&&(e.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,effects:n.effects})}function ff(n,e){return{eventTime:n,lane:e,tag:0,payload:null,callback:null,next:null}}function Sg(n,e,t){var r=n.updateQueue;if(r===null)return null;if(r=r.shared,jr&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,kf(n,t)}return i=r.interleaved,i===null?(e.next=e,YM(r)):(e.next=i.next,i.next=e),r.interleaved=e,kf(n,t)}function s5(n,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var r=e.lanes;r&=n.pendingLanes,t|=r,e.lanes=t,IM(n,t)}}function gz(n,e){var t=n.updateQueue,r=n.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var i=null,o=null;if(t=t.firstBaseUpdate,t!==null){do{var a={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};o===null?i=o=a:o=o.next=a,t=t.next}while(t!==null);o===null?i=o=e:o=o.next=e}else i=o=e;t={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:r.shared,effects:r.effects},n.updateQueue=t;return}n=t.lastBaseUpdate,n===null?t.firstBaseUpdate=e:n.next=e,t.lastBaseUpdate=e}function DA(n,e,t,r){var i=n.updateQueue;tp=!1;var o=i.firstBaseUpdate,a=i.lastBaseUpdate,l=i.shared.pending;if(l!==null){i.shared.pending=null;var d=l,c=d.next;d.next=null,a===null?o=c:a.next=c,a=d;var u=n.alternate;u!==null&&(u=u.updateQueue,l=u.lastBaseUpdate,l!==a&&(l===null?u.firstBaseUpdate=c:l.next=c,u.lastBaseUpdate=d))}if(o!==null){var f=i.baseState;a=0,u=c=d=null,l=o;do{var p=l.lane,g=l.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:g,lane:0,tag:l.tag,payload:l.payload,callback:l.callback,next:null});e:{var m=n,y=l;switch(p=e,g=t,y.tag){case 1:if(m=y.payload,typeof m=="function"){f=m.call(g,f,p);break e}f=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=y.payload,p=typeof m=="function"?m.call(g,f,p):m,p==null)break e;f=ns({},f,p);break e;case 2:tp=!0}}l.callback!==null&&l.lane!==0&&(n.flags|=64,p=i.effects,p===null?i.effects=[l]:p.push(l))}else g={eventTime:g,lane:p,tag:l.tag,payload:l.payload,callback:l.callback,next:null},u===null?(c=u=g,d=f):u=u.next=g,a|=p;if(l=l.next,l===null){if(l=i.shared.pending,l===null)break;p=l,l=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(!0);if(u===null&&(d=f),i.baseState=d,i.firstBaseUpdate=c,i.lastBaseUpdate=u,e=i.shared.interleaved,e!==null){i=e;do a|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);h0|=a,n.lanes=a,n.memoizedState=f}}function mz(n,e,t){if(n=e.effects,e.effects=null,n!==null)for(e=0;et?t:4,n(!0);var r=$E.transition;$E.transition={};try{n(!1),e()}finally{$r=t,$E.transition=r}}function WW(){return Ld().memoizedState}function IQ(n,e,t){var r=kg(n);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},UW(n))HW(e,t);else if(t=jW(n,e,t,r),t!==null){var i=_a();Fc(t,n,r,i),qW(t,e,r)}}function MQ(n,e,t){var r=kg(n),i={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(UW(n))HW(e,i);else{var o=n.alternate;if(n.lanes===0&&(o===null||o.lanes===0)&&(o=e.lastRenderedReducer,o!==null))try{var a=e.lastRenderedState,l=o(a,t);if(i.hasEagerState=!0,i.eagerState=l,Ec(l,a)){var d=e.interleaved;d===null?(i.next=i,YM(e)):(i.next=d.next,d.next=i),e.interleaved=i;return}}catch{}finally{}t=jW(n,e,i,r),t!==null&&(i=_a(),Fc(t,n,r,i),qW(t,e,r))}}function UW(n){var e=n.alternate;return n===Ji||e!==null&&e===Ji}function HW(n,e){OS=PA=!0;var t=n.pending;t===null?e.next=e:(e.next=t.next,t.next=e),n.pending=e}function qW(n,e,t){if(t&4194240){var r=e.lanes;r&=n.pendingLanes,t|=r,e.lanes=t,IM(n,t)}}var RA={readContext:Od,useCallback:Vo,useContext:Vo,useEffect:Vo,useImperativeHandle:Vo,useInsertionEffect:Vo,useLayoutEffect:Vo,useMemo:Vo,useReducer:Vo,useRef:Vo,useState:Vo,useDebugValue:Vo,useDeferredValue:Vo,useTransition:Vo,useMutableSource:Vo,useSyncExternalStore:Vo,useId:Vo,unstable_isNewReconciler:!1},zQ={readContext:Od,useCallback:function(n,e){return Zc().memoizedState=[n,e===void 0?null:e],n},useContext:Od,useEffect:xz,useImperativeHandle:function(n,e,t){return t=t!=null?t.concat([n]):null,a5(4194308,4,MW.bind(null,e,n),t)},useLayoutEffect:function(n,e){return a5(4194308,4,n,e)},useInsertionEffect:function(n,e){return a5(4,2,n,e)},useMemo:function(n,e){var t=Zc();return e=e===void 0?null:e,n=n(),t.memoizedState=[n,e],n},useReducer:function(n,e,t){var r=Zc();return e=t!==void 0?t(e):e,r.memoizedState=r.baseState=e,n={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:e},r.queue=n,n=n.dispatch=IQ.bind(null,Ji,n),[r.memoizedState,n]},useRef:function(n){var e=Zc();return n={current:n},e.memoizedState=n},useState:yz,useDebugValue:i6,useDeferredValue:function(n){return Zc().memoizedState=n},useTransition:function(){var n=yz(!1),e=n[0];return n=BQ.bind(null,n[1]),Zc().memoizedState=n,[e,n]},useMutableSource:function(){},useSyncExternalStore:function(n,e,t){var r=Ji,i=Zc();if(Ii){if(t===void 0)throw Error(ft(407));t=t()}else{if(t=e(),po===null)throw Error(ft(349));u0&30||TW(r,e,t)}i.memoizedState=t;var o={value:t,getSnapshot:e};return i.queue=o,xz(DW.bind(null,r,o,n),[n]),r.flags|=2048,Sj(9,FW.bind(null,r,o,t,e),void 0,null),t},useId:function(){var n=Zc(),e=po.identifierPrefix;if(Ii){var t=uf,r=cf;t=(r&~(1<<32-Tc(r)-1)).toString(32)+t,e=":"+e+"R"+t,t=vj++,0<\/script>",n=n.removeChild(n.firstChild)):typeof r.is=="string"?n=a.createElement(t,{is:r.is}):(n=a.createElement(t),t==="select"&&(a=n,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):n=a.createElementNS(n,t),n[Du]=e,n[yj]=r,e9(n,e,!1,!1),e.stateNode=n;e:{switch(a=uR(t,r),t){case"dialog":vi("cancel",n),vi("close",n),i=r;break;case"iframe":case"object":case"embed":vi("load",n),i=r;break;case"video":case"audio":for(i=0;i<$w.length;i++)vi($w[i],n);i=r;break;case"source":vi("error",n),i=r;break;case"img":case"image":case"link":vi("error",n),vi("load",n),i=r;break;case"details":vi("toggle",n),i=r;break;case"input":z8(n,r),i=sR(n,r),vi("invalid",n);break;case"option":i=r;break;case"select":n._wrapperState={wasMultiple:!!r.multiple},i=ns({},r,{value:void 0}),vi("invalid",n);break;case"textarea":L8(n,r),i=lR(n,r),vi("invalid",n);break;default:i=r}cR(t,i),l=i;for(o in l)if(l.hasOwnProperty(o)){var d=l[o];o==="style"?R7(n,d):o==="dangerouslySetInnerHTML"?(d=d?d.__html:void 0,d!=null&&E7(n,d)):o==="children"?typeof d=="string"?(t!=="textarea"||d!=="")&&lj(n,d):typeof d=="number"&&lj(n,""+d):o!=="suppressContentEditableWarning"&&o!=="suppressHydrationWarning"&&o!=="autoFocus"&&(aj.hasOwnProperty(o)?d!=null&&o==="onScroll"&&vi("scroll",n):d!=null&&FM(n,o,d,a))}switch(t){case"input":ZC(n),O8(n,r,!1);break;case"textarea":ZC(n),N8(n);break;case"option":r.value!=null&&n.setAttribute("value",""+Bg(r.value));break;case"select":n.multiple=!!r.multiple,o=r.value,o!=null?Zx(n,!!r.multiple,o,!1):r.defaultValue!=null&&Zx(n,!!r.multiple,r.defaultValue,!0);break;default:typeof i.onClick=="function"&&(n.onclick=jA)}switch(t){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return Go(e),null;case 6:if(n&&e.stateNode!=null)n9(n,e,n.memoizedProps,r);else{if(typeof r!="string"&&e.stateNode===null)throw Error(ft(166));if(t=ym(bj.current),ym(Mu.current),a2(e)){if(r=e.stateNode,t=e.memoizedProps,r[Du]=e,(o=r.nodeValue!==t)&&(n=Vl,n!==null))switch(n.tag){case 3:o2(r.nodeValue,t,(n.mode&1)!==0);break;case 5:n.memoizedProps.suppressHydrationWarning!==!0&&o2(r.nodeValue,t,(n.mode&1)!==0)}o&&(e.flags|=4)}else r=(t.nodeType===9?t:t.ownerDocument).createTextNode(r),r[Du]=e,e.stateNode=r}return Go(e),null;case 13:if(_i(Qi),r=e.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(Ii&&Nl!==null&&e.mode&1&&!(e.flags&128))vW(),$v(),e.flags|=98560,o=!1;else if(o=a2(e),r!==null&&r.dehydrated!==null){if(n===null){if(!o)throw Error(ft(318));if(o=e.memoizedState,o=o!==null?o.dehydrated:null,!o)throw Error(ft(317));o[Du]=e}else $v(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Go(e),o=!1}else kc!==null&&(VR(kc),kc=null),o=!0;if(!o)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(r=r!==null,r!==(n!==null&&n.memoizedState!==null)&&r&&(e.child.flags|=8192,e.mode&1&&(n===null||Qi.current&1?Ws===0&&(Ws=3):u6())),e.updateQueue!==null&&(e.flags|=4),Go(e),null);case 4:return Jv(),zR(n,e),n===null&&gj(e.stateNode.containerInfo),Go(e),null;case 10:return XM(e.type._context),Go(e),null;case 17:return nl(e.type)&&kA(),Go(e),null;case 19:if(_i(Qi),o=e.memoizedState,o===null)return Go(e),null;if(r=(e.flags&128)!==0,a=o.rendering,a===null)if(r)Cw(o,!1);else{if(Ws!==0||n!==null&&n.flags&128)for(n=e.child;n!==null;){if(a=EA(n),a!==null){for(e.flags|=128,Cw(o,!1),r=a.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),e.subtreeFlags=0,r=t,t=e.child;t!==null;)o=t,n=r,o.flags&=14680066,a=o.alternate,a===null?(o.childLanes=0,o.lanes=n,o.child=null,o.subtreeFlags=0,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null,o.stateNode=null):(o.childLanes=a.childLanes,o.lanes=a.lanes,o.child=a.child,o.subtreeFlags=0,o.deletions=null,o.memoizedProps=a.memoizedProps,o.memoizedState=a.memoizedState,o.updateQueue=a.updateQueue,o.type=a.type,n=a.dependencies,o.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext}),t=t.sibling;return yi(Qi,Qi.current&1|2),e.child}n=n.sibling}o.tail!==null&&ws()>t1&&(e.flags|=128,r=!0,Cw(o,!1),e.lanes=4194304)}else{if(!r)if(n=EA(a),n!==null){if(e.flags|=128,r=!0,t=n.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),Cw(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Ii)return Go(e),null}else 2*ws()-o.renderingStartTime>t1&&t!==1073741824&&(e.flags|=128,r=!0,Cw(o,!1),e.lanes=4194304);o.isBackwards?(a.sibling=e.child,e.child=a):(t=o.last,t!==null?t.sibling=a:e.child=a,o.last=a)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=ws(),e.sibling=null,t=Qi.current,yi(Qi,r?t&1|2:t&1),e):(Go(e),null);case 22:case 23:return c6(),r=e.memoizedState!==null,n!==null&&n.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?Bl&1073741824&&(Go(e),e.subtreeFlags&6&&(e.flags|=8192)):Go(e),null;case 24:return null;case 25:return null}throw Error(ft(156,e.tag))}function VQ(n,e){switch(qM(e),e.tag){case 1:return nl(e.type)&&kA(),n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 3:return Jv(),_i(tl),_i(ia),JM(),n=e.flags,n&65536&&!(n&128)?(e.flags=n&-65537|128,e):null;case 5:return ZM(e),null;case 13:if(_i(Qi),n=e.memoizedState,n!==null&&n.dehydrated!==null){if(e.alternate===null)throw Error(ft(340));$v()}return n=e.flags,n&65536?(e.flags=n&-65537|128,e):null;case 19:return _i(Qi),null;case 4:return Jv(),null;case 10:return XM(e.type._context),null;case 22:case 23:return c6(),null;case 24:return null;default:return null}}var c2=!1,na=!1,GQ=typeof WeakSet=="function"?WeakSet:Set,Ut=null;function Ux(n,e){var t=n.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){us(n,e,r)}else t.current=null}function OR(n,e,t){try{t()}catch(r){us(n,e,r)}}var Fz=!1;function KQ(n,e){if(wR=vA,n=aW(),UM(n)){if("selectionStart"in n)var t={start:n.selectionStart,end:n.selectionEnd};else e:{t=(t=n.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{t.nodeType,o.nodeType}catch{t=null;break e}var a=0,l=-1,d=-1,c=0,u=0,f=n,p=null;t:for(;;){for(var g;f!==t||i!==0&&f.nodeType!==3||(l=a+i),f!==o||r!==0&&f.nodeType!==3||(d=a+r),f.nodeType===3&&(a+=f.nodeValue.length),(g=f.firstChild)!==null;)p=f,f=g;for(;;){if(f===n)break t;if(p===t&&++c===i&&(l=a),p===o&&++u===r&&(d=a),(g=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=g}t=l===-1||d===-1?null:{start:l,end:d}}else t=null}t=t||{start:0,end:0}}else t=null;for(SR={focusedElem:n,selectionRange:t},vA=!1,Ut=e;Ut!==null;)if(e=Ut,n=e.child,(e.subtreeFlags&1028)!==0&&n!==null)n.return=e,Ut=n;else for(;Ut!==null;){e=Ut;try{var m=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var y=m.memoizedProps,v=m.memoizedState,x=e.stateNode,w=x.getSnapshotBeforeUpdate(e.elementType===e.type?y:ac(e.type,y),v);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var S=e.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ft(163))}}catch(_){us(e,e.return,_)}if(n=e.sibling,n!==null){n.return=e.return,Ut=n;break}Ut=e.return}return m=Fz,Fz=!1,m}function LS(n,e,t){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&n)===n){var o=i.destroy;i.destroy=void 0,o!==void 0&&OR(e,t,o)}i=i.next}while(i!==r)}}function uF(n,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&n)===n){var r=t.create;t.destroy=r()}t=t.next}while(t!==e)}}function LR(n){var e=n.ref;if(e!==null){var t=n.stateNode;switch(n.tag){case 5:n=t;break;default:n=t}typeof e=="function"?e(n):e.current=n}}function r9(n){var e=n.alternate;e!==null&&(n.alternate=null,r9(e)),n.child=null,n.deletions=null,n.sibling=null,n.tag===5&&(e=n.stateNode,e!==null&&(delete e[Du],delete e[yj],delete e[_R],delete e[FQ],delete e[DQ])),n.stateNode=null,n.return=null,n.dependencies=null,n.memoizedProps=null,n.memoizedState=null,n.pendingProps=null,n.stateNode=null,n.updateQueue=null}function i9(n){return n.tag===5||n.tag===3||n.tag===4}function Dz(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||i9(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function NR(n,e,t){var r=n.tag;if(r===5||r===6)n=n.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(n,e):t.insertBefore(n,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(n,t)):(e=t,e.appendChild(n)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=jA));else if(r!==4&&(n=n.child,n!==null))for(NR(n,e,t),n=n.sibling;n!==null;)NR(n,e,t),n=n.sibling}function WR(n,e,t){var r=n.tag;if(r===5||r===6)n=n.stateNode,e?t.insertBefore(n,e):t.appendChild(n);else if(r!==4&&(n=n.child,n!==null))for(WR(n,e,t),n=n.sibling;n!==null;)WR(n,e,t),n=n.sibling}var Ao=null,jc=!1;function Hf(n,e,t){for(t=t.child;t!==null;)s9(n,e,t),t=t.sibling}function s9(n,e,t){if(Iu&&typeof Iu.onCommitFiberUnmount=="function")try{Iu.onCommitFiberUnmount(rF,t)}catch{}switch(t.tag){case 5:na||Ux(t,e);case 6:var r=Ao,i=jc;Ao=null,Hf(n,e,t),Ao=r,jc=i,Ao!==null&&(jc?(n=Ao,t=t.stateNode,n.nodeType===8?n.parentNode.removeChild(t):n.removeChild(t)):Ao.removeChild(t.stateNode));break;case 18:Ao!==null&&(jc?(n=Ao,t=t.stateNode,n.nodeType===8?XE(n.parentNode,t):n.nodeType===1&&XE(n,t),hj(n)):XE(Ao,t.stateNode));break;case 4:r=Ao,i=jc,Ao=t.stateNode.containerInfo,jc=!0,Hf(n,e,t),Ao=r,jc=i;break;case 0:case 11:case 14:case 15:if(!na&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var o=i,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&OR(t,e,a),i=i.next}while(i!==r)}Hf(n,e,t);break;case 1:if(!na&&(Ux(t,e),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(l){us(t,e,l)}Hf(n,e,t);break;case 21:Hf(n,e,t);break;case 22:t.mode&1?(na=(r=na)||t.memoizedState!==null,Hf(n,e,t),na=r):Hf(n,e,t);break;default:Hf(n,e,t)}}function Ez(n){var e=n.updateQueue;if(e!==null){n.updateQueue=null;var t=n.stateNode;t===null&&(t=n.stateNode=new GQ),e.forEach(function(r){var i=n$.bind(null,n,r);t.has(r)||(t.add(r),r.then(i,i))})}}function tc(n,e){var t=e.deletions;if(t!==null)for(var r=0;ri&&(i=a),r&=~o}if(r=i,r=ws()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*YQ(r/1960))-r,10n?16:n,cg===null)var r=!1;else{if(n=cg,cg=null,MA=0,jr&6)throw Error(ft(331));var i=jr;for(jr|=4,Ut=n.current;Ut!==null;){var o=Ut,a=o.child;if(Ut.flags&16){var l=o.deletions;if(l!==null){for(var d=0;dws()-l6?i0(n,0):a6|=t),rl(n,e)}function f9(n,e){e===0&&(n.mode&1?(e=t2,t2<<=1,!(t2&130023424)&&(t2=4194304)):e=1);var t=_a();n=kf(n,e),n!==null&&(U_(n,e,t),rl(n,t))}function t$(n){var e=n.memoizedState,t=0;e!==null&&(t=e.retryLane),f9(n,t)}function n$(n,e){var t=0;switch(n.tag){case 13:var r=n.stateNode,i=n.memoizedState;i!==null&&(t=i.retryLane);break;case 19:r=n.stateNode;break;default:throw Error(ft(314))}r!==null&&r.delete(e),f9(n,t)}var p9;p9=function(n,e,t){if(n!==null)if(n.memoizedProps!==e.pendingProps||tl.current)Ja=!0;else{if(!(n.lanes&t)&&!(e.flags&128))return Ja=!1,HQ(n,e,t);Ja=!!(n.flags&131072)}else Ja=!1,Ii&&e.flags&1048576&&xW(e,AA,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;l5(n,e),n=e.pendingProps;var i=Qv(e,ia.current);nb(e,t),i=t6(null,e,r,n,i,t);var o=n6();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,nl(r)?(o=!0,_A(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,QM(e),i.updater=cF,e.stateNode=i,i._reactInternals=e,ER(e,r,n,t),e=BR(null,e,r,!0,o,t)):(e.tag=0,Ii&&o&&HM(e),va(null,e,i,t),e=e.child),e;case 16:r=e.elementType;e:{switch(l5(n,e),n=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=i$(r),n=ac(r,n),i){case 0:e=RR(null,e,r,n,t);break e;case 1:e=Cz(null,e,r,n,t);break e;case 11:e=kz(null,e,r,n,t);break e;case 14:e=_z(null,e,r,ac(r.type,n),t);break e}throw Error(ft(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),RR(n,e,r,i,t);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),Cz(n,e,r,i,t);case 3:e:{if($W(e),n===null)throw Error(ft(387));r=e.pendingProps,o=e.memoizedState,i=o.element,kW(n,e),DA(e,r,null,t);var a=e.memoizedState;if(r=a.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},e.updateQueue.baseState=o,e.memoizedState=o,e.flags&256){i=e1(Error(ft(423)),e),e=Az(n,e,r,t,i);break e}else if(r!==i){i=e1(Error(ft(424)),e),e=Az(n,e,r,t,i);break e}else for(Nl=wg(e.stateNode.containerInfo.firstChild),Vl=e,Ii=!0,kc=null,t=SW(e,null,r,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if($v(),r===i){e=_f(n,e,t);break e}va(n,e,r,t)}e=e.child}return e;case 5:return _W(e),n===null&&TR(e),r=e.type,i=e.pendingProps,o=n!==null?n.memoizedProps:null,a=i.children,jR(r,i)?a=null:o!==null&&jR(r,o)&&(e.flags|=32),QW(n,e),va(n,e,a,t),e.child;case 6:return n===null&&TR(e),null;case 13:return ZW(n,e,t);case 4:return $M(e,e.stateNode.containerInfo),r=e.pendingProps,n===null?e.child=Zv(e,null,r,t):va(n,e,r,t),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),kz(n,e,r,i,t);case 7:return va(n,e,e.pendingProps,t),e.child;case 8:return va(n,e,e.pendingProps.children,t),e.child;case 12:return va(n,e,e.pendingProps.children,t),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,o=e.memoizedProps,a=i.value,yi(TA,r._currentValue),r._currentValue=a,o!==null)if(Ec(o.value,a)){if(o.children===i.children&&!tl.current){e=_f(n,e,t);break e}}else for(o=e.child,o!==null&&(o.return=e);o!==null;){var l=o.dependencies;if(l!==null){a=o.child;for(var d=l.firstContext;d!==null;){if(d.context===r){if(o.tag===1){d=ff(-1,t&-t),d.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?d.next=d:(d.next=u.next,u.next=d),c.pending=d}}o.lanes|=t,d=o.alternate,d!==null&&(d.lanes|=t),FR(o.return,t,e),l.lanes|=t;break}d=d.next}}else if(o.tag===10)a=o.type===e.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(ft(341));a.lanes|=t,l=a.alternate,l!==null&&(l.lanes|=t),FR(a,t,e),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===e){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}va(n,e,i.children,t),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,nb(e,t),i=Od(i),r=r(i),e.flags|=1,va(n,e,r,t),e.child;case 14:return r=e.type,i=ac(r,e.pendingProps),i=ac(r.type,i),_z(n,e,r,i,t);case 15:return XW(n,e,e.type,e.pendingProps,t);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:ac(r,i),l5(n,e),e.tag=1,nl(r)?(n=!0,_A(e)):n=!1,nb(e,t),VW(e,r,i),ER(e,r,i,t),BR(null,e,r,!0,n,t);case 19:return JW(n,e,t);case 22:return YW(n,e,t)}throw Error(ft(156,e.tag))};function g9(n,e){return U7(n,e)}function r$(n,e,t,r){this.tag=n,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dd(n,e,t,r){return new r$(n,e,t,r)}function h6(n){return n=n.prototype,!(!n||!n.isReactComponent)}function i$(n){if(typeof n=="function")return h6(n)?1:0;if(n!=null){if(n=n.$$typeof,n===EM)return 11;if(n===PM)return 14}return 2}function _g(n,e){var t=n.alternate;return t===null?(t=Dd(n.tag,e,n.key,n.mode),t.elementType=n.elementType,t.type=n.type,t.stateNode=n.stateNode,t.alternate=n,n.alternate=t):(t.pendingProps=e,t.type=n.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=n.flags&14680064,t.childLanes=n.childLanes,t.lanes=n.lanes,t.child=n.child,t.memoizedProps=n.memoizedProps,t.memoizedState=n.memoizedState,t.updateQueue=n.updateQueue,e=n.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=n.sibling,t.index=n.index,t.ref=n.ref,t}function u5(n,e,t,r,i,o){var a=2;if(r=n,typeof n=="function")h6(n)&&(a=1);else if(typeof n=="string")a=5;else e:switch(n){case Rx:return s0(t.children,i,o,e);case DM:a=8,i|=8;break;case tR:return n=Dd(12,t,e,i|2),n.elementType=tR,n.lanes=o,n;case nR:return n=Dd(13,t,e,i),n.elementType=nR,n.lanes=o,n;case rR:return n=Dd(19,t,e,i),n.elementType=rR,n.lanes=o,n;case _7:return fF(t,i,o,e);default:if(typeof n=="object"&&n!==null)switch(n.$$typeof){case j7:a=10;break e;case k7:a=9;break e;case EM:a=11;break e;case PM:a=14;break e;case ep:a=16,r=null;break e}throw Error(ft(130,n==null?n:typeof n,""))}return e=Dd(a,t,e,i),e.elementType=n,e.type=r,e.lanes=o,e}function s0(n,e,t,r){return n=Dd(7,n,r,e),n.lanes=t,n}function fF(n,e,t,r){return n=Dd(22,n,r,e),n.elementType=_7,n.lanes=t,n.stateNode={isHidden:!1},n}function nP(n,e,t){return n=Dd(6,n,null,e),n.lanes=t,n}function rP(n,e,t){return e=Dd(4,n.children!==null?n.children:[],n.key,e),e.lanes=t,e.stateNode={containerInfo:n.containerInfo,pendingChildren:null,implementation:n.implementation},e}function s$(n,e,t,r,i){this.tag=e,this.containerInfo=n,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zE(0),this.expirationTimes=zE(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zE(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function f6(n,e,t,r,i,o,a,l,d){return n=new s$(n,e,t,l,d),e===1?(e=1,o===!0&&(e|=8)):e=0,o=Dd(3,null,null,e),n.current=o,o.stateNode=n,o.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},QM(o),n}function o$(n,e,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(b9)}catch(n){console.error(n)}}b9(),b7.exports=Ql;var u$=b7.exports,Lz=u$;JP.createRoot=Lz.createRoot,JP.hydrateRoot=Lz.hydrateRoot;/** - * @remix-run/router v1.23.3 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function kj(){return kj=Object.assign?Object.assign.bind():function(n){for(var e=1;e"u")throw new Error(e)}function y6(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function f$(){return Math.random().toString(36).substr(2,8)}function Wz(n,e){return{usr:n.state,key:n.key,idx:e}}function GR(n,e,t,r){return t===void 0&&(t=null),kj({pathname:typeof n=="string"?n:n.pathname,search:"",hash:""},typeof e=="string"?f1(e):e,{state:t,key:e&&e.key||r||f$()})}function LA(n){let{pathname:e="/",search:t="",hash:r=""}=n;return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),r&&r!=="#"&&(e+=r.charAt(0)==="#"?r:"#"+r),e}function f1(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substr(t),n=n.substr(0,t));let r=n.indexOf("?");r>=0&&(e.search=n.substr(r),n=n.substr(0,r)),n&&(e.pathname=n)}return e}function p$(n,e,t,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:o=!1}=r,a=i.history,l=ug.Pop,d=null,c=u();c==null&&(c=0,a.replaceState(kj({},a.state,{idx:c}),""));function u(){return(a.state||{idx:null}).idx}function f(){l=ug.Pop;let v=u(),x=v==null?null:v-c;c=v,d&&d({action:l,location:y.location,delta:x})}function p(v,x){l=ug.Push;let w=GR(y.location,v,x);c=u()+1;let S=Wz(w,c),_=y.createHref(w);try{a.pushState(S,"",_)}catch(b){if(b instanceof DOMException&&b.name==="DataCloneError")throw b;i.location.assign(_)}o&&d&&d({action:l,location:y.location,delta:1})}function g(v,x){l=ug.Replace;let w=GR(y.location,v,x);c=u();let S=Wz(w,c),_=y.createHref(w);a.replaceState(S,"",_),o&&d&&d({action:l,location:y.location,delta:0})}function m(v){let x=i.location.origin!=="null"?i.location.origin:i.location.href,w=typeof v=="string"?v:LA(v);return w=w.replace(/ $/,"%20"),es(x,"No window.location.(origin|href) available to create URL for href: "+w),new URL(w,x)}let y={get action(){return l},get location(){return n(i,a)},listen(v){if(d)throw new Error("A history only accepts one active listener");return i.addEventListener(Nz,f),d=v,()=>{i.removeEventListener(Nz,f),d=null}},createHref(v){return e(i,v)},createURL:m,encodeLocation(v){let x=m(v);return{pathname:x.pathname,search:x.search,hash:x.hash}},push:p,replace:g,go(v){return a.go(v)}};return y}var Uz;(function(n){n.data="data",n.deferred="deferred",n.redirect="redirect",n.error="error"})(Uz||(Uz={}));function g$(n,e,t){return t===void 0&&(t="/"),m$(n,e,t)}function m$(n,e,t,r){let i=typeof e=="string"?f1(e):e,o=n1(i.pathname||"/",t);if(o==null)return null;let a=v9(n);y$(a);let l=null,d=T$(o);for(let c=0;l==null&&c{let d={relativePath:l===void 0?o.path||"":l,caseSensitive:o.caseSensitive===!0,childrenIndex:a,route:o};d.relativePath.startsWith("/")&&(es(d.relativePath.startsWith(r),'Absolute route path "'+d.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),d.relativePath=d.relativePath.slice(r.length));let c=Cg([r,d.relativePath]),u=t.concat(d);o.children&&o.children.length>0&&(es(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),v9(o.children,e,u,c)),!(o.path==null&&!o.index)&&e.push({path:c,score:k$(c,o.index),routesMeta:u})};return n.forEach((o,a)=>{var l;if(o.path===""||!((l=o.path)!=null&&l.includes("?")))i(o,a);else for(let d of w9(o.path))i(o,a,d)}),e}function w9(n){let e=n.split("/");if(e.length===0)return[];let[t,...r]=e,i=t.endsWith("?"),o=t.replace(/\?$/,"");if(r.length===0)return i?[o,""]:[o];let a=w9(r.join("/")),l=[];return l.push(...a.map(d=>d===""?o:[o,d].join("/"))),i&&l.push(...a),l.map(d=>n.startsWith("/")&&d===""?"/":d)}function y$(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:_$(e.routesMeta.map(r=>r.childrenIndex),t.routesMeta.map(r=>r.childrenIndex)))}const x$=/^:[\w-]+$/,b$=3,v$=2,w$=1,S$=10,j$=-2,Hz=n=>n==="*";function k$(n,e){let t=n.split("/"),r=t.length;return t.some(Hz)&&(r+=j$),e&&(r+=v$),t.filter(i=>!Hz(i)).reduce((i,o)=>i+(x$.test(o)?b$:o===""?w$:S$),r)}function _$(n,e){return n.length===e.length&&n.slice(0,-1).every((r,i)=>r===e[i])?n[n.length-1]-e[e.length-1]:0}function C$(n,e,t){let{routesMeta:r}=n,i={},o="/",a=[];for(let l=0;l{let{paramName:p,isOptional:g}=u;if(p==="*"){let y=l[f]||"";a=o.slice(0,o.length-y.length).replace(/(.)\/+$/,"$1")}const m=l[f];return g&&!m?c[p]=void 0:c[p]=(m||"").replace(/%2F/g,"/"),c},{}),pathname:o,pathnameBase:a,pattern:n}}function A$(n,e,t){e===void 0&&(e=!1),t===void 0&&(t=!0),y6(n==="*"||!n.endsWith("*")||n.endsWith("/*"),'Route path "'+n+'" will be treated as if it were '+('"'+n.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+n.replace(/\*$/,"/*")+'".'));let r=[],i="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,l,d)=>(r.push({paramName:l,isOptional:d!=null}),d?"/?([^\\/]+)?":"/([^\\/]+)"));return n.endsWith("*")?(r.push({paramName:"*"}),i+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?i+="\\/*$":n!==""&&n!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function T$(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return y6(!1,'The URL path "'+n+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),n}}function n1(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,r=n.charAt(t);return r&&r!=="/"?null:n.slice(t)||"/"}const F$=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,D$=n=>F$.test(n);function E$(n,e){e===void 0&&(e="/");let{pathname:t,search:r="",hash:i=""}=typeof n=="string"?f1(n):n,o;if(t)if(D$(t))o=t;else{if(t.includes("//")){let a=t;t=S9(t),y6(!1,"Pathnames cannot have embedded double slashes - normalizing "+(a+" -> "+t))}t.startsWith("/")?o=qz(t.substring(1),"/"):o=qz(t,e)}else o=e;return{pathname:o,search:B$(r),hash:I$(i)}}function qz(n,e){let t=e.replace(/\/+$/,"").split("/");return n.split("/").forEach(i=>{i===".."?t.length>1&&t.pop():i!=="."&&t.push(i)}),t.length>1?t.join("/"):"/"}function iP(n,e,t,r){return"Cannot include a '"+n+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+t+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function P$(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function x6(n,e){let t=P$(n);return e?t.map((r,i)=>i===t.length-1?r.pathname:r.pathnameBase):t.map(r=>r.pathnameBase)}function b6(n,e,t,r){r===void 0&&(r=!1);let i;typeof n=="string"?i=f1(n):(i=kj({},n),es(!i.pathname||!i.pathname.includes("?"),iP("?","pathname","search",i)),es(!i.pathname||!i.pathname.includes("#"),iP("#","pathname","hash",i)),es(!i.search||!i.search.includes("#"),iP("#","search","hash",i)));let o=n===""||i.pathname==="",a=o?"/":i.pathname,l;if(a==null)l=t;else{let f=e.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;i.pathname=p.join("/")}l=f>=0?e[f]:"/"}let d=E$(i,l),c=a&&a!=="/"&&a.endsWith("/"),u=(o||a===".")&&t.endsWith("/");return!d.pathname.endsWith("/")&&(c||u)&&(d.pathname+="/"),d}const S9=n=>n.replace(/\/\/+/g,"/"),Cg=n=>S9(n.join("/")),R$=n=>n.replace(/\/+$/,"").replace(/^\/*/,"/"),B$=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,I$=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n;function M$(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}const j9=["post","put","patch","delete"];new Set(j9);const z$=["get",...j9];new Set(z$);/** - * React Router v6.30.4 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function _j(){return _j=Object.assign?Object.assign.bind():function(n){for(var e=1;e{l.current=!0}),k.useCallback(function(c,u){if(u===void 0&&(u={}),!l.current)return;if(typeof c=="number"){r.go(c);return}let f=b6(c,JSON.parse(a),o,u.relative==="path");n==null&&e!=="/"&&(f.pathname=f.pathname==="/"?e:Cg([e,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[e,r,a,o,n])}const N$=k.createContext(null);function W$(n){let e=k.useContext(Uu).outlet;return e&&k.createElement(N$.Provider,{value:n},e)}function G_(){let{matches:n}=k.useContext(Uu),e=n[n.length-1];return e?e.params:{}}function vF(n,e){let{relative:t}=e===void 0?{}:e,{future:r}=k.useContext(Pf),{matches:i}=k.useContext(Uu),{pathname:o}=E0(),a=JSON.stringify(x6(i,r.v7_relativeSplatPath));return k.useMemo(()=>b6(n,JSON.parse(a),o,t==="path"),[n,a,o,t])}function U$(n,e){return H$(n,e)}function H$(n,e,t,r){p1()||es(!1);let{navigator:i}=k.useContext(Pf),{matches:o}=k.useContext(Uu),a=o[o.length-1],l=a?a.params:{};a&&a.pathname;let d=a?a.pathnameBase:"/";a&&a.route;let c=E0(),u;if(e){var f;let v=typeof e=="string"?f1(e):e;d==="/"||(f=v.pathname)!=null&&f.startsWith(d)||es(!1),u=v}else u=c;let p=u.pathname||"/",g=p;if(d!=="/"){let v=d.replace(/^\//,"").split("/");g="/"+p.replace(/^\//,"").split("/").slice(v.length).join("/")}let m=g$(n,{pathname:g}),y=X$(m&&m.map(v=>Object.assign({},v,{params:Object.assign({},l,v.params),pathname:Cg([d,i.encodeLocation?i.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?d:Cg([d,i.encodeLocation?i.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),o,t,r);return e&&y?k.createElement(bF.Provider,{value:{location:_j({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:ug.Pop}},y):y}function q$(){let n=Z$(),e=M$(n)?n.status+" "+n.statusText:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},e),t?k.createElement("pre",{style:i},t):null,null)}const V$=k.createElement(q$,null);class G$ extends k.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){console.error("React Router caught the following error during render",e,t)}render(){return this.state.error!==void 0?k.createElement(Uu.Provider,{value:this.props.routeContext},k.createElement(_9.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function K$(n){let{routeContext:e,match:t,children:r}=n,i=k.useContext(xF);return i&&i.static&&i.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=t.route.id),k.createElement(Uu.Provider,{value:e},r)}function X$(n,e,t,r){var i;if(e===void 0&&(e=[]),t===void 0&&(t=null),r===void 0&&(r=null),n==null){var o;if(!t)return null;if(t.errors)n=t.matches;else if((o=r)!=null&&o.v7_partialHydration&&e.length===0&&!t.initialized&&t.matches.length>0)n=t.matches;else return null}let a=n,l=(i=t)==null?void 0:i.errors;if(l!=null){let u=a.findIndex(f=>f.route.id&&(l==null?void 0:l[f.route.id])!==void 0);u>=0||es(!1),a=a.slice(0,Math.min(a.length,u+1))}let d=!1,c=-1;if(t&&r&&r.v7_partialHydration)for(let u=0;u=0?a=a.slice(0,c+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let g,m=!1,y=null,v=null;t&&(g=l&&f.route.id?l[f.route.id]:void 0,y=f.route.errorElement||V$,d&&(c<0&&p===0?(eZ("route-fallback"),m=!0,v=null):c===p&&(m=!0,v=f.route.hydrateFallbackElement||null)));let x=e.concat(a.slice(0,p+1)),w=()=>{let S;return g?S=y:m?S=v:f.route.Component?S=k.createElement(f.route.Component,null):f.route.element?S=f.route.element:S=u,k.createElement(K$,{match:f,routeContext:{outlet:u,matches:x,isDataRoute:t!=null},children:S})};return t&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?k.createElement(G$,{location:t.location,revalidation:t.revalidation,component:y,error:g,children:w(),routeContext:{outlet:null,matches:x,isDataRoute:!0}}):w()},null)}var A9=function(n){return n.UseBlocker="useBlocker",n.UseRevalidator="useRevalidator",n.UseNavigateStable="useNavigate",n}(A9||{}),T9=function(n){return n.UseBlocker="useBlocker",n.UseLoaderData="useLoaderData",n.UseActionData="useActionData",n.UseRouteError="useRouteError",n.UseNavigation="useNavigation",n.UseRouteLoaderData="useRouteLoaderData",n.UseMatches="useMatches",n.UseRevalidator="useRevalidator",n.UseNavigateStable="useNavigate",n.UseRouteId="useRouteId",n}(T9||{});function Y$(n){let e=k.useContext(xF);return e||es(!1),e}function Q$(n){let e=k.useContext(k9);return e||es(!1),e}function $$(n){let e=k.useContext(Uu);return e||es(!1),e}function F9(n){let e=$$(),t=e.matches[e.matches.length-1];return t.route.id||es(!1),t.route.id}function Z$(){var n;let e=k.useContext(_9),t=Q$(),r=F9();return e!==void 0?e:(n=t.errors)==null?void 0:n[r]}function J$(){let{router:n}=Y$(A9.UseNavigateStable),e=F9(T9.UseNavigateStable),t=k.useRef(!1);return C9(()=>{t.current=!0}),k.useCallback(function(i,o){o===void 0&&(o={}),t.current&&(typeof i=="number"?n.navigate(i):n.navigate(i,_j({fromRouteId:e},o)))},[n,e])}const Vz={};function eZ(n,e,t){Vz[n]||(Vz[n]=!0)}function tZ(n,e){n==null||n.v7_startTransition,n==null||n.v7_relativeSplatPath}function Gz(n){let{to:e,replace:t,state:r,relative:i}=n;p1()||es(!1);let{future:o,static:a}=k.useContext(Pf),{matches:l}=k.useContext(Uu),{pathname:d}=E0(),c=go(),u=b6(e,x6(l,o.v7_relativeSplatPath),d,i==="path"),f=JSON.stringify(u);return k.useEffect(()=>c(JSON.parse(f),{replace:t,state:r,relative:i}),[c,f,i,t,r]),null}function nZ(n){return W$(n.context)}function Zn(n){es(!1)}function rZ(n){let{basename:e="/",children:t=null,location:r,navigationType:i=ug.Pop,navigator:o,static:a=!1,future:l}=n;p1()&&es(!1);let d=e.replace(/^\/*/,"/"),c=k.useMemo(()=>({basename:d,navigator:o,static:a,future:_j({v7_relativeSplatPath:!1},l)}),[d,l,o,a]);typeof r=="string"&&(r=f1(r));let{pathname:u="/",search:f="",hash:p="",state:g=null,key:m="default"}=r,y=k.useMemo(()=>{let v=n1(u,d);return v==null?null:{location:{pathname:v,search:f,hash:p,state:g,key:m},navigationType:i}},[d,u,f,p,g,m,i]);return y==null?null:k.createElement(Pf.Provider,{value:c},k.createElement(bF.Provider,{children:t,value:y}))}function iZ(n){let{children:e,location:t}=n;return U$(XR(e),t)}new Promise(()=>{});function XR(n,e){e===void 0&&(e=[]);let t=[];return k.Children.forEach(n,(r,i)=>{if(!k.isValidElement(r))return;let o=[...e,i];if(r.type===k.Fragment){t.push.apply(t,XR(r.props.children,o));return}r.type!==Zn&&es(!1),!r.props.index||!r.props.children||es(!1);let a={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=XR(r.props.children,o)),t.push(a)}),t}/** - * React Router DOM v6.30.4 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function NA(){return NA=Object.assign?Object.assign.bind():function(n){for(var e=1;e{let r=n[t];return e.concat(Array.isArray(r)?r.map(i=>[t,i]):[[t,r]])},[]))}function aZ(n,e){let t=YR(n);return e&&e.forEach((r,i)=>{t.has(i)||e.getAll(i).forEach(o=>{t.append(i,o)})}),t}const lZ=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],dZ=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],cZ="6";try{window.__reactRouterVersion=cZ}catch{}const uZ=k.createContext({isTransitioning:!1}),hZ="startTransition",Kz=eY[hZ];function fZ(n){let{basename:e,children:t,future:r,window:i}=n,o=k.useRef();o.current==null&&(o.current=h$({window:i,v5Compat:!0}));let a=o.current,[l,d]=k.useState({action:a.action,location:a.location}),{v7_startTransition:c}=r||{},u=k.useCallback(f=>{c&&Kz?Kz(()=>d(f)):d(f)},[d,c]);return k.useLayoutEffect(()=>a.listen(u),[a,u]),k.useEffect(()=>tZ(r),[r]),k.createElement(rZ,{basename:e,children:t,location:l.location,navigationType:l.action,navigator:a,future:r})}const pZ=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",gZ=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,mZ=k.forwardRef(function(e,t){let{onClick:r,relative:i,reloadDocument:o,replace:a,state:l,target:d,to:c,preventScrollReset:u,viewTransition:f}=e,p=D9(e,lZ),{basename:g}=k.useContext(Pf),m,y=!1;if(typeof c=="string"&&gZ.test(c)&&(m=c,pZ))try{let S=new URL(window.location.href),_=c.startsWith("//")?new URL(S.protocol+c):new URL(c),b=n1(_.pathname,g);_.origin===S.origin&&b!=null?c=b+_.search+_.hash:y=!0}catch{}let v=O$(c,{relative:i}),x=xZ(c,{replace:a,state:l,target:d,preventScrollReset:u,relative:i,viewTransition:f});function w(S){r&&r(S),S.defaultPrevented||x(S)}return k.createElement("a",NA({},p,{href:m||v,onClick:y||o?r:w,ref:t,target:d}))}),wx=k.forwardRef(function(e,t){let{"aria-current":r="page",caseSensitive:i=!1,className:o="",end:a=!1,style:l,to:d,viewTransition:c,children:u}=e,f=D9(e,dZ),p=vF(d,{relative:f.relative}),g=E0(),m=k.useContext(k9),{navigator:y,basename:v}=k.useContext(Pf),x=m!=null&&bZ(p)&&c===!0,w=y.encodeLocation?y.encodeLocation(p).pathname:p.pathname,S=g.pathname,_=m&&m.navigation&&m.navigation.location?m.navigation.location.pathname:null;i||(S=S.toLowerCase(),_=_?_.toLowerCase():null,w=w.toLowerCase()),_&&v&&(_=n1(_,v)||_);const b=w!=="/"&&w.endsWith("/")?w.length-1:w.length;let C=S===w||!a&&S.startsWith(w)&&S.charAt(b)==="/",T=_!=null&&(_===w||!a&&_.startsWith(w)&&_.charAt(w.length)==="/"),F={isActive:C,isPending:T,isTransitioning:x},A=C?r:void 0,D;typeof o=="function"?D=o(F):D=[o,C?"active":null,T?"pending":null,x?"transitioning":null].filter(Boolean).join(" ");let P=typeof l=="function"?l(F):l;return k.createElement(mZ,NA({},f,{"aria-current":A,className:D,ref:t,style:P,to:d,viewTransition:c}),typeof u=="function"?u(F):u)});var QR;(function(n){n.UseScrollRestoration="useScrollRestoration",n.UseSubmit="useSubmit",n.UseSubmitFetcher="useSubmitFetcher",n.UseFetcher="useFetcher",n.useViewTransitionState="useViewTransitionState"})(QR||(QR={}));var Xz;(function(n){n.UseFetcher="useFetcher",n.UseFetchers="useFetchers",n.UseScrollRestoration="useScrollRestoration"})(Xz||(Xz={}));function yZ(n){let e=k.useContext(xF);return e||es(!1),e}function xZ(n,e){let{target:t,replace:r,state:i,preventScrollReset:o,relative:a,viewTransition:l}=e===void 0?{}:e,d=go(),c=E0(),u=vF(n,{relative:a});return k.useCallback(f=>{if(oZ(f,t)){f.preventDefault();let p=r!==void 0?r:LA(c)===LA(u);d(n,{replace:p,state:i,preventScrollReset:o,relative:a,viewTransition:l})}},[c,d,u,r,i,t,n,o,a,l])}function K_(n){let e=k.useRef(YR(n)),t=k.useRef(!1),r=E0(),i=k.useMemo(()=>aZ(r.search,t.current?null:e.current),[r.search]),o=go(),a=k.useCallback((l,d)=>{const c=YR(typeof l=="function"?l(i):l);t.current=!0,o("?"+c,d)},[o,i]);return[i,a]}function bZ(n,e){e===void 0&&(e={});let t=k.useContext(uZ);t==null&&es(!1);let{basename:r}=yZ(QR.useViewTransitionState),i=vF(n,{relative:e.relative});if(!t.isTransitioning)return!1;let o=n1(t.currentLocation.pathname,r)||t.currentLocation.pathname,a=n1(t.nextLocation.pathname,r)||t.nextLocation.pathname;return KR(i.pathname,a)!=null||KR(i.pathname,o)!=null}var g1=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(n){return this.listeners.add(n),this.onSubscribe(),()=>{this.listeners.delete(n),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Am,op,cb,YN,vZ=(YN=class extends g1{constructor(){super();N(this,Am);N(this,op);N(this,cb);R(this,cb,e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}})}onSubscribe(){h(this,op)||this.setEventListener(h(this,cb))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,op))==null||e.call(this),R(this,op,void 0))}setEventListener(e){var t;R(this,cb,e),(t=h(this,op))==null||t.call(this),R(this,op,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){h(this,Am)!==e&&(R(this,Am,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){var e;return typeof h(this,Am)=="boolean"?h(this,Am):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Am=new WeakMap,op=new WeakMap,cb=new WeakMap,YN),v6=new vZ,wZ={setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n),setInterval:(n,e)=>setInterval(n,e),clearInterval:n=>clearInterval(n)},ap,SM,QN,SZ=(QN=class{constructor(){N(this,ap,wZ);N(this,SM,!1)}setTimeoutProvider(n){R(this,ap,n)}setTimeout(n,e){return h(this,ap).setTimeout(n,e)}clearTimeout(n){h(this,ap).clearTimeout(n)}setInterval(n,e){return h(this,ap).setInterval(n,e)}clearInterval(n){h(this,ap).clearInterval(n)}},ap=new WeakMap,SM=new WeakMap,QN),xm=new SZ;function jZ(n){setTimeout(n,0)}var kZ=typeof window>"u"||"Deno"in globalThis;function wa(){}function _Z(n,e){return typeof n=="function"?n(e):n}function $R(n){return typeof n=="number"&&n>=0&&n!==1/0}function E9(n,e){return Math.max(n+(e||0)-Date.now(),0)}function Ag(n,e){return typeof n=="function"?n(e):n}function Ml(n,e){return typeof n=="function"?n(e):n}function Yz(n,e){const{type:t="all",exact:r,fetchStatus:i,predicate:o,queryKey:a,stale:l}=n;if(a){if(r){if(e.queryHash!==w6(a,e.options))return!1}else if(!Cj(e.queryKey,a))return!1}if(t!=="all"){const d=e.isActive();if(t==="active"&&!d||t==="inactive"&&d)return!1}return!(typeof l=="boolean"&&e.isStale()!==l||i&&i!==e.state.fetchStatus||o&&!o(e))}function Qz(n,e){const{exact:t,status:r,predicate:i,mutationKey:o}=n;if(o){if(!e.options.mutationKey)return!1;if(t){if(p0(e.options.mutationKey)!==p0(o))return!1}else if(!Cj(e.options.mutationKey,o))return!1}return!(r&&e.state.status!==r||i&&!i(e))}function w6(n,e){return((e==null?void 0:e.queryKeyHashFn)||p0)(n)}function p0(n){return JSON.stringify(n,(e,t)=>ZR(t)?Object.keys(t).sort().reduce((r,i)=>(r[i]=t[i],r),{}):t)}function Cj(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"&&typeof e=="object"?Object.keys(e).every(t=>Cj(n[t],e[t])):!1}var CZ=Object.prototype.hasOwnProperty;function P9(n,e,t=0){if(n===e)return n;if(t>500)return e;const r=$z(n)&&$z(e);if(!r&&!(ZR(n)&&ZR(e)))return e;const o=(r?n:Object.keys(n)).length,a=r?e:Object.keys(e),l=a.length,d=r?new Array(l):{};let c=0;for(let u=0;u{xm.setTimeout(e,n)})}function JR(n,e,t){return typeof t.structuralSharing=="function"?t.structuralSharing(n,e):t.structuralSharing!==!1?P9(n,e):e}function TZ(n,e,t=0){const r=[...n,e];return t&&r.length>t?r.slice(1):r}function FZ(n,e,t=0){const r=[e,...n];return t&&r.length>t?r.slice(0,-1):r}var S6=Symbol();function R9(n,e){return!n.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!n.queryFn||n.queryFn===S6?()=>Promise.reject(new Error(`Missing queryFn: '${n.queryHash}'`)):n.queryFn}function j6(n,e){return typeof n=="function"?n(...e):!!n}function DZ(n,e,t){let r=!1,i;return Object.defineProperty(n,"signal",{enumerable:!0,get:()=>(i??(i=e()),r||(r=!0,i.aborted?t():i.addEventListener("abort",t,{once:!0})),i)}),n}var Aj=(()=>{let n=()=>kZ;return{isServer(){return n()},setIsServer(e){n=e}}})();function eB(){let n,e;const t=new Promise((i,o)=>{n=i,e=o});t.status="pending",t.catch(()=>{});function r(i){Object.assign(t,i),delete t.resolve,delete t.reject}return t.resolve=i=>{r({status:"fulfilled",value:i}),n(i)},t.reject=i=>{r({status:"rejected",reason:i}),e(i)},t}var EZ=jZ;function PZ(){let n=[],e=0,t=l=>{l()},r=l=>{l()},i=EZ;const o=l=>{e?n.push(l):i(()=>{t(l)})},a=()=>{const l=n;n=[],l.length&&i(()=>{r(()=>{l.forEach(d=>{t(d)})})})};return{batch:l=>{let d;e++;try{d=l()}finally{e--,e||a()}return d},batchCalls:l=>(...d)=>{o(()=>{l(...d)})},schedule:o,setNotifyFunction:l=>{t=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var Ls=PZ(),ub,lp,hb,$N,RZ=($N=class extends g1{constructor(){super();N(this,ub,!0);N(this,lp);N(this,hb);R(this,hb,e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}})}onSubscribe(){h(this,lp)||this.setEventListener(h(this,hb))}onUnsubscribe(){var e;this.hasListeners()||((e=h(this,lp))==null||e.call(this),R(this,lp,void 0))}setEventListener(e){var t;R(this,hb,e),(t=h(this,lp))==null||t.call(this),R(this,lp,e(this.setOnline.bind(this)))}setOnline(e){h(this,ub)!==e&&(R(this,ub,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return h(this,ub)}},ub=new WeakMap,lp=new WeakMap,hb=new WeakMap,$N),UA=new RZ;function BZ(n){return Math.min(1e3*2**n,3e4)}function B9(n){return(n??"online")==="online"?UA.isOnline():!0}var tB=class extends Error{constructor(n){super("CancelledError"),this.revert=n==null?void 0:n.revert,this.silent=n==null?void 0:n.silent}};function I9(n){let e=!1,t=0,r;const i=eB(),o=()=>i.status!=="pending",a=y=>{var v;if(!o()){const x=new tB(y);p(x),(v=n.onCancel)==null||v.call(n,x)}},l=()=>{e=!0},d=()=>{e=!1},c=()=>v6.isFocused()&&(n.networkMode==="always"||UA.isOnline())&&n.canRun(),u=()=>B9(n.networkMode)&&n.canRun(),f=y=>{o()||(r==null||r(),i.resolve(y))},p=y=>{o()||(r==null||r(),i.reject(y))},g=()=>new Promise(y=>{var v;r=x=>{(o()||c())&&y(x)},(v=n.onPause)==null||v.call(n)}).then(()=>{var y;r=void 0,o()||(y=n.onContinue)==null||y.call(n)}),m=()=>{if(o())return;let y;const v=t===0?n.initialPromise:void 0;try{y=v??n.fn()}catch(x){y=Promise.reject(x)}Promise.resolve(y).then(f).catch(x=>{var C;if(o())return;const w=n.retry??(Aj.isServer()?0:3),S=n.retryDelay??BZ,_=typeof S=="function"?S(t,x):S,b=w===!0||typeof w=="number"&&tc()?void 0:g()).then(()=>{e?p(x):m()})})};return{promise:i,status:()=>i.status,cancel:a,continue:()=>(r==null||r(),i),cancelRetry:l,continueRetry:d,canStart:u,start:()=>(u()?m():g().then(m),i)}}var Tm,ZN,M9=(ZN=class{constructor(){N(this,Tm)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),$R(this.gcTime)&&R(this,Tm,xm.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(n){this.gcTime=Math.max(this.gcTime||0,n??(Aj.isServer()?1/0:5*60*1e3))}clearGcTimeout(){h(this,Tm)!==void 0&&(xm.clearTimeout(h(this,Tm)),R(this,Tm,void 0))}},Tm=new WeakMap,ZN);function IZ(n){return{onFetch:(e,t)=>{var u,f,p,g,m;const r=e.options,i=(p=(f=(u=e.fetchOptions)==null?void 0:u.meta)==null?void 0:f.fetchMore)==null?void 0:p.direction,o=((g=e.state.data)==null?void 0:g.pages)||[],a=((m=e.state.data)==null?void 0:m.pageParams)||[];let l={pages:[],pageParams:[]},d=0;const c=async()=>{let y=!1;const v=S=>{DZ(S,()=>e.signal,()=>y=!0)},x=R9(e.options,e.fetchOptions),w=async(S,_,b)=>{if(y)return Promise.reject(e.signal.reason);if(_==null&&S.pages.length)return Promise.resolve(S);const T=(()=>{const P={client:e.client,queryKey:e.queryKey,pageParam:_,direction:b?"backward":"forward",meta:e.options.meta};return v(P),P})(),F=await x(T),{maxPages:A}=e.options,D=b?FZ:TZ;return{pages:D(S.pages,F,A),pageParams:D(S.pageParams,_,A)}};if(i&&o.length){const S=i==="backward",_=S?MZ:Jz,b={pages:o,pageParams:a},C=_(r,b);l=await w(b,C,S)}else{const S=n??o.length;do{const _=d===0?a[0]??r.initialPageParam:Jz(r,l);if(d>0&&_==null)break;l=await w(l,_),d++}while(d{var y,v;return(v=(y=e.options).persister)==null?void 0:v.call(y,c,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},t)}:e.fetchFn=c}}}function Jz(n,{pages:e,pageParams:t}){const r=e.length-1;return e.length>0?n.getNextPageParam(e[r],e,t[r],t):void 0}function MZ(n,{pages:e,pageParams:t}){var r;return e.length>0?(r=n.getPreviousPageParam)==null?void 0:r.call(n,e[0],e,t[0],t):void 0}var fb,Fm,pb,dd,Dm,eo,Zj,Em,Il,z9,dh,JN,zZ=(JN=class extends M9{constructor(e){super();N(this,Il);N(this,fb);N(this,Fm);N(this,pb);N(this,dd);N(this,Dm);N(this,eo);N(this,Zj);N(this,Em);R(this,Em,!1),R(this,Zj,e.defaultOptions),this.setOptions(e.options),this.observers=[],R(this,Dm,e.client),R(this,dd,h(this,Dm).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,R(this,Fm,tO(this.options)),this.state=e.state??h(this,Fm),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return h(this,fb)}get promise(){var e;return(e=h(this,eo))==null?void 0:e.promise}setOptions(e){if(this.options={...h(this,Zj),...e},e!=null&&e._type&&R(this,fb,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=tO(this.options);t.data!==void 0&&(this.setState(eO(t.data,t.dataUpdatedAt)),R(this,Fm,t))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&h(this,dd).remove(this)}setData(e,t){const r=JR(this.state.data,e,this.options);return q(this,Il,dh).call(this,{data:r,type:"success",dataUpdatedAt:t==null?void 0:t.updatedAt,manual:t==null?void 0:t.manual}),r}setState(e){q(this,Il,dh).call(this,{type:"setState",state:e})}cancel(e){var r,i;const t=(r=h(this,eo))==null?void 0:r.promise;return(i=h(this,eo))==null||i.cancel(e),t?t.then(wa).catch(wa):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return h(this,Fm)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Ml(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===S6||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ag(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!E9(this.state.dataUpdatedAt,e)}onFocus(){var t;const e=this.observers.find(r=>r.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,eo))==null||t.continue()}onOnline(){var t;const e=this.observers.find(r=>r.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(t=h(this,eo))==null||t.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),h(this,dd).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(h(this,eo)&&(h(this,Em)||q(this,Il,z9).call(this)?h(this,eo).cancel({revert:!0}):h(this,eo).cancelRetry()),this.scheduleGc()),h(this,dd).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,Il,dh).call(this,{type:"invalidate"})}async fetch(e,t){var c,u,f,p,g,m,y,v,x,w,S;if(this.state.fetchStatus!=="idle"&&((c=h(this,eo))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(t!=null&&t.cancelRefetch))this.cancel({silent:!0});else if(h(this,eo))return h(this,eo).continueRetry(),h(this,eo).promise}if(e&&this.setOptions(e),!this.options.queryFn){const _=this.observers.find(b=>b.options.queryFn);_&&this.setOptions(_.options)}const r=new AbortController,i=_=>{Object.defineProperty(_,"signal",{enumerable:!0,get:()=>(R(this,Em,!0),r.signal)})},o=()=>{const _=R9(this.options,t),C=(()=>{const T={client:h(this,Dm),queryKey:this.queryKey,meta:this.meta};return i(T),T})();return R(this,Em,!1),this.options.persister?this.options.persister(_,C,this):_(C)},l=(()=>{const _={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:h(this,Dm),state:this.state,fetchFn:o};return i(_),_})(),d=h(this,fb)==="infinite"?IZ(this.options.pages):this.options.behavior;d==null||d.onFetch(l,this),R(this,pb,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=l.fetchOptions)==null?void 0:u.meta))&&q(this,Il,dh).call(this,{type:"fetch",meta:(f=l.fetchOptions)==null?void 0:f.meta}),R(this,eo,I9({initialPromise:t==null?void 0:t.initialPromise,fn:l.fetchFn,onCancel:_=>{_ instanceof tB&&_.revert&&this.setState({...h(this,pb),fetchStatus:"idle"}),r.abort()},onFail:(_,b)=>{q(this,Il,dh).call(this,{type:"failed",failureCount:_,error:b})},onPause:()=>{q(this,Il,dh).call(this,{type:"pause"})},onContinue:()=>{q(this,Il,dh).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const _=await h(this,eo).start();if(_===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(_),(g=(p=h(this,dd).config).onSuccess)==null||g.call(p,_,this),(y=(m=h(this,dd).config).onSettled)==null||y.call(m,_,this.state.error,this),_}catch(_){if(_ instanceof tB){if(_.silent)return h(this,eo).promise;if(_.revert){if(this.state.data===void 0)throw _;return this.state.data}}throw q(this,Il,dh).call(this,{type:"error",error:_}),(x=(v=h(this,dd).config).onError)==null||x.call(v,_,this),(S=(w=h(this,dd).config).onSettled)==null||S.call(w,this.state.data,_,this),_}finally{this.scheduleGc()}}},fb=new WeakMap,Fm=new WeakMap,pb=new WeakMap,dd=new WeakMap,Dm=new WeakMap,eo=new WeakMap,Zj=new WeakMap,Em=new WeakMap,Il=new WeakSet,z9=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},dh=function(e){const t=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...O9(r.data,this.options),fetchMeta:e.meta??null};case"success":const i={...r,...eO(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return R(this,pb,e.manual?i:void 0),i;case"error":const o=e.error;return{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=t(this.state),Ls.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),h(this,dd).notify({query:this,type:"updated",action:e})})},JN);function O9(n,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:B9(e.networkMode)?"fetching":"paused",...n===void 0&&{error:null,status:"pending"}}}function eO(n,e){return{data:n,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tO(n){const e=typeof n.initialData=="function"?n.initialData():n.initialData,t=e!==void 0,r=t?typeof n.initialDataUpdatedAt=="function"?n.initialDataUpdatedAt():n.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:t?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:t?"success":"pending",fetchStatus:"idle"}}var Wa,ur,Jj,fa,Pm,gb,jh,dp,ek,mb,yb,Rm,Bm,cp,xb,qr,Zw,nB,rB,iB,sB,oB,aB,lB,L9,e7,OZ=(e7=class extends g1{constructor(e,t){super();N(this,qr);N(this,Wa);N(this,ur);N(this,Jj);N(this,fa);N(this,Pm);N(this,gb);N(this,jh);N(this,dp);N(this,ek);N(this,mb);N(this,yb);N(this,Rm);N(this,Bm);N(this,cp);N(this,xb,new Set);this.options=t,R(this,Wa,e),R(this,dp,null),R(this,jh,eB()),this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(h(this,ur).addObserver(this),nO(h(this,ur),this.options)?q(this,qr,Zw).call(this):this.updateResult(),q(this,qr,sB).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dB(h(this,ur),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dB(h(this,ur),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,qr,oB).call(this),q(this,qr,aB).call(this),h(this,ur).removeObserver(this)}setOptions(e){const t=this.options,r=h(this,ur);if(this.options=h(this,Wa).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ml(this.options.enabled,h(this,ur))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,qr,lB).call(this),h(this,ur).setOptions(this.options),t._defaulted&&!WA(this.options,t)&&h(this,Wa).getQueryCache().notify({type:"observerOptionsUpdated",query:h(this,ur),observer:this});const i=this.hasListeners();i&&rO(h(this,ur),r,this.options,t)&&q(this,qr,Zw).call(this),this.updateResult(),i&&(h(this,ur)!==r||Ml(this.options.enabled,h(this,ur))!==Ml(t.enabled,h(this,ur))||Ag(this.options.staleTime,h(this,ur))!==Ag(t.staleTime,h(this,ur)))&&q(this,qr,nB).call(this);const o=q(this,qr,rB).call(this);i&&(h(this,ur)!==r||Ml(this.options.enabled,h(this,ur))!==Ml(t.enabled,h(this,ur))||o!==h(this,cp))&&q(this,qr,iB).call(this,o)}getOptimisticResult(e){const t=h(this,Wa).getQueryCache().build(h(this,Wa),e),r=this.createResult(t,e);return NZ(this,r)&&(R(this,fa,r),R(this,gb,this.options),R(this,Pm,h(this,ur).state)),r}getCurrentResult(){return h(this,fa)}trackResult(e,t){return new Proxy(e,{get:(r,i)=>(this.trackProp(i),t==null||t(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&h(this,jh).status==="pending"&&h(this,jh).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,i))})}trackProp(e){h(this,xb).add(e)}getCurrentQuery(){return h(this,ur)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=h(this,Wa).defaultQueryOptions(e),r=h(this,Wa).getQueryCache().build(h(this,Wa),t);return r.fetch().then(()=>this.createResult(r,t))}fetch(e){return q(this,qr,Zw).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),h(this,fa)))}createResult(e,t){var A;const r=h(this,ur),i=this.options,o=h(this,fa),a=h(this,Pm),l=h(this,gb),c=e!==r?e.state:h(this,Jj),{state:u}=e;let f={...u},p=!1,g;if(t._optimisticResults){const D=this.hasListeners(),P=!D&&nO(e,t),L=D&&rO(e,r,t,i);(P||L)&&(f={...f,...O9(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:v}=f;g=f.data;let x=!1;if(t.placeholderData!==void 0&&g===void 0&&v==="pending"){let D;o!=null&&o.isPlaceholderData&&t.placeholderData===(l==null?void 0:l.placeholderData)?(D=o.data,x=!0):D=typeof t.placeholderData=="function"?t.placeholderData((A=h(this,yb))==null?void 0:A.state.data,h(this,yb)):t.placeholderData,D!==void 0&&(v="success",g=JR(o==null?void 0:o.data,D,t),p=!0)}if(t.select&&g!==void 0&&!x)if(o&&g===(a==null?void 0:a.data)&&t.select===h(this,ek))g=h(this,mb);else try{R(this,ek,t.select),g=t.select(g),g=JR(o==null?void 0:o.data,g,t),R(this,mb,g),R(this,dp,null)}catch(D){R(this,dp,D)}h(this,dp)&&(m=h(this,dp),g=h(this,mb),y=Date.now(),v="error");const w=f.fetchStatus==="fetching",S=v==="pending",_=v==="error",b=S&&w,C=g!==void 0,F={status:v,fetchStatus:f.fetchStatus,isPending:S,isSuccess:v==="success",isError:_,isInitialLoading:b,isLoading:b,data:g,dataUpdatedAt:f.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:f.dataUpdateCount>c.dataUpdateCount||f.errorUpdateCount>c.errorUpdateCount,isFetching:w,isRefetching:w&&!S,isLoadingError:_&&!C,isPaused:f.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:_&&C,isStale:k6(e,t),refetch:this.refetch,promise:h(this,jh),isEnabled:Ml(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const D=F.data!==void 0,P=F.status==="error"&&!D,L=U=>{P?U.reject(F.error):D&&U.resolve(F.data)},W=()=>{const U=R(this,jh,F.promise=eB());L(U)},O=h(this,jh);switch(O.status){case"pending":e.queryHash===r.queryHash&&L(O);break;case"fulfilled":(P||F.data!==O.value)&&W();break;case"rejected":(!P||F.error!==O.reason)&&W();break}}return F}updateResult(){const e=h(this,fa),t=this.createResult(h(this,ur),this.options);if(R(this,Pm,h(this,ur).state),R(this,gb,this.options),h(this,Pm).data!==void 0&&R(this,yb,h(this,ur)),WA(t,e))return;R(this,fa,t);const r=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!h(this,xb).size)return!0;const a=new Set(o??h(this,xb));return this.options.throwOnError&&a.add("error"),Object.keys(h(this,fa)).some(l=>{const d=l;return h(this,fa)[d]!==e[d]&&a.has(d)})};q(this,qr,L9).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,qr,sB).call(this)}},Wa=new WeakMap,ur=new WeakMap,Jj=new WeakMap,fa=new WeakMap,Pm=new WeakMap,gb=new WeakMap,jh=new WeakMap,dp=new WeakMap,ek=new WeakMap,mb=new WeakMap,yb=new WeakMap,Rm=new WeakMap,Bm=new WeakMap,cp=new WeakMap,xb=new WeakMap,qr=new WeakSet,Zw=function(e){q(this,qr,lB).call(this);let t=h(this,ur).fetch(this.options,e);return e!=null&&e.throwOnError||(t=t.catch(wa)),t},nB=function(){q(this,qr,oB).call(this);const e=Ag(this.options.staleTime,h(this,ur));if(Aj.isServer()||h(this,fa).isStale||!$R(e))return;const r=E9(h(this,fa).dataUpdatedAt,e)+1;R(this,Rm,xm.setTimeout(()=>{h(this,fa).isStale||this.updateResult()},r))},rB=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(h(this,ur)):this.options.refetchInterval)??!1},iB=function(e){q(this,qr,aB).call(this),R(this,cp,e),!(Aj.isServer()||Ml(this.options.enabled,h(this,ur))===!1||!$R(h(this,cp))||h(this,cp)===0)&&R(this,Bm,xm.setInterval(()=>{(this.options.refetchIntervalInBackground||v6.isFocused())&&q(this,qr,Zw).call(this)},h(this,cp)))},sB=function(){q(this,qr,nB).call(this),q(this,qr,iB).call(this,q(this,qr,rB).call(this))},oB=function(){h(this,Rm)!==void 0&&(xm.clearTimeout(h(this,Rm)),R(this,Rm,void 0))},aB=function(){h(this,Bm)!==void 0&&(xm.clearInterval(h(this,Bm)),R(this,Bm,void 0))},lB=function(){const e=h(this,Wa).getQueryCache().build(h(this,Wa),this.options);if(e===h(this,ur))return;const t=h(this,ur);R(this,ur,e),R(this,Jj,e.state),this.hasListeners()&&(t==null||t.removeObserver(this),e.addObserver(this))},L9=function(e){Ls.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(h(this,fa))}),h(this,Wa).getQueryCache().notify({query:h(this,ur),type:"observerResultsUpdated"})})},e7);function LZ(n,e){return Ml(e.enabled,n)!==!1&&n.state.data===void 0&&!(n.state.status==="error"&&Ml(e.retryOnMount,n)===!1)}function nO(n,e){return LZ(n,e)||n.state.data!==void 0&&dB(n,e,e.refetchOnMount)}function dB(n,e,t){if(Ml(e.enabled,n)!==!1&&Ag(e.staleTime,n)!=="static"){const r=typeof t=="function"?t(n):t;return r==="always"||r!==!1&&k6(n,e)}return!1}function rO(n,e,t,r){return(n!==e||Ml(r.enabled,n)===!1)&&(!t.suspense||n.state.status!=="error")&&k6(n,t)}function k6(n,e){return Ml(e.enabled,n)!==!1&&n.isStaleByTime(Ag(e.staleTime,n))}function NZ(n,e){return!WA(n.getCurrentResult(),e)}var tk,eu,Qo,Im,tu,Xf,t7,WZ=(t7=class extends M9{constructor(e){super();N(this,tu);N(this,tk);N(this,eu);N(this,Qo);N(this,Im);R(this,tk,e.client),this.mutationId=e.mutationId,R(this,Qo,e.mutationCache),R(this,eu,[]),this.state=e.state||N9(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){h(this,eu).includes(e)||(h(this,eu).push(e),this.clearGcTimeout(),h(this,Qo).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){R(this,eu,h(this,eu).filter(t=>t!==e)),this.scheduleGc(),h(this,Qo).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){h(this,eu).length||(this.state.status==="pending"?this.scheduleGc():h(this,Qo).remove(this))}continue(){var e;return((e=h(this,Im))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,l,d,c,u,f,p,g,m,y,v,x,w,S,_,b,C,T;const t=()=>{q(this,tu,Xf).call(this,{type:"continue"})},r={client:h(this,tk),meta:this.options.meta,mutationKey:this.options.mutationKey};R(this,Im,I9({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(F,A)=>{q(this,tu,Xf).call(this,{type:"failed",failureCount:F,error:A})},onPause:()=>{q(this,tu,Xf).call(this,{type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>h(this,Qo).canRun(this)}));const i=this.state.status==="pending",o=!h(this,Im).canStart();try{if(i)t();else{q(this,tu,Xf).call(this,{type:"pending",variables:e,isPaused:o}),h(this,Qo).config.onMutate&&await h(this,Qo).config.onMutate(e,this,r);const A=await((l=(a=this.options).onMutate)==null?void 0:l.call(a,e,r));A!==this.state.context&&q(this,tu,Xf).call(this,{type:"pending",context:A,variables:e,isPaused:o})}const F=await h(this,Im).start();return await((c=(d=h(this,Qo).config).onSuccess)==null?void 0:c.call(d,F,e,this.state.context,this,r)),await((f=(u=this.options).onSuccess)==null?void 0:f.call(u,F,e,this.state.context,r)),await((g=(p=h(this,Qo).config).onSettled)==null?void 0:g.call(p,F,null,this.state.variables,this.state.context,this,r)),await((y=(m=this.options).onSettled)==null?void 0:y.call(m,F,null,e,this.state.context,r)),q(this,tu,Xf).call(this,{type:"success",data:F}),F}catch(F){try{await((x=(v=h(this,Qo).config).onError)==null?void 0:x.call(v,F,e,this.state.context,this,r))}catch(A){Promise.reject(A)}try{await((S=(w=this.options).onError)==null?void 0:S.call(w,F,e,this.state.context,r))}catch(A){Promise.reject(A)}try{await((b=(_=h(this,Qo).config).onSettled)==null?void 0:b.call(_,void 0,F,this.state.variables,this.state.context,this,r))}catch(A){Promise.reject(A)}try{await((T=(C=this.options).onSettled)==null?void 0:T.call(C,void 0,F,e,this.state.context,r))}catch(A){Promise.reject(A)}throw q(this,tu,Xf).call(this,{type:"error",error:F}),F}finally{h(this,Qo).runNext(this)}}},tk=new WeakMap,eu=new WeakMap,Qo=new WeakMap,Im=new WeakMap,tu=new WeakSet,Xf=function(e){const t=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Ls.batch(()=>{h(this,eu).forEach(r=>{r.onMutationUpdate(e)}),h(this,Qo).notify({mutation:this,type:"updated",action:e})})},t7);function N9(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var kh,lc,nk,n7,UZ=(n7=class extends g1{constructor(e={}){super();N(this,kh);N(this,lc);N(this,nk);this.config=e,R(this,kh,new Set),R(this,lc,new Map),R(this,nk,0)}build(e,t,r){const i=new WZ({client:e,mutationCache:this,mutationId:++Gi(this,nk)._,options:e.defaultMutationOptions(t),state:r});return this.add(i),i}add(e){h(this,kh).add(e);const t=f2(e);if(typeof t=="string"){const r=h(this,lc).get(t);r?r.push(e):h(this,lc).set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(h(this,kh).delete(e)){const t=f2(e);if(typeof t=="string"){const r=h(this,lc).get(t);if(r)if(r.length>1){const i=r.indexOf(e);i!==-1&&r.splice(i,1)}else r[0]===e&&h(this,lc).delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=f2(e);if(typeof t=="string"){const r=h(this,lc).get(t),i=r==null?void 0:r.find(o=>o.state.status==="pending");return!i||i===e}else return!0}runNext(e){var r;const t=f2(e);if(typeof t=="string"){const i=(r=h(this,lc).get(t))==null?void 0:r.find(o=>o!==e&&o.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ls.batch(()=>{h(this,kh).forEach(e=>{this.notify({type:"removed",mutation:e})}),h(this,kh).clear(),h(this,lc).clear()})}getAll(){return Array.from(h(this,kh))}find(e){const t={exact:!0,...e};return this.getAll().find(r=>Qz(t,r))}findAll(e={}){return this.getAll().filter(t=>Qz(e,t))}notify(e){Ls.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Ls.batch(()=>Promise.all(e.map(t=>t.continue().catch(wa))))}},kh=new WeakMap,lc=new WeakMap,nk=new WeakMap,n7);function f2(n){var e;return(e=n.options.scope)==null?void 0:e.id}var _h,up,Ua,Ch,xf,h5,cB,r7,HZ=(r7=class extends g1{constructor(t,r){super();N(this,xf);N(this,_h);N(this,up);N(this,Ua);N(this,Ch);R(this,_h,t),this.setOptions(r),this.bindMethods(),q(this,xf,h5).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){var i;const r=this.options;this.options=h(this,_h).defaultMutationOptions(t),WA(this.options,r)||h(this,_h).getMutationCache().notify({type:"observerOptionsUpdated",mutation:h(this,Ua),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&p0(r.mutationKey)!==p0(this.options.mutationKey)?this.reset():((i=h(this,Ua))==null?void 0:i.state.status)==="pending"&&h(this,Ua).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=h(this,Ua))==null||t.removeObserver(this)}onMutationUpdate(t){q(this,xf,h5).call(this),q(this,xf,cB).call(this,t)}getCurrentResult(){return h(this,up)}reset(){var t;(t=h(this,Ua))==null||t.removeObserver(this),R(this,Ua,void 0),q(this,xf,h5).call(this),q(this,xf,cB).call(this)}mutate(t,r){var i;return R(this,Ch,r),(i=h(this,Ua))==null||i.removeObserver(this),R(this,Ua,h(this,_h).getMutationCache().build(h(this,_h),this.options)),h(this,Ua).addObserver(this),h(this,Ua).execute(t)}},_h=new WeakMap,up=new WeakMap,Ua=new WeakMap,Ch=new WeakMap,xf=new WeakSet,h5=function(){var r;const t=((r=h(this,Ua))==null?void 0:r.state)??N9();R(this,up,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},cB=function(t){Ls.batch(()=>{var r,i,o,a,l,d,c,u;if(h(this,Ch)&&this.hasListeners()){const f=h(this,up).variables,p=h(this,up).context,g={client:h(this,_h),meta:this.options.meta,mutationKey:this.options.mutationKey};if((t==null?void 0:t.type)==="success"){try{(i=(r=h(this,Ch)).onSuccess)==null||i.call(r,t.data,f,p,g)}catch(m){Promise.reject(m)}try{(a=(o=h(this,Ch)).onSettled)==null||a.call(o,t.data,null,f,p,g)}catch(m){Promise.reject(m)}}else if((t==null?void 0:t.type)==="error"){try{(d=(l=h(this,Ch)).onError)==null||d.call(l,t.error,f,p,g)}catch(m){Promise.reject(m)}try{(u=(c=h(this,Ch)).onSettled)==null||u.call(c,void 0,t.error,f,p,g)}catch(m){Promise.reject(m)}}}this.listeners.forEach(f=>{f(h(this,up))})})},r7),nu,i7,qZ=(i7=class extends g1{constructor(e={}){super();N(this,nu);this.config=e,R(this,nu,new Map)}build(e,t,r){const i=t.queryKey,o=t.queryHash??w6(i,t);let a=this.get(o);return a||(a=new zZ({client:e,queryKey:i,queryHash:o,options:e.defaultQueryOptions(t),state:r,defaultOptions:e.getQueryDefaults(i)}),this.add(a)),a}add(e){h(this,nu).has(e.queryHash)||(h(this,nu).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=h(this,nu).get(e.queryHash);t&&(e.destroy(),t===e&&h(this,nu).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ls.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return h(this,nu).get(e)}getAll(){return[...h(this,nu).values()]}find(e){const t={exact:!0,...e};return this.getAll().find(r=>Yz(t,r))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(r=>Yz(e,r)):t}notify(e){Ls.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Ls.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ls.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},nu=new WeakMap,i7),os,hp,fp,bb,vb,pp,wb,Sb,s7,VZ=(s7=class{constructor(n={}){N(this,os);N(this,hp);N(this,fp);N(this,bb);N(this,vb);N(this,pp);N(this,wb);N(this,Sb);R(this,os,n.queryCache||new qZ),R(this,hp,n.mutationCache||new UZ),R(this,fp,n.defaultOptions||{}),R(this,bb,new Map),R(this,vb,new Map),R(this,pp,0)}mount(){Gi(this,pp)._++,h(this,pp)===1&&(R(this,wb,v6.subscribe(async n=>{n&&(await this.resumePausedMutations(),h(this,os).onFocus())})),R(this,Sb,UA.subscribe(async n=>{n&&(await this.resumePausedMutations(),h(this,os).onOnline())})))}unmount(){var n,e;Gi(this,pp)._--,h(this,pp)===0&&((n=h(this,wb))==null||n.call(this),R(this,wb,void 0),(e=h(this,Sb))==null||e.call(this),R(this,Sb,void 0))}isFetching(n){return h(this,os).findAll({...n,fetchStatus:"fetching"}).length}isMutating(n){return h(this,hp).findAll({...n,status:"pending"}).length}getQueryData(n){var t;const e=this.defaultQueryOptions({queryKey:n});return(t=h(this,os).get(e.queryHash))==null?void 0:t.state.data}ensureQueryData(n){const e=this.defaultQueryOptions(n),t=h(this,os).build(this,e),r=t.state.data;return r===void 0?this.fetchQuery(n):(n.revalidateIfStale&&t.isStaleByTime(Ag(e.staleTime,t))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(n){return h(this,os).findAll(n).map(({queryKey:e,state:t})=>{const r=t.data;return[e,r]})}setQueryData(n,e,t){const r=this.defaultQueryOptions({queryKey:n}),i=h(this,os).get(r.queryHash),o=i==null?void 0:i.state.data,a=_Z(e,o);if(a!==void 0)return h(this,os).build(this,r).setData(a,{...t,manual:!0})}setQueriesData(n,e,t){return Ls.batch(()=>h(this,os).findAll(n).map(({queryKey:r})=>[r,this.setQueryData(r,e,t)]))}getQueryState(n){var t;const e=this.defaultQueryOptions({queryKey:n});return(t=h(this,os).get(e.queryHash))==null?void 0:t.state}removeQueries(n){const e=h(this,os);Ls.batch(()=>{e.findAll(n).forEach(t=>{e.remove(t)})})}resetQueries(n,e){const t=h(this,os);return Ls.batch(()=>(t.findAll(n).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...n},e)))}cancelQueries(n,e={}){const t={revert:!0,...e},r=Ls.batch(()=>h(this,os).findAll(n).map(i=>i.cancel(t)));return Promise.all(r).then(wa).catch(wa)}invalidateQueries(n,e={}){return Ls.batch(()=>(h(this,os).findAll(n).forEach(t=>{t.invalidate()}),(n==null?void 0:n.refetchType)==="none"?Promise.resolve():this.refetchQueries({...n,type:(n==null?void 0:n.refetchType)??(n==null?void 0:n.type)??"active"},e)))}refetchQueries(n,e={}){const t={...e,cancelRefetch:e.cancelRefetch??!0},r=Ls.batch(()=>h(this,os).findAll(n).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,t);return t.throwOnError||(o=o.catch(wa)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(wa)}fetchQuery(n){const e=this.defaultQueryOptions(n);e.retry===void 0&&(e.retry=!1);const t=h(this,os).build(this,e);return t.isStaleByTime(Ag(e.staleTime,t))?t.fetch(e):Promise.resolve(t.state.data)}prefetchQuery(n){return this.fetchQuery(n).then(wa).catch(wa)}fetchInfiniteQuery(n){return n._type="infinite",this.fetchQuery(n)}prefetchInfiniteQuery(n){return this.fetchInfiniteQuery(n).then(wa).catch(wa)}ensureInfiniteQueryData(n){return n._type="infinite",this.ensureQueryData(n)}resumePausedMutations(){return UA.isOnline()?h(this,hp).resumePausedMutations():Promise.resolve()}getQueryCache(){return h(this,os)}getMutationCache(){return h(this,hp)}getDefaultOptions(){return h(this,fp)}setDefaultOptions(n){R(this,fp,n)}setQueryDefaults(n,e){h(this,bb).set(p0(n),{queryKey:n,defaultOptions:e})}getQueryDefaults(n){const e=[...h(this,bb).values()],t={};return e.forEach(r=>{Cj(n,r.queryKey)&&Object.assign(t,r.defaultOptions)}),t}setMutationDefaults(n,e){h(this,vb).set(p0(n),{mutationKey:n,defaultOptions:e})}getMutationDefaults(n){const e=[...h(this,vb).values()],t={};return e.forEach(r=>{Cj(n,r.mutationKey)&&Object.assign(t,r.defaultOptions)}),t}defaultQueryOptions(n){if(n._defaulted)return n;const e={...h(this,fp).queries,...this.getQueryDefaults(n.queryKey),...n,_defaulted:!0};return e.queryHash||(e.queryHash=w6(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===S6&&(e.enabled=!1),e}defaultMutationOptions(n){return n!=null&&n._defaulted?n:{...h(this,fp).mutations,...(n==null?void 0:n.mutationKey)&&this.getMutationDefaults(n.mutationKey),...n,_defaulted:!0}}clear(){h(this,os).clear(),h(this,hp).clear()}},os=new WeakMap,hp=new WeakMap,fp=new WeakMap,bb=new WeakMap,vb=new WeakMap,pp=new WeakMap,wb=new WeakMap,Sb=new WeakMap,s7),W9=k.createContext(void 0),pi=n=>{const e=k.useContext(W9);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},GZ=({client:n,children:e})=>(k.useEffect(()=>(n.mount(),()=>{n.unmount()}),[n]),s.jsx(W9.Provider,{value:n,children:e})),U9=k.createContext(!1),KZ=()=>k.useContext(U9);U9.Provider;function XZ(){let n=!1;return{clearReset:()=>{n=!1},reset:()=>{n=!0},isReset:()=>n}}var YZ=k.createContext(XZ()),QZ=()=>k.useContext(YZ),$Z=(n,e,t)=>{const r=t!=null&&t.state.error&&typeof n.throwOnError=="function"?j6(n.throwOnError,[t.state.error,t]):n.throwOnError;(n.suspense||n.experimental_prefetchInRender||r)&&(e.isReset()||(n.retryOnMount=!1))},ZZ=n=>{k.useEffect(()=>{n.clearReset()},[n])},JZ=({result:n,errorResetBoundary:e,throwOnError:t,query:r,suspense:i})=>n.isError&&!e.isReset()&&!n.isFetching&&r&&(i&&n.data===void 0||j6(t,[n.error,r])),eJ=n=>{if(n.suspense){const t=i=>i==="static"?i:Math.max(i??1e3,1e3),r=n.staleTime;n.staleTime=typeof r=="function"?(...i)=>t(r(...i)):t(r),typeof n.gcTime=="number"&&(n.gcTime=Math.max(n.gcTime,1e3))}},tJ=(n,e)=>n.isLoading&&n.isFetching&&!e,nJ=(n,e)=>(n==null?void 0:n.suspense)&&e.isPending,iO=(n,e,t)=>e.fetchOptimistic(n).catch(()=>{t.clearReset()});function rJ(n,e,t){var g,m,y,v;const r=KZ(),i=QZ(),o=pi(),a=o.defaultQueryOptions(n);(m=(g=o.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||m.call(g,a);const l=o.getQueryCache().get(a.queryHash),d=n.subscribed!==!1;a._optimisticResults=r?"isRestoring":d?"optimistic":void 0,eJ(a),$Z(a,i,l),ZZ(i);const c=!o.getQueryCache().get(a.queryHash),[u]=k.useState(()=>new e(o,a)),f=u.getOptimisticResult(a),p=!r&&d;if(k.useSyncExternalStore(k.useCallback(x=>{const w=p?u.subscribe(Ls.batchCalls(x)):wa;return u.updateResult(),w},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),k.useEffect(()=>{u.setOptions(a)},[a,u]),nJ(a,f))throw iO(a,u,i);if(JZ({result:f,errorResetBoundary:i,throwOnError:a.throwOnError,query:l,suspense:a.suspense}))throw f.error;if((v=(y=o.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||v.call(y,a,f),a.experimental_prefetchInRender&&!Aj.isServer()&&tJ(f,r)){const x=c?iO(a,u,i):l==null?void 0:l.promise;x==null||x.catch(wa).finally(()=>{u.updateResult()})}return a.notifyOnChangeProps?f:u.trackResult(f)}function Oe(n,e){return rJ(n,OZ)}function Ue(n,e){const t=pi(),[r]=k.useState(()=>new HZ(t,n));k.useEffect(()=>{r.setOptions(n)},[r,n]);const i=k.useSyncExternalStore(k.useCallback(a=>r.subscribe(Ls.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=k.useCallback((a,l)=>{r.mutate(a,l).catch(wa)},[r]);if(i.error&&j6(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}const H9=k.createContext(null);function gn(){const n=k.useContext(H9);if(!n)throw new Error("useAuth outside AuthGate");return n}function iJ({children:n}){const[e,t]=k.useState(null),[r,i]=k.useState(!0);if(k.useEffect(()=>{fetch("/kitchen/api/auth/verify?app=kitchen",{credentials:"include"}).then(a=>{if(!a.ok)throw new Error("unauth");return a.json()}).then(a=>t({email:a.email||a.sub||"",name:a.name||a.display_name||"",is_admin:a.is_admin??!1,caps:a.caps??[]})).catch(()=>{(window.top??window).location.href="/login"}).finally(()=>i(!1))},[]),r)return s.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--navy-dark)"},children:s.jsx("div",{className:"spinner",style:{width:32,height:32}})});if(!e)return null;const o={user:e,token:"__session__",restrictedPages:[],login:()=>{},logout:()=>{(window.top??window).location.href="/login"}};return s.jsx(H9.Provider,{value:o,children:n})}/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sJ=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),q9=(...n)=>n.filter((e,t,r)=>!!e&&r.indexOf(e)===t).join(" ");/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var oJ={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const aJ=k.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:r,className:i="",children:o,iconNode:a,...l},d)=>k.createElement("svg",{ref:d,...oJ,width:e,height:e,stroke:n,strokeWidth:r?Number(t)*24/Number(e):t,className:q9("lucide",i),...l},[...a.map(([c,u])=>k.createElement(c,u)),...Array.isArray(o)?o:[o]]));/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Mi=(n,e)=>{const t=k.forwardRef(({className:r,...i},o)=>k.createElement(aJ,{ref:o,iconNode:e,className:q9(`lucide-${sJ(n)}`,r),...i}));return t.displayName=`${n}`,t};/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const lJ=Mi("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sO=Mi("BarChart2",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dJ=Mi("BookOpen",[["path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z",key:"vv98re"}],["path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",key:"1cyq3y"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const cJ=Mi("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sP=Mi("ChefHat",[["path",{d:"M17 21a1 1 0 0 0 1-1v-5.35c0-.457.316-.844.727-1.041a4 4 0 0 0-2.134-7.589 5 5 0 0 0-9.186 0 4 4 0 0 0-2.134 7.588c.411.198.727.585.727 1.041V20a1 1 0 0 0 1 1Z",key:"1qvrer"}],["path",{d:"M6 17h12",key:"1jwigz"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const uJ=Mi("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const hJ=Mi("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fJ=Mi("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const pJ=Mi("Hotel",[["path",{d:"M10 22v-6.57",key:"1wmca3"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M12 7h.01",key:"1ivr5q"}],["path",{d:"M14 15.43V22",key:"1q2vjd"}],["path",{d:"M15 16a5 5 0 0 0-6 0",key:"o9wqvi"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 7h.01",key:"1vti4s"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const gJ=Mi("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const mJ=Mi("List",[["line",{x1:"8",x2:"21",y1:"6",y2:"6",key:"7ey8pc"}],["line",{x1:"8",x2:"21",y1:"12",y2:"12",key:"rjfblc"}],["line",{x1:"8",x2:"21",y1:"18",y2:"18",key:"c3b1m8"}],["line",{x1:"3",x2:"3.01",y1:"6",y2:"6",key:"1g7gq3"}],["line",{x1:"3",x2:"3.01",y1:"12",y2:"12",key:"1pjlvk"}],["line",{x1:"3",x2:"3.01",y1:"18",y2:"18",key:"28t2mc"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const yJ=Mi("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const xJ=Mi("Package",[["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const oO=Mi("PieChart",[["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}],["path",{d:"M22 12A10 10 0 0 0 12 2v10z",key:"1rfc4y"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const bJ=Mi("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const vJ=Mi("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const wJ=Mi("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const SJ=Mi("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const jJ=Mi("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const aO=Mi("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const kJ=Mi("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const _J=Mi("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const CJ=Mi("UtensilsCrossed",[["path",{d:"m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8",key:"n7qcjb"}],["path",{d:"M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7",key:"d0u48b"}],["path",{d:"m2.1 21.8 6.4-6.3",key:"yn04lh"}],["path",{d:"m19 5-7 7",key:"194lzd"}]]);/** - * @license lucide-react v0.395.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const AJ=Mi("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);function Ma(n,e){return n?n.is_admin||n.caps.includes(e):!1}const TJ={size:15,strokeWidth:1.75};function dx({label:n,children:e}){return s.jsxs("div",{className:"sidebar-section",children:[s.jsx("div",{className:"sidebar-section-label",children:n}),e]})}function hi({to:n,label:e,icon:t}){return s.jsxs(wx,{to:n,className:({isActive:r})=>r?"active":"",children:[s.jsx(t,{...TJ}),e]})}function FJ(){const{user:n}=gn();return s.jsxs("div",{className:"app-shell",children:[s.jsxs("aside",{className:"sidebar",children:[s.jsxs("div",{className:"sidebar-logo",children:[s.jsx(sP,{size:18,strokeWidth:1.75,color:"var(--app-primary)"}),"Kitchen"]}),s.jsxs("nav",{className:"sidebar-nav",children:[s.jsx(hi,{to:"/dashboard",label:"Dashboard",icon:gJ}),Ma(n,"invoices")&&s.jsxs(dx,{label:"Invoices",children:[s.jsx(hi,{to:"/upload",label:"Upload",icon:kJ}),s.jsx(hi,{to:"/invoices",label:"Invoices",icon:fJ}),s.jsx(hi,{to:"/search/invoices",label:"Search",icon:vJ}),s.jsx(hi,{to:"/search/line-items",label:"Line Items",icon:mJ}),Ma(n,"disputes")&&s.jsx(hi,{to:"/disputes",label:"Disputes",icon:hJ}),Ma(n,"orders")&&s.jsx(hi,{to:"/purchase-orders",label:"Purchase Orders",icon:jJ})]}),Ma(n,"view")&&s.jsxs(dx,{label:"Reports",children:[s.jsx(hi,{to:"/gp",label:"Kitchen Flash",icon:aO}),s.jsx(hi,{to:"/purchases-report",label:"Purchases",icon:sO}),s.jsx(hi,{to:"/allowances-report",label:"Allowances",icon:oO}),s.jsx(hi,{to:"/sales-gp",label:"Sales GP%",icon:lJ}),s.jsx(hi,{to:"/usage-variance",label:"Usage Variance",icon:uJ}),s.jsx(hi,{to:"/purchases/reconcile",label:"Reconcile",icon:bJ})]}),Ma(n,"logbook")&&s.jsxs(dx,{label:"Kitchen",children:[s.jsx(hi,{to:"/logbook",label:"Allowance Logbook",icon:dJ}),s.jsx(hi,{to:"/budget",label:"Budget",icon:oO}),Ma(n,"orders")&&s.jsx(hi,{to:"/event-orders",label:"Event Orders",icon:xJ})]}),Ma(n,"view")&&s.jsxs(dx,{label:"Bookings",children:[s.jsx(hi,{to:"/resos",label:"ResOS Calendar",icon:cJ}),s.jsx(hi,{to:"/resos-stats",label:"Booking Stats",icon:sO}),s.jsx(hi,{to:"/residents-table-chart",label:"Residents Chart",icon:_J}),s.jsx(hi,{to:"/newbook",label:"NewBook Data",icon:pJ})]}),Ma(n,"recipes")&&s.jsxs(dx,{label:"Recipes",children:[s.jsx(hi,{to:"/ingredients",label:"Ingredients",icon:AJ}),s.jsx(hi,{to:"/recipes",label:"Recipes",icon:sP}),s.jsx(hi,{to:"/dishes",label:"Dishes",icon:CJ}),Ma(n,"menus")&&s.jsx(hi,{to:"/menus",label:"Menus",icon:yJ}),s.jsx(hi,{to:"/allergens",label:"Allergens",icon:SJ}),s.jsx(hi,{to:"/price-impact",label:"Price Impact",icon:aO})]}),Ma(n,"settings")&&s.jsx(dx,{label:"",children:s.jsx(hi,{to:"/settings",label:"Settings",icon:wJ})})]}),s.jsx("div",{className:"sidebar-user",children:n.name||n.email})]}),s.jsxs("header",{className:"top-bar",children:[s.jsx(sP,{size:16,strokeWidth:1.75,color:"var(--app-primary)"}),s.jsx("span",{className:"top-bar-title",children:"Kitchen"}),s.jsxs("nav",{className:"top-bar-nav",children:[s.jsx(wx,{to:"/dashboard",className:({isActive:e})=>e?"active":"",children:"Dashboard"}),Ma(n,"invoices")&&s.jsx(wx,{to:"/invoices",className:({isActive:e})=>e?"active":"",children:"Invoices"}),Ma(n,"view")&&s.jsx(wx,{to:"/gp",className:({isActive:e})=>e?"active":"",children:"Reports"}),Ma(n,"recipes")&&s.jsx(wx,{to:"/recipes",className:({isActive:e})=>e?"active":"",children:"Recipes"}),Ma(n,"settings")&&s.jsx(wx,{to:"/settings",className:({isActive:e})=>e?"active":"",children:"Settings"})]})]}),s.jsx("main",{className:"page-content",children:s.jsx(nZ,{})})]})}function DJ(){const{token:n}=gn(),e=pi(),[t,r]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(""),[d,c]=k.useState([]),[u,f]=k.useState(""),[p,g]=k.useState(!1),[m,y]=k.useState(""),[v,x]=k.useState(""),[w,S]=k.useState(null),{data:_,isLoading:b}=Oe({queryKey:["suppliers"],queryFn:async()=>{const I=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!I.ok)throw new Error("Failed to fetch suppliers");return I.json()}}),C=Ue({mutationFn:async({name:I,aliases:H,skip_dext:z,order_email:G,account_number:te})=>{const re=await fetch("/api/suppliers/",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:I,aliases:H,skip_dext:z,order_email:G||null,account_number:te||null})});if(!re.ok)throw new Error("Failed to create supplier");return re.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["suppliers"]}),r(!1),l(""),c([]),f(""),g(!1),y(""),x("")}}),T=Ue({mutationFn:async({id:I,name:H,aliases:z,skip_dext:G,order_email:te,account_number:re})=>{const me=await fetch(`/api/suppliers/${I}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:H,aliases:z,skip_dext:G,order_email:te||null,account_number:re||null})});if(!me.ok)throw new Error("Failed to update supplier");return me.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["suppliers"]}),o(null),l(""),c([]),f(""),g(!1),y(""),x("")}}),F=Ue({mutationFn:async I=>{const H=await fetch(`/api/suppliers/${I}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!H.ok)throw new Error("Failed to delete supplier");return H.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["suppliers"]}),S(null)}}),A=()=>{a.trim()&&C.mutate({name:a.trim(),aliases:d,skip_dext:p,order_email:m,account_number:v})},D=()=>{i&&a.trim()&&T.mutate({id:i.id,name:a.trim(),aliases:d,skip_dext:p,order_email:m,account_number:v})},P=I=>{o(I),l(I.name),c(I.aliases||[]),f(""),g(I.skip_dext||!1),y(I.order_email||""),x(I.account_number||"")},L=()=>{const I=u.trim();I&&!d.includes(I)&&(c([...d,I]),f(""))},W=I=>{c(d.filter(H=>H!==I))},O=I=>{I.key==="Enter"&&(I.preventDefault(),L())},U=()=>{r(!1),l(""),c([]),f(""),g(!1),y(""),x("")},M=()=>{o(null),l(""),c([]),f(""),g(!1),y(""),x("")};return b?s.jsx("div",{style:Pt.loading,children:"Loading suppliers..."}):s.jsxs("div",{children:[s.jsxs("div",{style:Pt.header,children:[s.jsx("h2",{style:Pt.title,children:"Suppliers"}),s.jsx("button",{onClick:()=>r(!0),style:Pt.addBtn,children:"+ Add Supplier"})]}),s.jsx("p",{style:Pt.hint,children:'Define your suppliers here. Add aliases for suppliers that appear with different names on invoices (e.g., "US Foods", "USF", "U.S. Foods Inc").'}),_&&_.length===0?s.jsxs("div",{style:Pt.empty,children:[s.jsx("p",{children:"No suppliers defined yet."}),s.jsx("p",{style:Pt.emptyHint,children:"Add your first supplier to start organizing invoices by vendor."})]}):s.jsx("div",{style:Pt.list,children:_==null?void 0:_.map(I=>s.jsxs("div",{style:Pt.card,children:[s.jsxs("div",{style:Pt.cardMain,children:[s.jsxs("span",{style:Pt.supplierName,children:[I.name,I.skip_dext&&s.jsx("span",{style:Pt.skipDextBadge,children:"Skip Dext"})]}),I.aliases&&I.aliases.length>0&&s.jsxs("div",{style:Pt.aliasesList,children:[s.jsx("span",{style:Pt.aliasesLabel,children:"Also known as: "}),I.aliases.map((H,z)=>s.jsxs("span",{style:Pt.aliasTag,children:[H,zP(I),style:Pt.editBtn,children:"Edit"}),s.jsx("button",{onClick:()=>S(I.id),style:Pt.deleteBtn,children:"Delete"})]})]},I.id))}),t&&s.jsx("div",{style:Pt.modalOverlay,onClick:U,children:s.jsxs("div",{style:Pt.modal,onClick:I=>I.stopPropagation(),children:[s.jsx("h3",{children:"Add Supplier"}),s.jsxs("label",{style:Pt.label,children:["Primary Name",s.jsx("input",{type:"text",value:a,onChange:I=>l(I.target.value),style:Pt.input,placeholder:"e.g., Sysco",autoFocus:!0})]}),s.jsxs("label",{style:Pt.label,children:["Aliases (alternative names on invoices)",s.jsxs("div",{style:Pt.aliasInputRow,children:[s.jsx("input",{type:"text",value:u,onChange:I=>f(I.target.value),onKeyDown:O,style:{...Pt.input,flex:1},placeholder:"e.g., SYSCO FOODS"}),s.jsx("button",{type:"button",onClick:L,style:Pt.addAliasBtn,children:"Add"})]}),d.length>0&&s.jsx("div",{style:Pt.aliasTagsContainer,children:d.map(I=>s.jsxs("span",{style:Pt.aliasTagEditable,children:[I,s.jsx("button",{type:"button",onClick:()=>W(I),style:Pt.removeAliasBtn,children:"x"})]},I))})]}),s.jsxs("label",{style:Pt.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:I=>g(I.target.checked),style:Pt.checkbox}),s.jsx("span",{children:"Don't Forward to Dext"}),s.jsx("span",{style:Pt.checkboxHint,children:"Invoices from this supplier won't be sent to Dext"})]}),s.jsxs("div",{style:Pt.poFieldsSection,children:[s.jsx("h4",{style:Pt.poFieldsTitle,children:"Purchase Order Details"}),s.jsxs("label",{style:Pt.label,children:["Order Email",s.jsx("input",{type:"email",value:m,onChange:I=>y(I.target.value),style:Pt.input,placeholder:"orders@supplier.com"})]}),s.jsxs("label",{style:Pt.label,children:["Account Number",s.jsx("input",{type:"text",value:v,onChange:I=>x(I.target.value),style:Pt.input,placeholder:"e.g., ACC-12345"})]})]}),s.jsxs("div",{style:Pt.modalActions,children:[s.jsx("button",{onClick:U,style:Pt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:A,style:Pt.saveBtn,disabled:!a.trim()||C.isPending,children:C.isPending?"Adding...":"Add Supplier"})]})]})}),i&&s.jsx("div",{style:Pt.modalOverlay,onClick:M,children:s.jsxs("div",{style:Pt.modal,onClick:I=>I.stopPropagation(),children:[s.jsx("h3",{children:"Edit Supplier"}),s.jsxs("label",{style:Pt.label,children:["Primary Name",s.jsx("input",{type:"text",value:a,onChange:I=>l(I.target.value),style:Pt.input,autoFocus:!0})]}),s.jsxs("label",{style:Pt.label,children:["Aliases (alternative names on invoices)",s.jsxs("div",{style:Pt.aliasInputRow,children:[s.jsx("input",{type:"text",value:u,onChange:I=>f(I.target.value),onKeyDown:O,style:{...Pt.input,flex:1},placeholder:"Add an alias..."}),s.jsx("button",{type:"button",onClick:L,style:Pt.addAliasBtn,children:"Add"})]}),d.length>0&&s.jsx("div",{style:Pt.aliasTagsContainer,children:d.map(I=>s.jsxs("span",{style:Pt.aliasTagEditable,children:[I,s.jsx("button",{type:"button",onClick:()=>W(I),style:Pt.removeAliasBtn,children:"x"})]},I))})]}),s.jsxs("label",{style:Pt.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:I=>g(I.target.checked),style:Pt.checkbox}),s.jsx("span",{children:"Don't Forward to Dext"}),s.jsx("span",{style:Pt.checkboxHint,children:"Invoices from this supplier won't be sent to Dext"})]}),s.jsxs("div",{style:Pt.poFieldsSection,children:[s.jsx("h4",{style:Pt.poFieldsTitle,children:"Purchase Order Details"}),s.jsxs("label",{style:Pt.label,children:["Order Email",s.jsx("input",{type:"email",value:m,onChange:I=>y(I.target.value),style:Pt.input,placeholder:"orders@supplier.com"})]}),s.jsxs("label",{style:Pt.label,children:["Account Number",s.jsx("input",{type:"text",value:v,onChange:I=>x(I.target.value),style:Pt.input,placeholder:"e.g., ACC-12345"})]})]}),s.jsxs("div",{style:Pt.modalActions,children:[s.jsx("button",{onClick:M,style:Pt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:D,style:Pt.saveBtn,disabled:!a.trim()||T.isPending,children:T.isPending?"Saving...":"Save Changes"})]})]})}),w&&s.jsx("div",{style:Pt.modalOverlay,onClick:()=>S(null),children:s.jsxs("div",{style:Pt.modal,onClick:I=>I.stopPropagation(),children:[s.jsx("h3",{children:"Delete Supplier?"}),s.jsx("p",{children:"Are you sure you want to delete this supplier?"}),s.jsx("p",{style:Pt.warningText,children:"Invoices linked to this supplier will have their supplier cleared."}),s.jsxs("div",{style:Pt.modalActions,children:[s.jsx("button",{onClick:()=>S(null),style:Pt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>F.mutate(w),style:Pt.confirmDeleteBtn,disabled:F.isPending,children:F.isPending?"Deleting...":"Delete"})]})]})})]})}const Pt={loading:{padding:"2rem",textAlign:"center",color:"#666"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},title:{color:"#1a1a2e",margin:0},addBtn:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontWeight:"bold",cursor:"pointer"},hint:{color:"#666",marginBottom:"1.5rem",background:"white",padding:"1rem",borderRadius:"8px"},empty:{background:"white",padding:"3rem",borderRadius:"12px",textAlign:"center",color:"#666"},emptyHint:{marginTop:"0.5rem",fontSize:"0.9rem",color:"#999"},list:{display:"flex",flexDirection:"column",gap:"0.75rem"},card:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",background:"white",padding:"1rem 1.5rem",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.05)"},cardMain:{display:"flex",flexDirection:"column",gap:"0.25rem",flex:1},supplierName:{fontWeight:"bold",fontSize:"1.1rem",color:"#1a1a2e"},aliasesList:{fontSize:"0.85rem",color:"#666",marginTop:"0.25rem"},aliasesLabel:{color:"#999"},aliasTag:{color:"#1a1a2e"},date:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},cardActions:{display:"flex",gap:"0.5rem",marginLeft:"1rem"},editBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},deleteBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #dc3545",color:"#dc3545",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"500px",width:"90%"},label:{display:"flex",flexDirection:"column",gap:"0.5rem",color:"#333",fontWeight:"500",marginTop:"1rem"},input:{padding:"0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"1rem"},aliasInputRow:{display:"flex",gap:"0.5rem"},addAliasBtn:{padding:"0.75rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},aliasTagsContainer:{display:"flex",flexWrap:"wrap",gap:"0.5rem",marginTop:"0.5rem"},aliasTagEditable:{display:"inline-flex",alignItems:"center",gap:"0.25rem",padding:"0.25rem 0.5rem",background:"#e9ecef",borderRadius:"4px",fontSize:"0.85rem"},removeAliasBtn:{background:"none",border:"none",color:"#999",cursor:"pointer",padding:"0 0.25rem",fontSize:"0.9rem",lineHeight:1},modalActions:{display:"flex",gap:"1rem",marginTop:"1.5rem"},cancelBtn:{flex:1,padding:"0.75rem",background:"#f0f0f0",border:"none",borderRadius:"6px",cursor:"pointer"},saveBtn:{flex:1,padding:"0.75rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},confirmDeleteBtn:{flex:1,padding:"0.75rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},warningText:{color:"#856404",background:"#fff3cd",padding:"0.75rem",borderRadius:"6px",fontSize:"0.9rem",marginTop:"0.5rem"},checkboxLabel:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0.5rem",marginTop:"1.25rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",cursor:"pointer"},checkbox:{width:"18px",height:"18px",cursor:"pointer"},checkboxHint:{width:"100%",fontSize:"0.8rem",color:"#666",marginLeft:"26px"},skipDextBadge:{display:"inline-block",fontSize:"0.7rem",padding:"0.2rem 0.5rem",background:"#28a745",color:"white",borderRadius:"4px",marginLeft:"0.5rem",fontWeight:"normal"},poDetails:{display:"flex",gap:"1.5rem",fontSize:"0.8rem",color:"#666",marginTop:"0.25rem"},poFieldsSection:{marginTop:"1.25rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},poFieldsTitle:{margin:"0 0 0.75rem 0",fontSize:"0.9rem",color:"#555",fontWeight:600}};function EJ(){const{user:n,token:e,logout:t,restrictedPages:r}=gn(),i=pi(),[o,a]=k.useState("account"),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState(null),[g,m]=k.useState(!1),[y,v]=k.useState(!1),[x,w]=k.useState(!1),[S,_]=k.useState(90),[b,C]=k.useState(""),[T,F]=k.useState("587"),[A,D]=k.useState(""),[P,L]=k.useState(""),[W,O]=k.useState(!0),[U,M]=k.useState(""),[I,H]=k.useState("Kitchen Invoice System"),[z,G]=k.useState(""),[te,re]=k.useState(null),[me,J]=k.useState(null),[ne,ye]=k.useState(""),[ke,Ye]=k.useState(!0),[De,qe]=k.useState(!0),[ue,Ze]=k.useState(!1),[ee,Z]=k.useState(!0),[ge,Te]=k.useState(!0),[Be,he]=k.useState(null),[He,Ge]=k.useState("£"),[ae,K]=k.useState("DD/MM/YYYY"),[de,Y]=k.useState(100),[Q,X]=k.useState(!0),[pe,we]=k.useState(!0),[Ne,st]=k.useState(null),[Ve,Re]=k.useState(""),[Le,rt]=k.useState(""),[$e,ce]=k.useState(""),[Je,jt]=k.useState(null),[ct,Se]=k.useState(null),[ot,ut]=k.useState(""),[Ot,An]=k.useState(""),[on,Ke]=k.useState(""),[Rt,vt]=k.useState("au"),[Cr,Qt]=k.useState(""),[Ci,Lr]=k.useState(""),[Gs,Ai]=k.useState(""),[Ks,un]=k.useState("10"),[Fr,zi]=k.useState("10"),[aa,Oi]=k.useState(null),[Vd,Gn]=k.useState(null),[Dr,xr]=k.useState(!1),[Ss,rs]=k.useState(!1),[Xs,Jt]=k.useState(!1),Ys=new Date;Ys.setDate(Ys.getDate()-1);const Ft=Ys.toISOString().split("T")[0],[Ea,zn]=k.useState(Ft),[gi,je]=k.useState(Ft),[bt,yn]=k.useState(""),[tn,ci]=k.useState(8),[hn,Ti]=k.useState(""),[js,Ar]=k.useState(""),[fs,Qs]=k.useState(null),[Lo,xn]=k.useState(null),[Pa,nn]=k.useState([]),[Zl,qu]=k.useState([]),[$s,Gd]=k.useState({}),[mo,Bc]=k.useState([]),[Kd,Zs]=k.useState(null),[Ra,Xd]=k.useState(!1),[No,Js]=k.useState([]),[Ba,Ic]=k.useState(!1),[al,ie]=k.useState(Ft),[nt,$]=k.useState(Ft),[ze,Qe]=k.useState(""),[pt,kt]=k.useState("1433"),[Ht,Gt]=k.useState(""),[Er,ar]=k.useState(""),[Kn,is]=k.useState(""),[On,sn]=k.useState(null),[ps,It]=k.useState(null),[Tn,Dt]=k.useState([]),[Ln,Fi]=k.useState(new Set),[Zr,ll]=k.useState(new Set),[Wo,Mc]=k.useState(new Set),[H0,Ia]=k.useState(null),[q0,A1]=k.useState(""),[V0,_e]=k.useState(""),[T1,G0]=k.useState(""),[Mf,Yt]=k.useState(""),[zc,Vu]=k.useState(5),[Li,ks]=k.useState([{name:"Starters",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20},{name:"Mains",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20},{name:"Desserts",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20}]),[ui,la]=k.useState(30),[F1,D1]=k.useState(60),[E1,P1]=k.useState(null),[Oc,Lc]=k.useState(null),[fC,Yd]=k.useState(""),[Ni,K0]=k.useState(""),[Gu,pC]=k.useState(""),[Jl,gC]=k.useState(""),[mC,yC]=k.useState(""),[X0,Y0]=k.useState(""),[xC,bC]=k.useState(""),[R1,B1]=k.useState(null),[I1,vC]=k.useState(""),[M1,z1]=k.useState(""),[wC,SC]=k.useState("65.00"),[jC,O1]=k.useState(4),[Q0,L1]=k.useState(null),[N1,W1]=k.useState(null),[kC,U1]=k.useState(""),[_C,CC]=k.useState(""),[$0,pD]=k.useState(""),[ed,AC]=k.useState("/Kitchen Invoices"),[H1,TC]=k.useState(!1),[Z0,J0]=k.useState(!1),[ex,q1]=k.useState(null),[V1,G1]=k.useState(null),[K1,X1]=k.useState(null),[Y1,Q1]=k.useState("manual"),[Ku,FC]=k.useState(7),[dl,DC]=k.useState("local"),[tx,qn]=k.useState("03:00"),[Qd,Nc]=k.useState("/Backups"),[Xu,$1]=k.useState(""),[Yu,Z1]=k.useState(""),[J1,ew]=k.useState(""),[nx,EC]=k.useState(""),[tw,B]=k.useState("/backups"),[oe,be]=k.useState(null),[Ae,it]=k.useState(null),[en,rn]=k.useState(30),[Nn,Qn]=k.useState(10),[gr,br]=k.useState(20),[mr,Wi]=k.useState(null),[er,lr]=k.useState(""),[Kt,Fn]=k.useState("993"),[Jr,ei]=k.useState(!0),[Ui,Uo]=k.useState(""),[da,zf]=k.useState(""),[nw,rw]=k.useState("INBOX"),[iw,sw]=k.useState(15),[ow,aw]=k.useState(!1),[rx,vr]=k.useState(50),[Gr,Ho]=k.useState(null),[Qu,Of]=k.useState(null),[lw,$u]=k.useState(null),[dw,Xg]=k.useState(null),[cw,uw]=k.useState(""),[Yg,ix]=k.useState("contains"),[Lf,hw]=k.useState(""),[PC,Zu]=k.useState("contains"),[Qg,fw]=k.useState(!1),[gD,Nf]=k.useState(null),[pw,X3]=k.useState(""),[Y3,Q3]=k.useState(""),[$3,Z3]=k.useState(""),[HK,mD]=k.useState(null),[RC,yD]=k.useState(""),[J3,xD]=k.useState(""),[e8,bD]=k.useState(""),[vD,Hi]=k.useState(null),[BC,t8]=k.useState(!1),[sx,wD]=k.useState(""),[qK,SD]=k.useState(null),[jD,gw]=k.useState(""),[VK,kD]=k.useState(null),[n8,r8]=k.useState(""),[i8,s8]=k.useState(0),[_D,CD]=k.useState(""),[o8,IC]=k.useState(0),[GK,AD]=k.useState(!1),[TD,yo]=k.useState(null),[FD,MC]=k.useState(null),[DD,zC]=k.useState(null),[a8,ED]=k.useState(!1),[$d,PD]=k.useState(null),[OC,l8]=k.useState(!1),[RD,Wf]=k.useState(null),[mw,d8]=k.useState(!1),[LC,c8]=k.useState(""),[BD,ID]=k.useState("claude-haiku-4-5-20251001"),[MD,u8]=k.useState(.8),[$g,h8]=k.useState(5e5),[f8,p8]=k.useState({label_parsing:!0,invoice_assist:!0,ingredient_match:!0,recipe_scanning:!0,line_item_reconciliation:!0,menu_description:!0,dispute_email:!0,duplicate_detection:!0,supplier_alias:!0,yield_estimation:!0}),[zD,OD]=k.useState(null),[LD,NC]=k.useState(null),{data:Lt,isLoading:KK}=Oe({queryKey:["settings"],queryFn:async()=>{const j=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch settings");return j.json()}}),{data:tr,error:g8,isLoading:XK}=Oe({queryKey:["newbook-settings"],queryFn:async()=>{const j=await fetch("/api/newbook/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const Pe=await j.text();throw console.error("Newbook settings fetch failed:",j.status,Pe),new Error(`Failed to fetch: ${j.status}`)}const V=await j.json();return console.log("[Newbook] GET settings response:",{upcoming_sync_enabled:V.newbook_upcoming_sync_enabled}),V},staleTime:0}),{data:Dn,error:YK,isLoading:QK}=Oe({queryKey:["resos-settings"],queryFn:async()=>{const j=await fetch("/api/resos/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const Pe=await j.text();throw console.error("Resos settings fetch failed:",j.status,Pe),new Error(`Failed to fetch: ${j.status}`)}return await j.json()},staleTime:0}),{data:Zd,refetch:ND}=Oe({queryKey:["gl-accounts"],queryFn:async()=>{const j=await fetch("/api/newbook/gl-accounts",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]}}),{data:cl,refetch:m8}=Oe({queryKey:["room-categories"],queryFn:async()=>{const j=await fetch("/api/newbook/room-categories",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]}}),{data:WD}=Oe({queryKey:["users"],queryFn:async()=>{const j=await fetch("/auth/users",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){if(j.status===403)return[];throw new Error("Failed to fetch users")}return j.json()},enabled:!!(n!=null&&n.is_admin)}),{data:$n}=Oe({queryKey:["sambapos-settings"],queryFn:async()=>{const j=await fetch("/api/sambapos/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch SambaPOS settings");return j.json()},enabled:!!e}),{data:Zg,refetch:y8,isLoading:$K,error:x8}=Oe({queryKey:["sambapos-categories"],queryFn:async()=>{const j=await fetch("/api/sambapos/categories",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch categories")}return j.json()},enabled:!!e&&!!($n!=null&&$n.sambapos_db_host)&&!!($n!=null&&$n.sambapos_db_password_set),retry:!1}),{data:UD,refetch:ZK,isLoading:JK}=Oe({queryKey:["sambapos-group-codes"],queryFn:async()=>{const j=await fetch("/api/sambapos/group-codes",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch group codes")}return j.json()},enabled:!!e&&!!($n!=null&&$n.sambapos_db_host)&&!!($n!=null&&$n.sambapos_db_password_set),retry:!1}),{data:WC,refetch:eX,isLoading:tX}=Oe({queryKey:["sambapos-gl-codes"],queryFn:async()=>{const j=await fetch("/api/sambapos/gl-codes",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch GL codes")}return j.json()},enabled:!!e&&!!($n!=null&&$n.sambapos_db_host)&&!!($n!=null&&$n.sambapos_db_password_set),retry:!1}),{data:UC}=Oe({queryKey:["sambapos-selected-gl-codes"],queryFn:async()=>{const j=await fetch("/api/sambapos/gl-codes/selected",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch selected GL codes");return j.json()},enabled:!!e}),{data:td}=Oe({queryKey:["kds-settings"],queryFn:async()=>{const j=await fetch("/api/kds/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch KDS settings");return j.json()},enabled:!!e}),{data:Ju}=Oe({queryKey:["kitchen-details"],queryFn:async()=>{const j=await fetch("/api/settings/kitchen-details",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch kitchen details");return j.json()},enabled:!!e}),{data:Jd}=Oe({queryKey:["budget-settings"],queryFn:async()=>{const j=await fetch("/api/budget/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch Budget settings");return j.json()},enabled:!!e}),{data:yw}=Oe({queryKey:["page-restrictions"],queryFn:async()=>{const j=await fetch("/api/settings/page-restrictions",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch page restrictions");return j.json()},enabled:!!e}),{data:ul}=Oe({queryKey:["nextcloud-settings"],queryFn:async()=>{const j=await fetch("/api/settings/nextcloud",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch Nextcloud settings");return j.json()},enabled:!!e}),{data:qo}=Oe({queryKey:["nextcloud-stats"],queryFn:async()=>{const j=await fetch("/api/settings/nextcloud/stats",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch Nextcloud stats");return j.json()},enabled:!!e}),{data:Nr}=Oe({queryKey:["backup-settings"],queryFn:async()=>{const j=await fetch("/api/backup/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch backup settings");return j.json()},enabled:!!e}),{data:HD}=Oe({queryKey:["backup-history"],queryFn:async()=>{const j=await fetch("/api/backup/history",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch backup history");return j.json()},enabled:!!e}),{data:xw}=Oe({queryKey:["search-settings"],queryFn:async()=>{const j=await fetch("/api/search/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch search settings");return j.json()},enabled:!!e}),{data:qi}=Oe({queryKey:["imap-settings"],queryFn:async()=>{const j=await fetch("/api/imap/settings",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch IMAP settings");return j.json()},enabled:!!e&&!!(n!=null&&n.is_admin)}),{data:qD}=Oe({queryKey:["imap-logs"],queryFn:async()=>{const j=await fetch("/api/imap/logs?limit=20",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch IMAP logs");return j.json()},enabled:!!e&&!!(n!=null&&n.is_admin)&&o==="inbox"}),{data:Wc}=Oe({queryKey:["imap-stats"],queryFn:async()=>{const j=await fetch("/api/imap/logs/stats",{headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to fetch IMAP stats");return j.json()},enabled:!!e&&!!(n!=null&&n.is_admin)&&o==="inbox"}),[eh,bw]=k.useState(new Set),[VD,GD]=k.useState(null);k.useEffect(()=>{yw!=null&&yw.restricted_pages&&bw(new Set(yw.restricted_pages))},[yw]),k.useEffect(()=>{Lt&&(d(Lt.azure_endpoint||""),Ge(Lt.currency_symbol),K(Lt.date_format),Y(Lt.high_quantity_threshold),C(Lt.smtp_host||""),F(String(Lt.smtp_port||587)),D(Lt.smtp_username||""),O(Lt.smtp_use_tls),M(Lt.smtp_from_email||""),H(Lt.smtp_from_name||"Kitchen Invoice System"),G(Lt.support_email||""),ye(Lt.dext_email||""),Ye(Lt.dext_include_notes),qe(Lt.dext_include_non_stock),Ze(Lt.dext_auto_send_enabled),Z(Lt.dext_manual_send_enabled),Te(Lt.dext_include_annotations),X(Lt.pdf_annotations_enabled),we(Lt.pdf_preview_show_annotations),m(Lt.ocr_clean_product_codes||!1),v(Lt.ocr_filter_subtotal_rows||!1),w(Lt.ocr_use_weight_as_quantity||!1),_(Lt.cost_distribution_max_days??90),d8(Lt.llm_enabled??!1),ID(Lt.llm_model||"claude-haiku-4-5-20251001"),u8(Lt.llm_confidence_threshold??.8),h8(Lt.llm_monthly_token_limit??5e5),Lt.llm_features_enabled&&p8(Lt.llm_features_enabled))},[Lt]),k.useEffect(()=>{ul&&(U1(ul.nextcloud_host||""),CC(ul.nextcloud_username||""),AC(ul.nextcloud_base_path||"/Kitchen Invoices"),TC(ul.nextcloud_enabled),J0(ul.nextcloud_delete_local))},[ul]),k.useEffect(()=>{Nr&&(Q1(Nr.backup_frequency||"manual"),FC(Nr.backup_retention_count||7),DC(Nr.backup_destination||"local"),qn(Nr.backup_time||"03:00"),Nc(Nr.backup_nextcloud_path||"/Backups"),$1(Nr.backup_smb_host||""),Z1(Nr.backup_smb_share||""),ew(Nr.backup_smb_username||""),B(Nr.backup_smb_path||"/backups"))},[Nr]),k.useEffect(()=>{xw&&(rn(xw.price_change_lookback_days||30),Qn(xw.price_change_amber_threshold||10),br(xw.price_change_red_threshold||20))},[xw]),k.useEffect(()=>{qi&&(lr(qi.imap_host||""),Fn(String(qi.imap_port||993)),ei(qi.imap_use_ssl),Uo(qi.imap_username||""),rw(qi.imap_folder||"INBOX"),sw(qi.imap_poll_interval||15),aw(qi.imap_enabled),vr((qi.imap_confidence_threshold||.5)*100))},[qi]),k.useEffect(()=>{tr&&(ut(tr.newbook_api_username||""),vt(tr.newbook_api_region||"au"),Qt(tr.newbook_instance_id||""),Lr(tr.newbook_breakfast_gl_codes||""),Ai(tr.newbook_dinner_gl_codes||""),un(tr.newbook_breakfast_vat_rate?String(parseFloat(tr.newbook_breakfast_vat_rate)*100):"10"),zi(tr.newbook_dinner_vat_rate?String(parseFloat(tr.newbook_dinner_vat_rate)*100):"10"))},[tr]),k.useEffect(()=>{$n&&(Qe($n.sambapos_db_host||""),kt(String($n.sambapos_db_port||1433)),Gt($n.sambapos_db_name||""),ar($n.sambapos_db_username||""),Dt($n.sambapos_tracked_categories||[]),Fi(new Set($n.sambapos_excluded_items||[])))},[$n]),k.useEffect(()=>{UC&&(ll(new Set(UC.food_codes||[])),Mc(new Set(UC.beverage_codes||[])))},[UC]),k.useEffect(()=>{if(td){A1(td.kds_graphql_url||""),_e(td.kds_graphql_username||""),Yt(td.kds_graphql_client_id||""),Vu(td.kds_poll_interval_seconds||6e3);const j=(td.kds_course_order||[]).map(V=>({name:V.name,prep_green:V.prep_green/60,prep_amber:V.prep_amber/60,prep_red:V.prep_red/60,away_green:V.away_green/60,away_amber:V.away_amber/60,away_red:V.away_red/60}));j.length>0&&ks(j),la(td.kds_show_completed_for_seconds||30),D1(td.kds_bookings_refresh_seconds||60)}},[td]),k.useEffect(()=>{Ju&&(Yd(Ju.kitchen_display_name||""),K0(Ju.kitchen_address_line1||""),pC(Ju.kitchen_address_line2||""),gC(Ju.kitchen_city||""),yC(Ju.kitchen_postcode||""),Y0(Ju.kitchen_phone||""),bC(Ju.kitchen_email||""))},[Ju]),k.useEffect(()=>{Jd&&(vC(Jd.forecast_api_url||""),SC(String(Jd.budget_gp_target||65)),O1(Jd.budget_lookback_weeks||4))},[Jd]),k.useEffect(()=>{if(Dn){ci(Dn.resos_large_group_threshold||8),Ti(Dn.resos_note_keywords||""),Ar(Dn.resos_allergy_keywords||""),Gd(Dn.resos_custom_field_mapping||{}),Zs(Dn.resos_arrival_widget_service_filter||null),Xd(Dn.resos_enable_manual_breakfast||!1),Js(Dn.resos_manual_breakfast_periods||[]);const j=(Dn.resos_opening_hours_mapping||[]).map(V=>({resos_id:V.resos_id,display_name:V.display_name,actual_end:V.actual_end,service_type:V.service_type||""}));Bc(j),Dn.resos_custom_field_mapping&&Object.keys(Dn.resos_custom_field_mapping).length>0&&Pa.length===0&&fetch("/api/resos/custom-fields",{headers:{Authorization:`Bearer ${e}`}}).then(V=>V.json()).then(V=>nn(V.custom_fields||[])).catch(V=>console.error("Failed to auto-fetch custom fields:",V)),Dn.resos_opening_hours_mapping&&Dn.resos_opening_hours_mapping.length>0&&Zl.length===0&&fetch("/api/resos/opening-hours",{headers:{Authorization:`Bearer ${e}`}}).then(V=>V.json()).then(V=>qu(V.opening_hours||[])).catch(V=>console.error("Failed to auto-fetch opening hours:",V))}},[Dn]);const{data:b8,refetch:ox}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const j=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]}}),{data:HC}=Oe({queryKey:["api-access-settings"],queryFn:async()=>{const j=await fetch("/api/settings/api-access",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():{api_key:null,api_key_enabled:!1}}});k.useEffect(()=>{HC&&(ED(HC.api_key_enabled),PD(HC.api_key))},[HC]);const KD=Ue({mutationFn:async j=>{const V=await fetch("/api/food-flags/categories",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to create category");return V.json()},onSuccess:()=>{ox(),hw(""),Zu("contains"),fw(!1),Hi("Category created"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error creating category")}),XD=Ue({mutationFn:async({id:j,data:V})=>{const Pe=await fetch(`/api/food-flags/categories/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Pe.ok)throw new Error("Failed to update category");return Pe.json()},onSuccess:()=>{ox(),Xg(null),Hi("Category updated"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error updating category")}),nX=Ue({mutationFn:async j=>{const V=await fetch(`/api/food-flags/categories/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok)throw new Error("Failed to delete category");return V.json()},onSuccess:()=>{ox(),Hi("Category deleted"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error deleting category")}),v8=Ue({mutationFn:async j=>{const V=await fetch("/api/food-flags/flags",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to create flag");return V.json()},onSuccess:()=>{ox(),mD(null),yD(""),xD(""),bD(""),Hi("Flag created"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error creating flag")}),w8=Ue({mutationFn:async({id:j,data:V})=>{const Pe=await fetch(`/api/food-flags/flags/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Pe.ok)throw new Error("Failed to update flag");return Pe.json()},onSuccess:()=>{ox(),Nf(null),Hi("Flag updated"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error updating flag")}),rX=Ue({mutationFn:async j=>{const V=await fetch(`/api/food-flags/flags/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok)throw new Error("Failed to delete flag");return V.json()},onSuccess:()=>{ox(),Hi("Flag deleted"),setTimeout(()=>Hi(null),3e3)},onError:()=>Hi("Error deleting flag")}),{data:YD,refetch:QD}=Oe({queryKey:["allergen-keywords"],queryFn:async()=>{const j=await fetch("/api/food-flags/keywords",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="allergen_keywords"}),$D=Ue({mutationFn:async({food_flag_id:j,keyword:V})=>{const Pe=await fetch("/api/food-flags/keywords",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_id:j,keyword:V})});if(!Pe.ok){const St=await Pe.json().catch(()=>({}));throw new Error(St.detail||"Failed to add keyword")}return Pe.json()},onSuccess:()=>{QD(),wD(""),SD(null),gw("Keyword added"),setTimeout(()=>gw(""),2e3)},onError:j=>{gw(`Error: ${j.message}`)}}),iX=Ue({mutationFn:async j=>{if(!(await fetch(`/api/food-flags/keywords/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})).ok)throw new Error("Failed to delete keyword")},onSuccess:()=>{QD()}}),ZD=Ue({mutationFn:async()=>{if(!(await fetch("/api/food-flags/keywords/reset-defaults",{method:"POST",headers:{Authorization:`Bearer ${e}`}})).ok)throw new Error("Failed to reset keywords")},onSuccess:()=>{QD(),gw("Default keywords restored (custom keywords preserved)"),setTimeout(()=>gw(""),3e3)}}),{data:Ps,refetch:qC}=Oe({queryKey:["ingredient-categories-settings"],queryFn:async()=>{const j=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="ingredient_categories"}),JD=Ue({mutationFn:async j=>{const V=await fetch("/api/ingredients/categories",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json().catch(()=>null);throw new Error((Pe==null?void 0:Pe.detail)||"Failed to create category")}return V.json()},onSuccess:()=>{qC(),CD(""),IC((Ps==null?void 0:Ps.length)||0),AD(!1),yo("Category created"),setTimeout(()=>yo(null),3e3)},onError:j=>{yo(`Error: ${j.message}`),setTimeout(()=>yo(null),5e3)}}),VC=Ue({mutationFn:async({id:j,data:V})=>{const Pe=await fetch(`/api/ingredients/categories/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(V)});if(!Pe.ok){const St=await Pe.json().catch(()=>null);throw new Error((St==null?void 0:St.detail)||"Failed to update category")}return Pe.json()},onSuccess:()=>{qC(),kD(null),yo("Category updated"),setTimeout(()=>yo(null),3e3)},onError:j=>{yo(`Error: ${j.message}`),setTimeout(()=>yo(null),5e3)}}),sX=Ue({mutationFn:async j=>{const V=await fetch(`/api/ingredients/categories/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok)throw new Error("Failed to delete category");return V.json()},onSuccess:()=>{qC(),yo("Category deleted"),setTimeout(()=>yo(null),3e3)},onError:()=>{yo("Error deleting category"),setTimeout(()=>yo(null),5e3)}}),S8=(j,V)=>{if(!Ps)return;const Pe=Ps.findIndex(xo=>xo.id===j);if(Pe<0)return;const St=V==="up"?Pe-1:Pe+1;if(St<0||St>=Ps.length)return;const yr=Ps[Pe].sort_order,dr=Ps[St].sort_order;VC.mutate({id:Ps[Pe].id,data:{sort_order:dr}}),VC.mutate({id:Ps[St].id,data:{sort_order:yr}})},{data:th,refetch:GC}=Oe({queryKey:["recipe-sections-settings"],queryFn:async()=>{const j=await fetch("/api/recipes/menu-sections?section_type=recipe",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="recipe_sections"}),{data:nh,refetch:KC}=Oe({queryKey:["dish-courses-settings"],queryFn:async()=>{const j=await fetch("/api/recipes/menu-sections?section_type=dish",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():[]},enabled:!!e&&o==="dish_courses"}),oX=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/api-access",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save API access settings");return V.json()},onSuccess:j=>{j.api_key&&PD(j.api_key),ED(j.api_key_enabled),Wf("Settings saved"),setTimeout(()=>Wf(null),3e3)},onError:()=>Wf("Error saving settings")}),XC=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/api-access/regenerate",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok)throw new Error("Failed to regenerate API key");return j.json()},onSuccess:j=>{PD(j.api_key),l8(!0),Wf("API key regenerated. Copy it now - it will be masked next time you visit."),setTimeout(()=>Wf(null),8e3)},onError:()=>Wf("Error regenerating API key")}),{data:ec,refetch:aX}=Oe({queryKey:["llm-usage"],queryFn:async()=>{const j=await fetch("/api/settings/llm-usage",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():{total_calls:0,successful_calls:0,failed_calls:0,total_input_tokens:0,total_output_tokens:0,total_tokens:0,estimated_cost_usd:0,cache_entries_this_month:0}},enabled:!!(Lt!=null&&Lt.llm_enabled)}),{data:Uf,isLoading:lX,refetch:dX,isFetching:j8}=Oe({queryKey:["llm-models"],queryFn:async()=>{const j=await fetch("/api/settings/llm-models",{headers:{Authorization:`Bearer ${e}`}});return j.ok?j.json():{models:[],default:"claude-haiku-4-5-20251001",current:"claude-haiku-4-5-20251001"}},enabled:!!(Lt!=null&&Lt.llm_enabled)&&!!(Lt!=null&&Lt.anthropic_api_key_set),staleTime:3e5}),eE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save LLM settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["settings"]}),c8(""),OD("AI settings saved successfully"),setTimeout(()=>OD(null),3e3)},onError:j=>OD(`Error: ${j.message}`)}),tE=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/test-llm",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{NC(j.message||"Connection successful"),setTimeout(()=>NC(null),5e3)},onError:j=>{NC(`Error: ${j.message}`),setTimeout(()=>NC(null),8e3)}}),cX=()=>{const j={llm_enabled:mw,llm_model:BD,llm_confidence_threshold:MD,llm_monthly_token_limit:$g,llm_features_enabled:f8};LC&&(j.anthropic_api_key=LC),eE.mutate(j)},Jg=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to update settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["settings"]}),st("Settings saved successfully"),u(""),setTimeout(()=>st(null),3e3)},onError:j=>{st(`Error: ${j.message}`)}}),uX=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/test-azure",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{p(j.message),setTimeout(()=>p(null),5e3)},onError:j=>{p(`Error: ${j.message}`)}}),nE=Ue({mutationFn:async j=>{const V=await fetch("/auth/change-password",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to change password")}return V.json()},onSuccess:()=>{jt("Password changed successfully"),Re(""),rt(""),ce(""),setTimeout(()=>jt(null),5e3)},onError:j=>{jt(`Error: ${j.message}`)}}),hX=Ue({mutationFn:async j=>{const V=await fetch(`/auth/users/${j}/toggle-active`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to toggle user")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["users"]})}}),fX=Ue({mutationFn:async j=>{const V=await fetch(`/auth/users/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to delete user")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["users"]})}}),pX=Ue({mutationFn:async j=>{const V=await fetch(`/auth/users/${j}/toggle-admin`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to toggle admin status")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["users"]})}}),rE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/page-restrictions",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({restricted_pages:j})});if(!V.ok)throw new Error("Failed to save page restrictions");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["page-restrictions"]}),GD("Page restrictions saved successfully"),setTimeout(()=>GD(null),3e3)},onError:j=>{GD(`Error: ${j.message}`)}}),iE=Ue({mutationFn:async()=>{const j=await fetch("/api/invoices/reprocess-all",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to reprocess invoices")}return j.json()},onSuccess:j=>{Se(j.message),i.invalidateQueries({queryKey:["invoices"]}),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),sE=Ue({mutationFn:async()=>{const j=await fetch("/api/recipes/cleanup-false-price-changes",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to cleanup")}return j.json()},onSuccess:j=>{Se(j.message),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),oE=Ue({mutationFn:async()=>{const j=await fetch("/api/recipes/backfill-invoice-references",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to backfill")}return j.json()},onSuccess:j=>{Se(j.message),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),aE=Ue({mutationFn:async()=>{const j=await fetch("/api/suppliers/rematch-fuzzy",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to rematch invoices")}return j.json()},onSuccess:j=>{Se(j.message),i.invalidateQueries({queryKey:["invoices"]}),setTimeout(()=>Se(null),5e3)},onError:j=>{Se(`Error: ${j.message}`)}}),rh=Ue({mutationFn:async j=>{console.log("[Newbook] Sending PATCH with data:",j);const V=await fetch("/api/newbook/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const St=await V.text();throw console.error("[Newbook] PATCH failed:",V.status,St),new Error("Failed to update Newbook settings")}const Pe=await V.json();return console.log("[Newbook] PATCH response:",Pe),Pe},onSuccess:j=>{console.log("[Newbook] Mutation success, response data:",j),i.invalidateQueries({queryKey:["newbook-settings"]}),Gn("Newbook settings saved"),An(""),Ke(""),setTimeout(()=>Gn(null),3e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),k8=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/test-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{Oi(j.message),setTimeout(()=>Oi(null),5e3)},onError:j=>{Oi(`Error: ${j.message}`)}}),lE=Ue({mutationFn:async j=>{console.log("[Resos] Sending PATCH with data:",j);const V=await fetch("/api/resos/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const St=await V.text();throw console.error("[Resos] PATCH failed:",V.status,St),new Error("Failed to update Resos settings")}const Pe=await V.json();return console.log("[Resos] PATCH response:",Pe),Pe},onSuccess:()=>{i.invalidateQueries({queryKey:["resos-settings"]}),xn("✓ Sync settings saved"),setTimeout(()=>xn(null),3e3)},onError:j=>{xn(`✗ Error: ${j.message}`),setTimeout(()=>xn(null),5e3)}}),dE=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/gl-accounts/fetch",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch GL accounts")}return j.json()},onSuccess:()=>{ND(),Gn("GL accounts fetched successfully"),setTimeout(()=>Gn(null),3e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),cE=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/sync/forecast",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Sync failed")}return j.json()},onSuccess:j=>{Gn(`Forecast sync complete: ${JSON.stringify(j.results)}`),i.invalidateQueries({queryKey:["newbook-settings"]}),setTimeout(()=>Gn(null),5e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),uE=Ue({mutationFn:async j=>{const V=await fetch("/api/newbook/sync/historical",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Sync failed")}return V.json()},onSuccess:j=>{Gn(`Historical sync complete: ${JSON.stringify(j.results)}`),Jt(!1),i.invalidateQueries({queryKey:["newbook-settings"]}),setTimeout(()=>Gn(null),5e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),gX=Ue({mutationFn:async({id:j,is_tracked:V})=>{const Pe=await fetch(`/api/newbook/gl-accounts/${j}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({is_tracked:V})});if(!Pe.ok)throw new Error("Failed to update GL account");return Pe.json()},onSuccess:()=>{ND()}}),mX=Ue({mutationFn:async j=>{const V=await fetch("/api/newbook/gl-accounts/bulk-update",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({updates:j})});if(!V.ok)throw new Error("Failed to update GL accounts");return V.json()},onSuccess:()=>{ND()}}),hE=Ue({mutationFn:async()=>{const j=await fetch("/api/newbook/room-categories/fetch",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Failed to fetch room categories")}return j.json()},onSuccess:()=>{m8(),Gn("Room categories fetched successfully"),setTimeout(()=>Gn(null),3e3)},onError:j=>{Gn(`Error: ${j.message}`)}}),fE=Ue({mutationFn:async j=>{const V=await fetch("/api/newbook/room-categories/bulk-update",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({updates:j})});if(!V.ok)throw new Error("Failed to update room categories");return V.json()},onSuccess:()=>{m8()}}),pE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save SambaPOS settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-settings"]}),It("Settings saved successfully"),is(""),setTimeout(()=>It(null),3e3)},onError:j=>{It(`Error: ${j.message}`)}}),gE=Ue({mutationFn:async()=>{const j=await fetch("/api/sambapos/test-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:j=>{sn(j.message),y8(),setTimeout(()=>sn(null),5e3)},onError:j=>{sn(`Error: ${j.message}`)}}),mE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/tracked-categories",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({categories:j})});if(!V.ok)throw new Error("Failed to save courses");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-settings"]}),It("Courses saved successfully"),setTimeout(()=>It(null),3e3)},onError:j=>{It(`Error: ${j.message}`)}}),yE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/excluded-items",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({items:j})});if(!V.ok)throw new Error("Failed to save excluded categories");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-settings"]}),It("Excluded categories saved successfully"),setTimeout(()=>It(null),3e3)},onError:j=>{It(`Error: ${j.message}`)}}),xE=Ue({mutationFn:async j=>{const V=await fetch("/api/sambapos/gl-codes",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save GL codes");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["sambapos-selected-gl-codes"]}),Ia("GL codes saved successfully"),setTimeout(()=>Ia(null),3e3)},onError:j=>{Ia(`Error: ${j.message}`)}}),ax=Ue({mutationFn:async j=>{const V=await fetch("/api/kds/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok)throw new Error("Failed to save KDS settings");return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["kds-settings"]}),Lc("Settings saved successfully"),G0(""),setTimeout(()=>Lc(null),3e3)},onError:j=>{Lc(`Error: ${j.message}`)}}),bE=Ue({mutationFn:async()=>{const V=await(await fetch("/api/kds/test-connection",{headers:{Authorization:`Bearer ${e}`}})).json();if(!V.success)throw new Error(V.error||"Connection test failed");return V},onSuccess:j=>{P1(j.message),setTimeout(()=>P1(null),5e3)},onError:j=>{P1(`Error: ${j.message}`)}}),vE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/kitchen-details",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save kitchen details")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["kitchen-details"]}),B1("Kitchen details saved successfully"),setTimeout(()=>B1(null),3e3)},onError:j=>{B1(`Error: ${j.message}`)}}),wE=Ue({mutationFn:async j=>{const V=await fetch("/api/budget/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save Budget settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["budget-settings"]}),W1("Budget settings saved successfully"),z1(""),setTimeout(()=>W1(null),3e3)},onError:j=>{W1(`Error: ${j.message}`)}}),SE=Ue({mutationFn:async()=>{const V=await(await fetch("/api/budget/test-forecast-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}})).json();if(!V.success)throw new Error(V.message||"Connection test failed");return V},onSuccess:j=>{L1(j.message),setTimeout(()=>L1(null),5e3)},onError:j=>{L1(`Error: ${j.message}`)}}),jE=Ue({mutationFn:async j=>{const V=await fetch("/api/settings/nextcloud",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save Nextcloud settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["nextcloud-settings"]}),i.invalidateQueries({queryKey:["nextcloud-stats"]}),G1("Nextcloud settings saved successfully"),setTimeout(()=>G1(null),3e3)},onError:j=>{G1(`Error: ${j.message}`)}}),kE=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/nextcloud/test",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Connection test failed")}return j.json()},onSuccess:()=>{q1("Connection successful"),setTimeout(()=>q1(null),5e3)},onError:j=>{q1(`Error: ${j.message}`)}}),_E=Ue({mutationFn:async()=>{const j=await fetch("/api/settings/nextcloud/archive-all",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Archive failed")}return j.json()},onSuccess:j=>{i.invalidateQueries({queryKey:["nextcloud-stats"]}),X1(`Archived ${j.success_count} invoices${j.failed_count>0?`, ${j.failed_count} failed`:""}`),setTimeout(()=>X1(null),5e3)},onError:j=>{X1(`Error: ${j.message}`)}}),CE=Ue({mutationFn:async j=>{const V=await fetch("/api/backup/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save backup settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["backup-settings"]}),be("Backup settings saved successfully"),setTimeout(()=>be(null),3e3)},onError:j=>{be(`Error: ${j.message}`)}}),AE=Ue({mutationFn:async()=>{const j=await fetch("/api/backup/create",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){const V=await j.json();throw new Error(V.detail||"Backup creation failed")}return j.json()},onSuccess:j=>{i.invalidateQueries({queryKey:["backup-history"]}),i.invalidateQueries({queryKey:["backup-settings"]}),it(j.message),setTimeout(()=>it(null),5e3)},onError:j=>{it(`Error: ${j.message}`)}}),_8=Ue({mutationFn:async j=>{const V=await fetch(`/api/backup/${j}/restore`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Restore failed")}return V.json()},onSuccess:j=>{it(j.message),setTimeout(()=>it(null),5e3),i.invalidateQueries()},onError:j=>{it(`Error: ${j.message}`)}}),C8=Ue({mutationFn:async j=>{const V=await fetch(`/api/backup/${j}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Delete failed")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["backup-history"]}),it("Backup deleted"),setTimeout(()=>it(null),3e3)},onError:j=>{it(`Error: ${j.message}`)}}),YC=Ue({mutationFn:async j=>{const V=new FormData;V.append("file",j);const Pe=await fetch("/api/backup/upload",{method:"POST",headers:{Authorization:`Bearer ${e}`},body:V});if(!Pe.ok){const St=await Pe.json();throw new Error(St.detail||"Upload failed")}return Pe.json()},onSuccess:j=>{i.invalidateQueries({queryKey:["backup-history"]}),it(j.message),setTimeout(()=>it(null),5e3)},onError:j=>{it(`Error: ${j.message}`)}}),TE=Ue({mutationFn:async j=>{const V=await fetch("/api/search/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(j)});if(!V.ok){const Pe=await V.json();throw new Error(Pe.detail||"Failed to save search settings")}return V.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["search-settings"]}),Wi("Search settings saved successfully"),setTimeout(()=>Wi(null),3e3)},onError:j=>{Wi(`Error: ${j.message}`)}}),yX=()=>{if(!Ve||!Le||!$e){jt("Error: Please fill in all password fields");return}if(Le!==$e){jt("Error: New passwords do not match");return}if(Le.length<6){jt("Error: Password must be at least 6 characters");return}nE.mutate({current_password:Ve,new_password:Le})},A8=()=>{const j={azure_endpoint:l,currency_symbol:He,date_format:ae,high_quantity_threshold:de,pdf_annotations_enabled:Q,pdf_preview_show_annotations:pe,ocr_clean_product_codes:g,ocr_filter_subtotal_rows:y,ocr_use_weight_as_quantity:x,cost_distribution_max_days:S};c&&(j.azure_key=c),Jg.mutate(j)},xX=()=>{const j={newbook_api_username:ot,newbook_api_region:Rt,newbook_instance_id:Cr};Ot&&(j.newbook_api_password=Ot),on&&(j.newbook_api_key=on),rh.mutate(j)},bX=()=>{const j={sambapos_db_host:ze,sambapos_db_port:parseInt(pt)||1433,sambapos_db_name:Ht,sambapos_db_username:Er};Kn&&(j.sambapos_db_password=Kn),pE.mutate(j)},T8=j=>{Tn.includes(j)?Dt(Tn.filter(V=>V!==j)):Dt([...Tn,j])},vX=j=>{if(j<=0)return;const V=[...Tn];[V[j-1],V[j]]=[V[j],V[j-1]],Dt(V)},wX=j=>{if(j>=Tn.length-1)return;const V=[...Tn];[V[j],V[j+1]]=[V[j+1],V[j]],Dt(V)},SX=()=>{mE.mutate(Tn)},jX=j=>{const V=new Set(Ln);V.has(j)?V.delete(j):V.add(j),Fi(V)},kX=()=>{yE.mutate(Array.from(Ln))},_X=j=>{const V=new Set(Zr);if(V.has(j))V.delete(j);else if(V.add(j),Wo.has(j)){const Pe=new Set(Wo);Pe.delete(j),Mc(Pe)}ll(V)},CX=j=>{const V=new Set(Wo);if(V.has(j))V.delete(j);else if(V.add(j),Zr.has(j)){const Pe=new Set(Zr);Pe.delete(j),ll(Pe)}Mc(V)},AX=()=>{xE.mutate({food_codes:Array.from(Zr),beverage_codes:Array.from(Wo)})},FE=($n==null?void 0:$n.sambapos_db_host)&&($n==null?void 0:$n.sambapos_db_password_set),TX=()=>{const j={kds_graphql_url:q0,kds_graphql_username:V0,kds_graphql_client_id:Mf};T1&&(j.kds_graphql_password=T1),ax.mutate(j)},FX=()=>{const j=Li.map(V=>({name:V.name,prep_green:Math.round(V.prep_green*60),prep_amber:Math.round(V.prep_amber*60),prep_red:Math.round(V.prep_red*60),away_green:Math.round(V.away_green*60),away_amber:Math.round(V.away_amber*60),away_red:Math.round(V.away_red*60)}));ax.mutate({kds_poll_interval_seconds:zc,kds_course_order:j,kds_show_completed_for_seconds:ui,kds_bookings_refresh_seconds:F1})},DX=()=>{vE.mutate({kitchen_display_name:fC||null,kitchen_address_line1:Ni||null,kitchen_address_line2:Gu||null,kitchen_city:Jl||null,kitchen_postcode:mC||null,kitchen_phone:X0||null,kitchen_email:xC||null})},EX=()=>{const j={forecast_api_url:I1||null,budget_gp_target:parseFloat(wC)||65,budget_lookback_weeks:jC};M1&&(j.forecast_api_key=M1),wE.mutate(j)},em=(j,V,Pe)=>{ks(St=>St.map((yr,dr)=>dr===j?{...yr,[V]:Pe}:yr))},F8=(j,V)=>{const Pe=j+V;Pe<0||Pe>=Li.length||ks(St=>{const yr=[...St];return[yr[j],yr[Pe]]=[yr[Pe],yr[j]],yr})},PX=j=>{ks(V=>V.filter((Pe,St)=>St!==j))},RX=()=>{ks(j=>[...j,{name:"",prep_green:5,prep_amber:10,prep_red:15,away_green:10,away_amber:15,away_red:20}])};if(KK)return s.jsx("div",{style:E.loading,children:"Loading settings..."});const BX=j=>!j||n!=null&&n.is_admin?!0:!r.includes(j),IX=[{id:"account",label:"Account"},{id:"users",label:"Users",adminOnly:!0,restrictPath:"/settings-users"},{id:"access",label:"Access Control",adminOnly:!0,restrictPath:"/settings-access"},{id:"display",label:"Display",restrictPath:"/settings-display"},{id:"azure",label:"Azure OCR",restrictPath:"/settings-azure"},{id:"email",label:"Email Configuration",restrictPath:"/settings-email"},{id:"inbox",label:"Email Inbox",adminOnly:!0,restrictPath:"/settings-inbox"},{id:"dext",label:"Dext Integration",restrictPath:"/settings-dext"},{id:"newbook",label:"Newbook PMS",restrictPath:"/settings-newbook"},{id:"resos",label:"Resos Bookings",restrictPath:"/settings-resos"},{id:"sambapos",label:"SambaPOS EPOS",restrictPath:"/settings-sambapos"},{id:"kds",label:"Kitchen Display",restrictPath:"/settings-kds"},{id:"budget",label:"Spend Budget",restrictPath:"/settings-budget"},{id:"kitchen",label:"Kitchen Details",restrictPath:"/settings-kitchen"},{id:"suppliers",label:"Suppliers",restrictPath:"/settings-suppliers"},{id:"search",label:"Search & Pricing",restrictPath:"/settings-search"},{id:"nextcloud",label:"Nextcloud Storage",restrictPath:"/settings-nextcloud"},{id:"backup",label:"Backup & Restore",restrictPath:"/settings-backup"},{id:"food_flags",label:"Food Flags",restrictPath:"/settings-food-flags"},{id:"allergen_keywords",label:"Allergen Keywords",restrictPath:"/settings-food-flags"},{id:"ingredient_categories",label:"Ingredient Categories",restrictPath:"/settings-ingredient-categories"},{id:"recipe_sections",label:"Recipe Sections",restrictPath:"/settings-recipe-sections"},{id:"dish_courses",label:"Dish Courses",restrictPath:"/settings-dish-courses"},{id:"api_access",label:"API Access",restrictPath:"/settings-api-access"},{id:"llm",label:"AI Features",adminOnly:!0,restrictPath:"/settings-llm"},{id:"data",label:"Data Management",restrictPath:"/settings-data"}];return s.jsxs("div",{style:E.layout,children:[s.jsxs("div",{style:E.sidebar,children:[s.jsx("h3",{style:E.sidebarTitle,children:"Settings"}),s.jsx("nav",{style:E.nav,children:IX.map(j=>j.adminOnly&&!(n!=null&&n.is_admin)||!BX(j.restrictPath)?null:j.href?s.jsx("a",{href:j.href,style:E.navItem,children:j.label},j.id):s.jsx("button",{onClick:()=>a(j.id),style:{...E.navItem,...o===j.id?E.navItemActive:{}},children:j.label},j.id))}),s.jsx("button",{onClick:async()=>{var j;try{const V=await caches.keys();await Promise.all(V.map(St=>caches.delete(St)));const Pe=await((j=navigator.serviceWorker)==null?void 0:j.getRegistrations());Pe&&await Promise.all(Pe.map(St=>St.unregister()))}catch{}window.location.reload()},title:"Clear cached files and reload with fresh assets",style:{marginTop:"1rem",padding:"0.6rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"#f9fafb",cursor:"pointer",fontSize:"0.85rem",color:"#666",textAlign:"left",width:"100%"},children:"↻ Refresh App"})]}),s.jsxs("div",{style:E.content,children:[o==="account"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Account"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Account Information"}),s.jsxs("div",{style:E.infoGrid,children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Email:"})," ",n==null?void 0:n.email]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Name:"})," ",n==null?void 0:n.name]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Kitchen:"})," ",n==null?void 0:n.kitchen_name]}),(n==null?void 0:n.is_admin)&&s.jsxs("p",{children:[s.jsx("strong",{children:"Role:"})," Admin"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Change Password"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Current Password",s.jsx("input",{type:"password",value:Ve,onChange:j=>Re(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["New Password",s.jsx("input",{type:"password",value:Le,onChange:j=>rt(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Confirm New Password",s.jsx("input",{type:"password",value:$e,onChange:j=>ce(j.target.value),style:E.input})]})]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("button",{onClick:yX,style:E.btn,disabled:nE.isPending,children:nE.isPending?"Changing...":"Change Password"}),Je&&s.jsx("div",{style:{...E.statusMessage,background:Je.startsWith("Error")?"#fee":"#efe",marginTop:"0.5rem"},children:Je})]}),s.jsx("div",{children:s.jsx("button",{onClick:()=>{window.confirm("Are you sure you want to logout?")&&(t(),window.location.href="/login")},style:{background:"#e94560",color:"white",border:"none",padding:"0.75rem 1.5rem",borderRadius:"4px",cursor:"pointer",fontSize:"16px",fontWeight:"bold"},children:"Logout"})})]}),o==="users"&&(n==null?void 0:n.is_admin)&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"User Management"}),s.jsx("p",{style:E.hint,children:"Manage users who have access to this kitchen."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Users"}),WD&&WD.length>0&&s.jsxs("table",{style:E.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:E.th,children:"Email"}),s.jsx("th",{style:E.th,children:"Name"}),s.jsx("th",{style:E.th,children:"Status"}),s.jsx("th",{style:E.th,children:"Role"}),s.jsx("th",{style:E.th,children:"Actions"})]})}),s.jsx("tbody",{children:WD.map(j=>s.jsxs("tr",{style:j.is_active?void 0:E.disabledRow,children:[s.jsx("td",{style:E.td,children:j.email}),s.jsx("td",{style:E.td,children:j.name||"-"}),s.jsx("td",{style:E.td,children:s.jsx("span",{style:j.is_active?E.activeStatus:E.inactiveStatus,children:j.is_active?"Active":"Disabled"})}),s.jsx("td",{style:E.td,children:j.is_admin?"Admin":"User"}),s.jsx("td",{style:E.td,children:j.id!==n.id?s.jsxs("div",{style:E.actionButtons,children:[s.jsx("button",{onClick:()=>hX.mutate(j.id),style:j.is_active?E.disableBtn:E.enableBtn,children:j.is_active?"Disable":"Enable"}),s.jsx("button",{onClick:()=>{confirm(`${j.is_admin?"Remove admin rights from":"Make admin"} ${j.email}?`)&&pX.mutate(j.id)},style:j.is_admin?E.demoteBtn:E.promoteBtn,children:j.is_admin?"Demote":"Make Admin"}),!j.is_admin&&s.jsx("button",{onClick:()=>{confirm(`Delete user ${j.email}?`)&&fX.mutate(j.id)},style:E.deleteBtn,children:"Delete"})]}):s.jsx("span",{style:E.youLabel,children:"(You)"})})]},j.id))})]})]})]}),o==="access"&&(n==null?void 0:n.is_admin)&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Access Control"}),s.jsx("p",{style:E.hint,children:"Restrict pages to admin users only. Non-admin users will not see restricted pages in the navigation."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Invoice & Data"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/upload",label:"Upload Invoices"},{path:"/invoices",label:"Invoice List & Disputes"},{path:"/purchases",label:"Purchase Chart"},{path:"/logbook",label:"Allowance Logbook"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Reports"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/gp-report",label:"Kitchen Flash & Purchase Reports"},{path:"/newbook",label:"Newbook Data"},{path:"/resos",label:"Resos Bookings & Stats"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Search & Tools"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/search",label:"Search (Invoices, Line Items, Definitions)"},{path:"/kds",label:"Kitchen Display System (KDS)"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Settings Sections"}),s.jsx("div",{style:E.checkboxGroup,children:[{path:"/settings",label:"Settings Page (entire page)"},{path:"/settings-users",label:"Users Management"},{path:"/settings-access",label:"Access Control"},{path:"/settings-display",label:"Display Settings"},{path:"/settings-azure",label:"Azure OCR"},{path:"/settings-email",label:"Email Configuration"},{path:"/settings-inbox",label:"Email Inbox"},{path:"/settings-dext",label:"Dext Integration"},{path:"/settings-newbook",label:"Newbook PMS"},{path:"/settings-resos",label:"Resos Bookings"},{path:"/settings-sambapos",label:"SambaPOS EPOS"},{path:"/settings-kds",label:"Kitchen Display"},{path:"/settings-suppliers",label:"Suppliers"},{path:"/settings-search",label:"Search & Pricing"},{path:"/settings-nextcloud",label:"Nextcloud Storage"},{path:"/settings-backup",label:"Backup & Restore"},{path:"/settings-data",label:"Data Management"}].map(({path:j,label:V})=>s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:eh.has(j),onChange:()=>{const Pe=new Set(eh);Pe.has(j)?Pe.delete(j):Pe.add(j),bw(Pe)}}),V]},j))})]}),s.jsx("div",{style:{marginTop:"1.5rem"},children:s.jsx("button",{onClick:()=>rE.mutate(Array.from(eh)),style:E.saveBtn,disabled:rE.isPending,children:rE.isPending?"Saving...":"Save Restrictions"})}),VD&&s.jsx("div",{style:{...E.statusMessage,background:VD.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:VD}),s.jsxs("div",{style:{marginTop:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},children:[s.jsx("strong",{children:"Note:"})," Restricting a page will hide it from non-admin users. Admin users always have access to all pages. The Dashboard is always accessible to all users."]})]}),o==="display"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Display Settings"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Display Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Currency Symbol",s.jsxs("select",{value:He,onChange:j=>Ge(j.target.value),style:E.input,children:[s.jsx("option",{value:"£",children:"£ (GBP)"}),s.jsx("option",{value:"$",children:"$ (USD)"}),s.jsx("option",{value:"€",children:"€ (EUR)"})]})]}),s.jsxs("label",{style:E.label,children:["Date Format",s.jsxs("select",{value:ae,onChange:j=>K(j.target.value),style:E.input,children:[s.jsx("option",{value:"DD/MM/YYYY",children:"DD/MM/YYYY"}),s.jsx("option",{value:"MM/DD/YYYY",children:"MM/DD/YYYY"}),s.jsx("option",{value:"YYYY-MM-DD",children:"YYYY-MM-DD"})]})]}),s.jsxs("label",{style:E.label,children:["High Quantity Warning Threshold",s.jsx("input",{type:"number",min:"1",value:de,onChange:j=>Y(parseInt(j.target.value)||100),style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"Line items with quantity above this value will be highlighted amber"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"PDF Annotations"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:Q,onChange:j=>X(j.target.checked)}),"Enable PDF annotations",s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When enabled, the system will add visual annotations (highlights, labels) to PDFs"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:pe,onChange:j=>we(j.target.checked)}),"Show annotations in PDF preview",s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When enabled, annotations will be visible in the preview window on the review page"})]})]})]}),s.jsx("button",{onClick:A8,style:E.saveBtn,disabled:Jg.isPending,children:Jg.isPending?"Saving...":"Save Settings"}),Ne&&s.jsx("div",{style:{...E.statusMessage,background:Ne.startsWith("Error")?"#fee":"#efe"},children:Ne})]}),o==="azure"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Azure Document Intelligence"}),s.jsx("p",{style:E.hint,children:"Configure Azure credentials for invoice OCR processing."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Endpoint URL",s.jsx("input",{type:"text",value:l,onChange:j=>d(j.target.value),style:E.input,placeholder:"https://your-resource.cognitiveservices.azure.com/"})]}),s.jsxs("label",{style:E.label,children:["API Key",s.jsx("input",{type:"password",value:c,onChange:j=>u(j.target.value),style:E.input,placeholder:Lt!=null&&Lt.azure_key_set?"••••••••••••••••":"Enter your API key"}),(Lt==null?void 0:Lt.azure_key_set)&&!c&&s.jsx("span",{style:E.keyStatus,children:"Key is configured"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Post-Processing Options"}),s.jsx("p",{style:E.hint,children:"Optional cleanup of OCR results for common invoice quirks."}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:g,onChange:j=>m(j.target.checked),style:E.checkbox}),'Clean product codes (strip section headers like "CHILL/AMBIENT")']}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:y,onChange:j=>v(j.target.checked),style:E.checkbox}),'Filter subtotal rows (remove "Sub Total" lines from line items)']}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:x,onChange:j=>w(j.target.checked),style:E.checkbox}),"Use weight as quantity for KG items (when weight × price matches total)"]})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>uX.mutate(),style:E.testBtn,disabled:!(Lt!=null&&Lt.azure_key_set),children:"Test Connection"}),s.jsx("button",{onClick:A8,style:E.saveBtn,disabled:Jg.isPending,children:"Save"})]}),f&&s.jsx("div",{style:{...E.statusMessage,background:f.startsWith("Error")?"#fee":"#efe"},children:f})]}),o==="email"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Email Configuration (SMTP)"}),s.jsx("p",{style:E.hint,children:"Configure SMTP settings for sending emails."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"SMTP Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["SMTP Server",s.jsx("input",{type:"text",value:b,onChange:j=>C(j.target.value),style:E.input,placeholder:"smtp.gmail.com"})]}),s.jsxs("label",{style:E.label,children:["SMTP Port",s.jsx("input",{type:"number",value:T,onChange:j=>F(j.target.value),style:E.input,placeholder:"587"})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:A,onChange:j=>D(j.target.value),style:E.input,placeholder:"your-email@example.com"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:P,onChange:j=>L(j.target.value),style:E.input,placeholder:Lt!=null&&Lt.smtp_password_set?"••••••••••••••••":"Enter password"}),(Lt==null?void 0:Lt.smtp_password_set)&&!P&&s.jsx("span",{style:E.keyStatus,children:"Password is configured"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:W,onChange:j=>O(j.target.checked)}),"Use TLS/STARTTLS"]}),s.jsxs("label",{style:E.label,children:["From Email",s.jsx("input",{type:"email",value:U,onChange:j=>M(j.target.value),style:E.input,placeholder:"invoices@yourcompany.com"})]}),s.jsxs("label",{style:E.label,children:["From Name",s.jsx("input",{type:"text",value:I,onChange:j=>H(j.target.value),style:E.input,placeholder:"Kitchen Invoice System"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Support Request Settings"}),s.jsx("p",{style:E.hint,children:"Configure where user support requests (with screenshots) are sent."}),s.jsx("div",{style:E.form,children:s.jsxs("label",{style:E.label,children:["Support Email",s.jsx("input",{type:"email",value:z,onChange:j=>G(j.target.value),style:E.input,placeholder:"support@yourcompany.com"}),s.jsx("small",{style:{color:"#666",fontSize:"0.9em"},children:"Users can report issues with a screenshot using the ? button (visible when configured)"})]})})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:async()=>{re("Saving settings...");try{const j={smtp_host:b||null,smtp_port:parseInt(T)||587,smtp_username:A||null,smtp_password:P||void 0,smtp_use_tls:W,smtp_from_email:U||null,smtp_from_name:I||null,support_email:z||null};if(!(await fetch("/api/settings/",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(j)})).ok){re("Error: Failed to save settings");return}await i.invalidateQueries({queryKey:["settings"]}),re("Testing connection...");const Pe=await fetch("/api/settings/test-smtp",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(Pe.ok){const St=await Pe.json();re(`✓ ${St.message}`)}else{const St=await Pe.json();console.error("SMTP test error:",St),re(`Error: ${St.detail}`)}}catch(j){console.error("SMTP test exception:",j),re(`Error: ${j}`)}},style:E.testBtn,disabled:!b||!U,children:"Test Connection"}),s.jsx("button",{onClick:async()=>{try{(await fetch("/api/settings/",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({smtp_host:b||null,smtp_port:parseInt(T)||587,smtp_username:A||null,smtp_password:P||void 0,smtp_use_tls:W,smtp_from_email:U||null,smtp_from_name:I||null,support_email:z||null})})).ok?(J("✓ Saved successfully"),i.invalidateQueries({queryKey:["settings"]}),setTimeout(()=>J(null),3e3)):J("Error: Failed to save")}catch(j){J(`Error: ${j}`)}},style:E.saveBtn,children:"Save"})]}),te&&s.jsx("div",{style:{...E.statusMessage,background:te.startsWith("Error")?"#fee":"#efe"},children:te}),me&&s.jsx("div",{style:{...E.statusMessage,background:me.startsWith("Error")?"#fee":"#efe"},children:me})]}),o==="inbox"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Email Inbox (IMAP)"}),s.jsx("p",{style:E.hint,children:"Configure an email inbox to automatically process invoice attachments. Emails with confident invoice attachments will be marked as read."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"IMAP Connection"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["IMAP Server",s.jsx("input",{type:"text",value:er,onChange:j=>lr(j.target.value),style:E.input,placeholder:"imap.gmail.com"})]}),s.jsxs("label",{style:E.label,children:["Port",s.jsx("input",{type:"number",value:Kt,onChange:j=>Fn(j.target.value),style:E.input,placeholder:"993"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:Jr,onChange:j=>ei(j.target.checked)}),"Use SSL"]}),s.jsxs("label",{style:E.label,children:["Username / Email",s.jsx("input",{type:"text",value:Ui,onChange:j=>Uo(j.target.value),style:E.input,placeholder:"invoices@yourcompany.com"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:da,onChange:j=>zf(j.target.value),style:E.input,placeholder:qi!=null&&qi.imap_password_set?"••••••••••••••••":"Enter password"}),(qi==null?void 0:qi.imap_password_set)&&!da&&s.jsx("span",{style:E.keyStatus,children:"Password is configured"})]}),s.jsxs("label",{style:E.label,children:["Folder",s.jsx("input",{type:"text",value:nw,onChange:j=>rw(j.target.value),style:E.input,placeholder:"INBOX"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Processing Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Poll Interval",s.jsxs("select",{value:iw,onChange:j=>sw(parseInt(j.target.value)),style:E.input,children:[s.jsx("option",{value:5,children:"Every 5 minutes"}),s.jsx("option",{value:10,children:"Every 10 minutes"}),s.jsx("option",{value:15,children:"Every 15 minutes"}),s.jsx("option",{value:30,children:"Every 30 minutes"}),s.jsx("option",{value:60,children:"Every hour"})]})]}),s.jsxs("label",{style:E.label,children:["Confidence Threshold: ",rx,"%",s.jsx("input",{type:"range",min:30,max:90,value:rx,onChange:j=>vr(parseInt(j.target.value)),style:{width:"100%"}}),s.jsx("span",{style:E.hint,children:"Emails are marked as read when any attachment has confidence above this threshold"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ow,onChange:j=>aw(j.target.checked)}),"Enable Automatic Polling"]})]})]}),(qi==null?void 0:qi.imap_last_sync)&&s.jsxs("div",{style:{...E.hint,marginBottom:"1rem"},children:["Last sync: ",new Date(qi.imap_last_sync).toLocaleString()]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:async()=>{var j;Ho("Testing connection...");try{const Pe=await(await fetch("/api/imap/test-connection",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({imap_host:er||void 0,imap_port:parseInt(Kt)||void 0,imap_use_ssl:Jr,imap_username:Ui||void 0,imap_password:da||void 0})})).json();Pe.success?Ho(`✓ Connected! Available folders: ${((j=Pe.folders)==null?void 0:j.join(", "))||"INBOX"}`):Ho(`Error: ${Pe.error}`)}catch(V){Ho(`Error: ${V}`)}},style:E.testBtn,disabled:!er,children:"Test Connection"}),s.jsx("button",{onClick:async()=>{$u("Syncing...");try{const V=await(await fetch("/api/imap/sync-now",{method:"POST",headers:{Authorization:`Bearer ${e}`}})).json();if(V.success){const Pe=V.results;$u(`✓ Sync complete: ${Pe.emails_processed} emails processed, ${Pe.invoices_created} invoices created, ${Pe.emails_marked_read} marked as read`),i.invalidateQueries({queryKey:["imap-settings"]}),i.invalidateQueries({queryKey:["imap-logs"]}),i.invalidateQueries({queryKey:["imap-stats"]})}else $u(`Error: ${V.error}`)}catch(j){$u(`Error: ${j}`)}},style:E.testBtn,disabled:!(qi!=null&&qi.imap_password_set)&&!da,children:"Sync Now"}),s.jsx("button",{onClick:async()=>{Of("Saving...");try{const j=await fetch("/api/imap/settings",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({imap_host:er||null,imap_port:parseInt(Kt)||993,imap_use_ssl:Jr,imap_username:Ui||null,imap_password:da||void 0,imap_folder:nw||"INBOX",imap_poll_interval:iw,imap_enabled:ow,imap_confidence_threshold:rx/100})});if(j.ok)Of("✓ Settings saved"),zf(""),i.invalidateQueries({queryKey:["imap-settings"]});else{const V=await j.json();Of(`Error: ${V.detail}`)}}catch(j){Of(`Error: ${j}`)}},style:E.saveBtn,children:"Save Settings"})]}),Gr&&s.jsx("div",{style:{...E.statusMessage,background:Gr.startsWith("Error")?"#fee":"#efe"},children:Gr}),lw&&s.jsx("div",{style:{...E.statusMessage,background:lw.startsWith("Error")?"#fee":"#efe"},children:lw}),Qu&&s.jsx("div",{style:{...E.statusMessage,background:Qu.startsWith("Error")?"#fee":"#efe"},children:Qu}),Wc&&s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Sync Statistics"}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Last 24 Hours"}),s.jsxs("p",{children:[Wc.last_24h.emails_processed," emails"]}),s.jsxs("p",{children:[Wc.last_24h.invoices_created," invoices"]}),s.jsxs("p",{children:[Wc.last_24h.confident_invoices," confident"]})]}),s.jsxs("div",{children:[s.jsx("strong",{children:"Last 7 Days"}),s.jsxs("p",{children:[Wc.last_7d.emails_processed," emails"]}),s.jsxs("p",{children:[Wc.last_7d.invoices_created," invoices"]}),s.jsxs("p",{children:[Wc.last_7d.confident_invoices," confident"]})]}),s.jsxs("div",{children:[s.jsx("strong",{children:"Last 30 Days"}),s.jsxs("p",{children:[Wc.last_30d.emails_processed," emails"]}),s.jsxs("p",{children:[Wc.last_30d.invoices_created," invoices"]}),s.jsxs("p",{children:[Wc.last_30d.confident_invoices," confident"]})]})]})]}),qD&&qD.length>0&&s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Recent Processing Logs"}),s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #ddd"},children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem"},children:"Date"}),s.jsx("th",{style:{textAlign:"left",padding:"0.5rem"},children:"Subject"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem"},children:"Attachments"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem"},children:"Invoices"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem"},children:"Status"})]})}),s.jsx("tbody",{children:qD.map(j=>s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem"},children:new Date(j.processed_at).toLocaleString()}),s.jsx("td",{style:{padding:"0.5rem",maxWidth:"250px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j.email_subject||"(no subject)"}),s.jsx("td",{style:{textAlign:"center",padding:"0.5rem"},children:j.attachments_count}),s.jsxs("td",{style:{textAlign:"center",padding:"0.5rem"},children:[j.invoices_created,j.confident_invoices>0&&s.jsxs("span",{style:{color:"#27ae60"},children:[" (",j.confident_invoices," confident)"]})]}),s.jsx("td",{style:{textAlign:"center",padding:"0.5rem"},children:j.marked_as_read?s.jsx("span",{style:{color:"#27ae60"},children:"Read"}):j.processing_status==="skipped"?s.jsx("span",{style:{color:"#95a5a6"},children:"Skipped"}):s.jsx("span",{style:{color:"#e67e22"},children:"Unread"})})]},j.id))})]})]})]}),o==="dext"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Dext Integration"}),s.jsx("p",{style:E.hint,children:"Configure automatic invoice submission to Dext."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Dext Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Dext Email Address",s.jsx("input",{type:"email",value:ne,onChange:j=>ye(j.target.value),style:E.input,placeholder:"yourcompany@dext.com"}),s.jsx("small",{style:{color:"#666",fontSize:"0.9em"},children:"Invoices will be sent to this email address"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ke,onChange:j=>Ye(j.target.checked)}),"Include invoice notes in email body"]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:De,onChange:j=>qe(j.target.checked)}),"Include non-stock items table in email body"]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ue,onChange:j=>Ze(j.target.checked)}),"Automatically send to Dext when invoice is confirmed",s.jsx("small",{style:{color:"#e67e22",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"⚠️ Leave disabled for testing. Enable only when ready for production."})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ee,onChange:j=>Z(j.target.checked)}),'Enable manual "Send to Dext" button on invoice review page',s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When disabled, only the send status will be displayed (without send/resend buttons)"})]}),s.jsxs("label",{style:E.label,children:[s.jsx("input",{type:"checkbox",checked:ge,onChange:j=>Te(j.target.checked)}),"Include PDF annotations (highlights) when sending to Dext",s.jsx("small",{style:{color:"#666",fontSize:"0.9em",display:"block",marginTop:"0.25rem"},children:"When enabled, non-stock items will be highlighted in yellow on the PDF attachment"})]})]})]}),s.jsx("button",{onClick:async()=>{try{(await fetch("/api/settings/",{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({dext_email:ne||null,dext_include_notes:ke,dext_include_non_stock:De,dext_auto_send_enabled:ue,dext_manual_send_enabled:ee,dext_include_annotations:ge})})).ok?(he("✓ Saved successfully"),i.invalidateQueries({queryKey:["settings"]}),setTimeout(()=>he(null),3e3)):he("Error: Failed to save")}catch(j){he(`Error: ${j}`)}},style:E.saveBtn,children:"Save Settings"}),Be&&s.jsx("div",{style:{...E.statusMessage,background:Be.startsWith("Error")?"#fee":"#efe"},children:Be}),s.jsxs("div",{style:{...E.settingsBlock,marginTop:"2rem",borderTop:"1px solid #ddd",paddingTop:"1.5rem"},children:[s.jsx("h3",{style:E.blockTitle,children:"Bulk Operations"}),s.jsx("p",{style:E.hint,children:"Mark all existing invoices as sent to Dext without actually sending them. Useful for migrating to the system."}),s.jsx("button",{onClick:async()=>{if(window.confirm(`Mark ALL invoices not yet sent to Dext as sent? - -This will mark all existing unsent invoices as already sent to Dext. - -Use this when migrating to the system or if invoices were sent outside the system. - -This action cannot be undone.`))try{const j=await fetch("/api/invoices/bulk/mark-all-dext-sent",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();he(`✓ ${V.message}`),setTimeout(()=>he(null),5e3)}else{const V=await j.json();he(`Error: ${V.detail||"Failed to mark invoices"}`)}}catch(j){he(`Error: ${j}`)}},style:{...E.saveBtn,background:"#6c757d"},children:"Mark All Invoices as Sent to Dext"})]})]}),o==="newbook"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Newbook PMS Integration"}),s.jsx("p",{style:E.hint,children:"Connect to Newbook to fetch revenue and occupancy data for GP calculations."}),XK&&s.jsx("div",{style:{padding:"0.5rem",background:"#fff3cd",borderRadius:"4px",marginBottom:"1rem"},children:"Loading Newbook settings..."}),g8&&s.jsxs("div",{style:{padding:"0.5rem",background:"#f8d7da",borderRadius:"4px",marginBottom:"1rem"},children:["Error loading settings: ",g8.message]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Credentials"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:ot,onChange:j=>ut(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:Ot,onChange:j=>An(j.target.value),style:E.input,placeholder:tr!=null&&tr.newbook_api_password_set?"••••••••":"Enter password"})]}),s.jsxs("label",{style:E.label,children:["API Key",s.jsx("input",{type:"password",value:on,onChange:j=>Ke(j.target.value),style:E.input,placeholder:tr!=null&&tr.newbook_api_key_set?"••••••••":"Enter API key"})]}),s.jsxs("label",{style:E.label,children:["Region",s.jsxs("select",{value:Rt,onChange:j=>vt(j.target.value),style:E.input,children:[s.jsx("option",{value:"au",children:"Australia (au)"}),s.jsx("option",{value:"ap",children:"Asia Pacific (ap)"}),s.jsx("option",{value:"eu",children:"Europe (eu)"}),s.jsx("option",{value:"us",children:"United States (us)"})]})]}),s.jsxs("label",{style:E.label,children:["Instance ID (optional)",s.jsx("input",{type:"text",value:Cr,onChange:j=>Qt(j.target.value),style:E.input,placeholder:"Property/Hotel ID"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>k8.mutate(),style:E.testBtn,disabled:k8.isPending,children:"Test Connection"}),s.jsx("button",{onClick:xX,style:E.saveBtn,disabled:rh.isPending,children:"Save Credentials"})]}),aa&&s.jsx("div",{style:{...E.statusMessage,background:aa.startsWith("Error")?"#fee":"#efe"},children:aa})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"GL Account Tracking (for Revenue)"}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>dE.mutate(),style:E.actionBtn,disabled:dE.isPending,children:dE.isPending?"Fetching...":"Fetch GL Accounts"}),s.jsxs("button",{onClick:()=>xr(!0),style:E.actionBtn,disabled:!(Zd!=null&&Zd.length),children:["Select Accounts (",(Zd==null?void 0:Zd.filter(j=>j.is_tracked).length)||0," selected)"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Meal Allocation GL Mapping"}),s.jsx("p",{style:E.hint,children:"Select from tracked GL accounts above to map meal allocations."}),(()=>{const j=(Zd==null?void 0:Zd.filter(dr=>dr.is_tracked))||[],V=Ci?Ci.split(",").map(dr=>dr.trim()):[],Pe=Gs?Gs.split(",").map(dr=>dr.trim()):[],St=dr=>{const xo=new Set(V);xo.has(dr)?xo.delete(dr):xo.add(dr);const Vi=Array.from(xo).join(",");Lr(Vi),rh.mutate({newbook_breakfast_gl_codes:Vi})},yr=dr=>{const xo=new Set(Pe);xo.has(dr)?xo.delete(dr):xo.add(dr);const Vi=Array.from(xo).join(",");Ai(Vi),rh.mutate({newbook_dinner_gl_codes:Vi})};return s.jsxs("div",{style:{display:"flex",gap:"2rem",flexWrap:"wrap"},children:[s.jsxs("div",{style:{flex:1,minWidth:"200px"},children:[s.jsx("strong",{children:"Breakfast Allocations"}),s.jsx("div",{style:E.mealMappingList,children:j.length===0?s.jsx("span",{style:E.mealMappingEmpty,children:"No tracked accounts - select GL accounts above first"}):j.map(dr=>s.jsxs("label",{style:E.mealMappingItem,children:[s.jsx("input",{type:"checkbox",checked:V.includes(dr.gl_code||""),onChange:()=>St(dr.gl_code||"")}),s.jsx("span",{children:dr.gl_name})]},dr.id))})]}),s.jsxs("div",{style:{flex:1,minWidth:"200px"},children:[s.jsx("strong",{children:"Dinner Allocations"}),s.jsx("div",{style:E.mealMappingList,children:j.length===0?s.jsx("span",{style:E.mealMappingEmpty,children:"No tracked accounts - select GL accounts above first"}):j.map(dr=>s.jsxs("label",{style:E.mealMappingItem,children:[s.jsx("input",{type:"checkbox",checked:Pe.includes(dr.gl_code||""),onChange:()=>yr(dr.gl_code||"")}),s.jsx("span",{children:dr.gl_name})]},dr.id))})]})]})})()]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"VAT Rates"}),s.jsx("p",{style:E.hint,children:"Set VAT rates to calculate net values from gross amounts in Newbook inventory items."}),s.jsxs("div",{style:{display:"flex",gap:"2rem",flexWrap:"wrap",marginBottom:"1rem"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"150px"},children:["Breakfast VAT Rate (%)",s.jsx("input",{type:"number",value:Ks,onChange:j=>un(j.target.value),onBlur:()=>{const j=parseFloat(Ks)/100;!isNaN(j)&&j>=0&&j<=1&&rh.mutate({newbook_breakfast_vat_rate:j.toString()})},style:E.input,min:"0",max:"100",step:"0.1"})]}),s.jsxs("label",{style:{...E.label,flex:1,minWidth:"150px"},children:["Dinner VAT Rate (%)",s.jsx("input",{type:"number",value:Fr,onChange:j=>zi(j.target.value),onBlur:()=>{const j=parseFloat(Fr)/100;!isNaN(j)&&j>=0&&j<=1&&rh.mutate({newbook_dinner_vat_rate:j.toString()})},style:E.input,min:"0",max:"100",step:"0.1"})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Room Categories (for Occupancy)"}),s.jsx("p",{style:E.hint,children:"Select which room types to include in occupancy and guest calculations. Exclude overflow rooms etc."}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>hE.mutate(),style:E.actionBtn,disabled:hE.isPending,children:hE.isPending?"Fetching...":"Fetch Room Categories"}),s.jsxs("button",{onClick:()=>rs(!0),style:E.actionBtn,disabled:!(cl!=null&&cl.length),children:["Select Types (",(cl==null?void 0:cl.filter(j=>j.is_included).reduce((j,V)=>j+(V.room_count||0),0))||0," rooms in ",(cl==null?void 0:cl.filter(j=>j.is_included).length)||0," types)"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Data Sync"}),s.jsxs("p",{style:E.hint,children:["Last sync: ",tr!=null&&tr.newbook_last_sync?new Date(tr.newbook_last_sync).toLocaleString():"Never"]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>cE.mutate(),style:E.actionBtn,disabled:cE.isPending,children:cE.isPending?"Syncing...":"Update Forecast Data"}),s.jsx("button",{onClick:()=>Jt(!0),style:E.actionBtn,children:"Fetch Historical Data"})]}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:(tr==null?void 0:tr.newbook_auto_sync_enabled)||!1,onChange:j=>rh.mutate({newbook_auto_sync_enabled:j.target.checked})}),"Enable automatic daily sync (4:00 AM)"]}),s.jsxs("div",{style:{marginTop:"1rem",paddingTop:"1rem",borderTop:"1px solid #eee"},children:[s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:(tr==null?void 0:tr.newbook_upcoming_sync_enabled)||!1,onChange:j=>{const V=j.target.checked;console.log("[DEBUG] Checkbox onChange fired, newValue:",V),rh.mutate({newbook_upcoming_sync_enabled:V})}}),"Enable frequent upcoming sync (next 7 days)"]}),s.jsx("small",{style:E.hint,children:"Keeps ResidentsTableChart fresh with more frequent updates"})]}),(tr==null?void 0:tr.newbook_upcoming_sync_enabled)&&s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"Sync interval (minutes)"}),s.jsx("input",{type:"number",value:(tr==null?void 0:tr.newbook_upcoming_sync_interval)||15,onChange:j=>rh.mutate({newbook_upcoming_sync_interval:parseInt(j.target.value)||15}),min:5,max:60,style:{...E.input,width:"100px"}}),s.jsx("small",{style:E.hint,children:"Recommended: 15 minutes"})]}),(tr==null?void 0:tr.newbook_last_upcoming_sync)&&s.jsx("div",{style:E.formGroup,children:s.jsxs("small",{style:E.hint,children:["Last frequent sync: ",new Date(tr.newbook_last_upcoming_sync).toLocaleString()]})})]}),Vd&&s.jsx("div",{style:{...E.statusMessage,background:Vd.startsWith("Error")?"#fee":"#efe"},children:Vd}),s.jsxs("div",{style:{marginTop:"1rem",paddingTop:"1.5rem",borderTop:"1px solid #e0e0e0"},children:[s.jsx("a",{href:"/newbook",style:{display:"inline-block",padding:"0.75rem 1.5rem",background:"#4a90d9",color:"white",textDecoration:"none",borderRadius:"6px",fontWeight:500},children:"View Newbook Data"}),s.jsx("p",{style:{...E.hint,marginTop:"0.5rem"},children:"View synced revenue, charges, and occupancy data from Newbook."})]})]}),o==="resos"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Resos Restaurant Bookings Integration"}),s.jsx("p",{style:E.hint,children:"Connect to Resos to fetch booking data, flag notable reservations, and track covers."}),QK&&s.jsx("div",{style:{padding:"0.5rem",background:"#fff3cd",borderRadius:"4px",marginBottom:"1rem"},children:"Loading Resos settings..."}),YK&&s.jsx("div",{style:{padding:"0.5rem",background:"#f8d7da",color:"#721c24",borderRadius:"4px",marginBottom:"1rem"},children:"Failed to load Resos settings"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Configuration"}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{style:E.label,children:"Resos API Key *"}),s.jsx("input",{type:"password",value:bt,onChange:j=>yn(j.target.value),placeholder:Dn!=null&&Dn.resos_api_key_set?"••••••••••••":"Enter API key",style:E.input}),(Dn==null?void 0:Dn.resos_api_key_set)&&s.jsx("small",{style:E.hint,children:"API key is configured (enter new value to update)"})]}),s.jsx("button",{onClick:async()=>{try{Qs("Testing...");const j=await fetch("/api/resos/test-connection",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok)Qs("✓ Connection successful");else{const V=await j.json();Qs(`✗ Connection failed: ${V.detail||"Unknown error"}`)}}catch(j){Qs(`✗ Connection failed: ${j}`)}setTimeout(()=>Qs(null),5e3)},style:E.secondaryButton,children:"Test Connection"}),fs&&s.jsx("div",{style:{marginTop:"0.5rem",fontSize:"0.9rem"},children:fs})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Flagging Configuration"}),s.jsxs("div",{style:{...E.formGroup,marginBottom:"1.5rem"},children:[s.jsx("label",{style:E.label,children:"Large Group Threshold"}),s.jsx("input",{type:"number",value:tn,onChange:j=>ci(parseInt(j.target.value)||8),style:{...E.input,maxWidth:"150px"}}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:"Flag bookings with this many people or more (default: 8)"})]}),s.jsxs("div",{style:{...E.formGroup,marginBottom:"1.5rem"},children:[s.jsx("label",{style:E.label,children:"Note Keywords (pipe-separated)"}),s.jsx("input",{type:"text",value:hn,onChange:j=>Ti(j.target.value),placeholder:"birthday|anniversary|proposal|vip",style:{...E.input,maxWidth:"600px"}}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:"Flag bookings with these keywords in notes"})]}),s.jsxs("div",{style:{...E.formGroup,marginBottom:"1.5rem"},children:[s.jsx("label",{style:E.label,children:"Allergy Keywords (pipe-separated)"}),s.jsx("input",{type:"text",value:js,onChange:j=>Ar(j.target.value),placeholder:"gluten|dairy|nut|shellfish|vegan",style:{...E.input,maxWidth:"600px"}}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:'Additional allergy terms to detect in notes (for "Other Allergies" free-text field)'})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Custom Field Mapping"}),s.jsx("p",{style:E.hint,children:"Map Resos custom fields to system fields. Fetch from API to populate available fields."}),s.jsx("button",{onClick:async()=>{try{const j=await fetch("/api/resos/custom-fields",{headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();nn(V.custom_fields||[]),xn("Custom fields fetched successfully")}else xn("Failed to fetch custom fields")}catch(j){xn(`Error: ${j}`)}setTimeout(()=>xn(null),5e3)},style:E.secondaryButton,children:"Fetch Custom Fields from Resos"}),Pa.length>0&&s.jsx("div",{style:{marginTop:"1rem",display:"flex",flexDirection:"column",gap:"0.75rem"},children:[{key:"booking_number",label:"Hotel Booking #",hint:"Newbook/hotel booking reference number from Resos custom field"},{key:"hotel_guest",label:"Hotel Guest",hint:"Yes/No field indicating if diner is a hotel guest"},{key:"dbb",label:"DBB (Dinner B&B)",hint:"Yes/No field indicating Dinner Bed & Breakfast package guests"},{key:"package",label:"Package",hint:"Yes/No field indicating package deal bookings (e.g., special offers)"},{key:"exclude",label:"Group/Exclude",hint:'Free-text field for group codes and exclusions (e.g., "G#123" for groups)'},{key:"allergies",label:"Allergies (Predefined)",hint:"Multi-select field with predefined allergy options (e.g., Gluten, Dairy, Nuts)"},{key:"allergies_other",label:"Other Allergies",hint:"Free-text field for custom allergy notes not in predefined list"}].map(j=>s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},children:[s.jsx("label",{style:{fontWeight:"500",color:"#333",fontSize:"0.9rem"},children:j.label}),s.jsxs("select",{value:$s[j.key]||"",onChange:V=>Gd({...$s,[j.key]:V.target.value}),style:{...E.input,maxWidth:"400px",fontSize:"0.85rem"},children:[s.jsx("option",{value:"",children:"-- Select Field --"}),Pa.map(V=>s.jsx("option",{value:V._id,children:V.name},V._id))]}),s.jsx("small",{style:{...E.hint,marginTop:0,fontSize:"0.75rem"},children:j.hint})]},j.key))})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Opening Hours Mapping"}),s.jsx("p",{style:E.hint,children:"Map regular service periods (excludes special/one-off periods). Resos extends closing times by the default booking length to allow late bookings - the Actual End field shows the calculated time when kitchen closes for new arrivals."}),s.jsx("button",{onClick:async()=>{try{const j=await fetch("/api/resos/sync/opening-hours",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!j.ok){xn("Failed to sync opening hours to database"),setTimeout(()=>xn(null),5e3);return}const V=await j.json(),Pe=await fetch("/api/resos/opening-hours",{headers:{Authorization:`Bearer ${e}`}});if(Pe.ok){const St=await Pe.json();qu(St.opening_hours||[]),xn(`Opening hours synced to database: ${V.count} service periods`)}else xn("Synced to database but failed to fetch for display")}catch(j){xn(`Error: ${j}`)}setTimeout(()=>xn(null),5e3)},style:E.secondaryButton,children:"Fetch Opening Hours from Resos"}),Zl.length>0&&s.jsx("div",{style:{marginTop:"1rem",overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"2px solid #ddd"},children:[s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Period Name"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Start Time"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"End Time (Resos)"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Actual End"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Display Name"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Service Type"})]})}),s.jsx("tbody",{children:Zl.map(j=>{const V=mo.find(Pe=>Pe.resos_id===j._id);return s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem"},children:j.name}),s.jsx("td",{style:{padding:"0.5rem"},children:j.startTime||"-"}),s.jsx("td",{style:{padding:"0.5rem"},children:j.endTime||"-"}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"time",value:(V==null?void 0:V.actual_end)||"",onChange:Pe=>{const St=mo.filter(yr=>yr.resos_id!==j._id);St.push({resos_id:j._id,display_name:(V==null?void 0:V.display_name)||j.name,actual_end:Pe.target.value,service_type:(V==null?void 0:V.service_type)||""}),Bc(St)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px"},placeholder:"Enter actual end time"})}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"text",value:(V==null?void 0:V.display_name)||"",onChange:Pe=>{const St=mo.filter(yr=>yr.resos_id!==j._id);St.push({resos_id:j._id,display_name:Pe.target.value,actual_end:(V==null?void 0:V.actual_end)||"",service_type:(V==null?void 0:V.service_type)||""}),Bc(St)},placeholder:j.name,style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px",width:"100%"}})}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsxs("select",{value:(V==null?void 0:V.service_type)||"",onChange:Pe=>{const St=mo.filter(yr=>yr.resos_id!==j._id);St.push({resos_id:j._id,display_name:(V==null?void 0:V.display_name)||j.name,actual_end:(V==null?void 0:V.actual_end)||"",service_type:Pe.target.value}),Bc(St)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px",width:"120px"},children:[s.jsx("option",{value:"",children:"-- Select --"}),s.jsx("option",{value:"breakfast",children:"Breakfast"}),s.jsx("option",{value:"lunch",children:"Lunch"}),s.jsx("option",{value:"afternoon",children:"Afternoon"}),s.jsx("option",{value:"dinner",children:"Dinner"}),s.jsx("option",{value:"other",children:"Other"})]})})]},j._id)})})]})})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Manual Breakfast Configuration"}),s.jsx("p",{style:E.hint,children:"Since breakfast bookings are not taken through Resos, you can define manual breakfast periods to properly categorize early morning restaurant tickets. Configure different times for each day of the week."}),s.jsx("div",{style:E.formGroup,children:s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:Ra,onChange:j=>Xd(j.target.checked),style:{cursor:"pointer"}}),s.jsx("span",{style:{fontWeight:"bold"},children:"Enable Manual Breakfast Periods"})]})}),Ra&&s.jsxs("div",{style:{marginTop:"1rem"},children:[s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"2px solid #ddd",background:"#f9f9f9"},children:[s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Day"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Start Time"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"End Time"}),s.jsx("th",{style:{padding:"0.5rem",textAlign:"left"},children:"Actions"})]})}),s.jsx("tbody",{children:["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"].map((j,V)=>{const Pe=V+1,St=No.find(yr=>yr.day===Pe);return s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem",fontWeight:"bold"},children:j}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"time",value:(St==null?void 0:St.start)||"",onChange:yr=>{const dr=No.filter(xo=>xo.day!==Pe);(yr.target.value||St!=null&&St.end)&&dr.push({day:Pe,start:yr.target.value,end:(St==null?void 0:St.end)||""}),Js(dr)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px"}})}),s.jsx("td",{style:{padding:"0.5rem"},children:s.jsx("input",{type:"time",value:(St==null?void 0:St.end)||"",onChange:yr=>{const dr=No.filter(xo=>xo.day!==Pe);(yr.target.value||St!=null&&St.start)&&dr.push({day:Pe,start:(St==null?void 0:St.start)||"",end:yr.target.value}),Js(dr)},style:{padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px"}})}),s.jsx("td",{style:{padding:"0.5rem"},children:St&&s.jsx("button",{onClick:()=>{Js(No.filter(yr=>yr.day!==Pe))},style:{padding:"0.25rem 0.5rem",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"Clear"})})]},Pe)})})]}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:"Leave times blank for days without breakfast service. Times are in 24-hour format (e.g., 07:00 - 11:00)."})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Hotel Arrivals Widget Configuration"}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{style:{fontWeight:"bold",display:"block",marginBottom:"0.5rem"},children:"Service Filter for Arrivals Widget"}),s.jsxs("select",{value:Kd||"",onChange:j=>Zs(j.target.value||null),style:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",width:"300px"},children:[s.jsx("option",{value:"",children:"All Services"}),Array.from(new Set(mo.map(j=>j.service_type).filter(j=>j))).sort().map(j=>s.jsx("option",{value:j,children:j.charAt(0).toUpperCase()+j.slice(1)},j))]}),s.jsx("small",{style:{...E.hint,display:"block",marginTop:"0.5rem"},children:'Filter the "Hotel Arrivals & Restaurant Bookings" dashboard widget to show only bookings for a specific service type (e.g., Dinner only). This filter spans all opening hours mapped to the selected service type across different days/times.'})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Sync Configuration"}),s.jsxs("div",{style:E.formGroup,children:[s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:(Dn==null?void 0:Dn.resos_auto_sync_enabled)||!1,onChange:j=>lE.mutate({resos_auto_sync_enabled:j.target.checked})}),"Enable automatic daily sync (4:30 AM)"]}),s.jsx("small",{style:E.hint,children:"Syncs all historical and forecast data (past 30 days + next 60 days)"})]}),(Dn==null?void 0:Dn.resos_last_sync)&&s.jsx("div",{style:E.formGroup,children:s.jsxs("small",{style:E.hint,children:["Last full sync: ",new Date(Dn.resos_last_sync).toLocaleString()]})}),s.jsxs("div",{style:E.formGroup,children:[s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("input",{type:"checkbox",checked:(Dn==null?void 0:Dn.resos_upcoming_sync_enabled)||!1,onChange:j=>lE.mutate({resos_upcoming_sync_enabled:j.target.checked})}),"Enable frequent upcoming sync (next 7 days)"]}),s.jsx("small",{style:E.hint,children:"Keeps upcoming bookings fresh with more frequent updates"})]}),(Dn==null?void 0:Dn.resos_upcoming_sync_enabled)&&s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"Sync interval (minutes)"}),s.jsx("input",{type:"number",value:(Dn==null?void 0:Dn.resos_upcoming_sync_interval)||15,onChange:j=>lE.mutate({resos_upcoming_sync_interval:parseInt(j.target.value)||15}),min:5,max:60,style:E.textInput}),s.jsx("small",{style:E.hint,children:"How often to sync upcoming bookings (5-60 minutes, default 15)"})]}),(Dn==null?void 0:Dn.resos_last_upcoming_sync)&&s.jsx("div",{style:E.formGroup,children:s.jsxs("small",{style:E.hint,children:["Last frequent sync: ",new Date(Dn.resos_last_upcoming_sync).toLocaleString()]})}),(Dn==null?void 0:Dn.resos_upcoming_sync_enabled)&&s.jsx("div",{style:E.formGroup,children:s.jsx("button",{onClick:async()=>{var j;try{xn("Syncing upcoming bookings...");const V=await fetch("/api/resos/sync/upcoming",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(V.ok){const Pe=await V.json();xn(`✓ Upcoming sync complete: ${((j=Pe.upcoming)==null?void 0:j.bookings_fetched)||0} bookings`),i.invalidateQueries({queryKey:["resos-settings"]})}else xn("✗ Upcoming sync failed")}catch(V){xn(`✗ Error: ${V}`)}setTimeout(()=>xn(null),1e4)},style:E.secondaryButton,children:"Sync Now (Next 7 Days)"})}),s.jsxs("div",{style:{display:"flex",gap:"1rem",marginTop:"1rem"},children:[s.jsx("button",{onClick:async()=>{try{xn("Syncing forecast...");const j=await fetch("/api/resos/sync/forecast",{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();xn(`✓ Forecast synced: ${V.bookings_fetched} bookings`),i.invalidateQueries({queryKey:["resos-settings"]})}else xn("✗ Forecast sync failed")}catch(j){xn(`✗ Error: ${j}`)}setTimeout(()=>xn(null),1e4)},style:E.secondaryButton,children:"Sync Forecast (Next 60 Days)"}),s.jsx("button",{onClick:()=>Ic(!0),style:E.secondaryButton,children:"Sync Historical (Custom Range)"})]}),Lo&&s.jsx("div",{style:{marginTop:"1rem",padding:"0.75rem",background:Lo.includes("✓")?"#d4edda":"#f8d7da",borderRadius:"4px"},children:Lo})]}),s.jsx("button",{onClick:async()=>{try{(await fetch("/api/resos/settings",{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({resos_api_key:bt||void 0,resos_large_group_threshold:tn,resos_note_keywords:hn,resos_allergy_keywords:js,resos_custom_field_mapping:$s,resos_opening_hours_mapping:mo,resos_arrival_widget_service_filter:Kd||null,resos_enable_manual_breakfast:Ra,resos_manual_breakfast_periods:No})})).ok?(xn("✓ Settings saved successfully"),i.invalidateQueries({queryKey:["resos-settings"]})):xn("✗ Failed to save settings")}catch(j){xn(`✗ Error: ${j}`)}setTimeout(()=>xn(null),5e3)},style:{...E.button,marginTop:"2rem"},children:"Save Resos Settings"}),s.jsxs("div",{style:{marginTop:"2rem",paddingTop:"1.5rem",borderTop:"1px solid #e0e0e0"},children:[s.jsx("a",{href:"/resos",style:{display:"inline-block",padding:"0.75rem 1.5rem",background:"#0066cc",color:"white",textDecoration:"none",borderRadius:"6px",fontWeight:500},children:"View Resos Booking Data"}),s.jsx("p",{style:{...E.hint,marginTop:"0.5rem"},children:"View synced booking data, covers, and flagged reservations from Resos."})]}),Ba&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Sync Historical Bookings"}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"From Date:"}),s.jsx("input",{type:"date",value:al,onChange:j=>ie(j.target.value),style:E.input})]}),s.jsxs("div",{style:E.formGroup,children:[s.jsx("label",{children:"To Date:"}),s.jsx("input",{type:"date",value:nt,onChange:j=>$(j.target.value),style:E.input})]}),s.jsxs("div",{style:{display:"flex",gap:"1rem",marginTop:"1rem"},children:[s.jsx("button",{onClick:async()=>{try{xn("Syncing historical data...");const j=await fetch(`/api/resos/sync/historical?from_date=${al}&to_date=${nt}`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(j.ok){const V=await j.json();xn(`✓ Historical synced: ${V.bookings_fetched} bookings`),Ic(!1),i.invalidateQueries({queryKey:["resos-settings"]})}else xn("✗ Historical sync failed")}catch(j){xn(`✗ Error: ${j}`)}setTimeout(()=>xn(null),1e4)},style:E.button,children:"Start Sync"}),s.jsx("button",{onClick:()=>Ic(!1),style:E.secondaryButton,children:"Cancel"})]})]})})]}),o==="sambapos"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"SambaPOS EPOS Settings"}),s.jsx("p",{style:E.hint,children:"Connect to your SambaPOS MSSQL database to fetch kitchen courses and sales data for Top Sellers reports."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Database Connection"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Server Host",s.jsx("input",{type:"text",value:ze,onChange:j=>Qe(j.target.value),style:E.input,placeholder:"localhost\\SQLEXPRESS17"}),s.jsx("span",{style:{fontSize:"0.8rem",color:"#888"},children:"For named instances, use format: hostname\\instancename"})]}),s.jsxs("label",{style:E.label,children:["Port",s.jsx("input",{type:"number",value:pt,onChange:j=>kt(j.target.value),style:E.input,placeholder:"1433"}),s.jsx("span",{style:{fontSize:"0.8rem",color:"#888"},children:"Default SQL Server port is 1433 (ignored for named instances)"})]}),s.jsxs("label",{style:E.label,children:["Database Name",s.jsx("input",{type:"text",value:Ht,onChange:j=>Gt(j.target.value),style:E.input,placeholder:"SambaPOS5"})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:Er,onChange:j=>ar(j.target.value),style:E.input,placeholder:"sa"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:Kn,onChange:j=>is(j.target.value),style:E.input,placeholder:$n!=null&&$n.sambapos_db_password_set?"********":"Enter password"}),($n==null?void 0:$n.sambapos_db_password_set)&&!Kn&&s.jsx("span",{style:E.keyStatus,children:"Password is configured"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>gE.mutate(),style:E.testBtn,disabled:gE.isPending||!ze||!Ht||!Er,children:gE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:bX,style:E.saveBtn,disabled:pE.isPending,children:pE.isPending?"Saving...":"Save Connection"})]}),On&&s.jsx("div",{style:{...E.statusMessage,background:On.startsWith("Error")?"#fee":"#efe"},children:On})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Kitchen Courses for Top Sellers"}),s.jsx("p",{style:E.hint,children:"Select and order kitchen courses for the Top Sellers report. Use arrows to change the display order in reports."}),FE?$K?s.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"#666"},children:"Loading courses..."}):x8?s.jsxs("div",{style:{padding:"1rem",background:"#fee",borderRadius:"6px",color:"#c00"},children:["Failed to load courses: ",x8.message,s.jsx("button",{onClick:()=>y8(),style:{...E.actionBtn,marginLeft:"1rem"},children:"Retry"})]}):Zg&&Zg.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("strong",{style:{display:"block",marginBottom:"0.5rem"},children:"Selected Courses (in report order):"}),Tn.length===0?s.jsx("div",{style:{padding:"1rem",background:"#f8f9fa",borderRadius:"6px",color:"#666",fontStyle:"italic"},children:"No courses selected. Add courses from the list below."}):s.jsx("div",{style:E.sortableList,children:Tn.map((j,V)=>s.jsxs("div",{style:E.sortableItem,children:[s.jsx("span",{style:E.sortableOrder,children:V+1}),s.jsx("span",{style:E.sortableName,children:j}),s.jsxs("div",{style:E.sortableButtons,children:[s.jsx("button",{onClick:()=>vX(V),disabled:V===0,style:E.arrowBtn,title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>wX(V),disabled:V===Tn.length-1,style:E.arrowBtn,title:"Move down",children:"▼"}),s.jsx("button",{onClick:()=>T8(j),style:E.removeBtn,title:"Remove",children:"✕"})]})]},j))})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("strong",{style:{display:"block",marginBottom:"0.5rem"},children:"Available Courses:"}),s.jsxs("div",{style:E.sambaCategoryGrid,children:[Zg.filter(j=>!Tn.includes(j.name)).map(j=>s.jsxs("button",{onClick:()=>T8(j.name),style:E.addCourseBtn,children:["+ ",j.name]},j.id)),Zg.filter(j=>!Tn.includes(j.name)).length===0&&s.jsx("span",{style:{color:"#666",fontStyle:"italic"},children:"All courses selected"})]})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{Zg&&Dt(Zg.map(j=>j.name))},style:E.actionBtn,children:"Select All"}),s.jsx("button",{onClick:()=>Dt([]),style:E.actionBtn,children:"Clear All"}),s.jsx("button",{onClick:SX,style:E.saveBtn,disabled:mE.isPending,children:mE.isPending?"Saving...":"Save Courses"})]}),s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:"#e8f4fd",borderRadius:"6px",textAlign:"center",fontWeight:500},children:[Tn.length," of ",Zg.length," courses selected"]})]}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:'No courses found. Please verify your SambaPOS menu items have the "Kitchen Course" product tag configured.'}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:"Configure and test your database connection above to load courses."})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Excluded Menu Categories"}),s.jsx("p",{style:E.hint,children:'Select menu categories (GroupCode) to exclude from the Top Sellers report (e.g., "Drinks", "Extras").'}),FE?JK?s.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"#666"},children:"Loading menu categories..."}):UD&&UD.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>Fi(new Set),style:E.actionBtn,children:"Clear Exclusions"}),s.jsx("button",{onClick:kX,style:E.saveBtn,disabled:yE.isPending,children:yE.isPending?"Saving...":"Save Exclusions"})]}),s.jsx("div",{style:E.excludedItemsGrid,children:UD.map(j=>s.jsxs("label",{style:E.excludedItem,children:[s.jsx("input",{type:"checkbox",checked:Ln.has(j.name),onChange:()=>jX(j.name)}),s.jsx("span",{style:{flex:1},children:j.name})]},j.name))}),s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:Ln.size>0?"#fef3c7":"#e8f4fd",borderRadius:"6px",textAlign:"center",fontWeight:500},children:[Ln.size," categories excluded from reports"]})]}):s.jsxs("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:["No menu categories found.",s.jsx("button",{onClick:()=>ZK(),style:{...E.actionBtn,marginLeft:"1rem"},children:"Retry"})]}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:"Configure your database connection above first."})]}),ps&&s.jsx("div",{style:{...E.statusMessage,background:ps.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:ps}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"GL Code Classification for Spend Analysis"}),s.jsx("p",{style:E.hint,children:'Fetch unique GL codes from "NewBook GLA" custom tags and classify them as food or beverage. Used to calculate average spend per cover and food/beverage split in the Bookings Stats Report.'}),FE?tX?s.jsx("div",{style:{padding:"1rem",textAlign:"center",color:"#666"},children:"Loading GL codes..."}):WC&&WC.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{ll(new Set),Mc(new Set)},style:E.actionBtn,children:"Clear Selections"}),s.jsx("button",{onClick:AX,style:E.saveBtn,disabled:xE.isPending,children:xE.isPending?"Saving...":"Save GL Codes"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"2rem",marginTop:"1.5rem"},children:[s.jsxs("div",{children:[s.jsxs("h4",{style:{marginBottom:"1rem",color:"#374151",fontSize:"1rem"},children:["Food GL Codes (",Zr.size," selected)"]}),s.jsx("div",{style:{...E.excludedItemsGrid,maxHeight:"400px",overflowY:"auto",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"0.75rem"},children:WC.map(j=>s.jsxs("label",{style:E.excludedItem,children:[s.jsx("input",{type:"checkbox",checked:Zr.has(j.code),onChange:()=>_X(j.code),disabled:Wo.has(j.code)}),s.jsx("span",{style:{flex:1,color:Wo.has(j.code)?"#999":"#000"},children:j.code})]},j.code))})]}),s.jsxs("div",{children:[s.jsxs("h4",{style:{marginBottom:"1rem",color:"#374151",fontSize:"1rem"},children:["Beverage GL Codes (",Wo.size," selected)"]}),s.jsx("div",{style:{...E.excludedItemsGrid,maxHeight:"400px",overflowY:"auto",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"0.75rem"},children:WC.map(j=>s.jsxs("label",{style:E.excludedItem,children:[s.jsx("input",{type:"checkbox",checked:Wo.has(j.code),onChange:()=>CX(j.code),disabled:Zr.has(j.code)}),s.jsx("span",{style:{flex:1,color:Zr.has(j.code)?"#999":"#000"},children:j.code})]},j.code))})]})]}),s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:Zr.size>0||Wo.size>0?"#dcfce7":"#e8f4fd",borderRadius:"6px",textAlign:"center",fontWeight:500},children:[Zr.size," food codes, ",Wo.size," beverage codes selected"]})]}):s.jsxs("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:["No GL codes found in ProductTag custom tags.",s.jsx("button",{onClick:()=>eX(),style:{...E.actionBtn,marginLeft:"1rem"},children:"Retry"})]}):s.jsx("div",{style:{padding:"1.5rem",background:"#f8f9fa",borderRadius:"8px",color:"#666",textAlign:"center"},children:"Configure your database connection above first."})]}),H0&&s.jsx("div",{style:{...E.statusMessage,background:H0.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:H0})]}),o==="kds"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Kitchen Display System Settings"}),s.jsx("p",{style:E.hint,children:"Configure the KDS to display orders from SambaPOS GraphQL API for kitchen staff."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"SambaPOS GraphQL Connection"}),s.jsx("p",{style:E.blockHint,children:"Connect to SambaPOS Message Server to fetch kitchen orders in real-time."}),s.jsxs("label",{style:E.label,children:["GraphQL URL",s.jsx("input",{type:"text",value:q0,onChange:j=>A1(j.target.value),style:E.input,placeholder:"http://localhost:9000"})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:V0,onChange:j=>_e(j.target.value),style:E.input,placeholder:"Admin"})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:T1,onChange:j=>G0(j.target.value),style:E.input,placeholder:td!=null&&td.kds_graphql_password_set?"••••••••":"Enter password"})]}),s.jsxs("label",{style:E.label,children:["Client ID (Application Key)",s.jsx("input",{type:"text",value:Mf,onChange:j=>Yt(j.target.value),style:E.input,placeholder:"graphiql"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>bE.mutate(),style:E.testBtn,disabled:bE.isPending||!q0,children:bE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:TX,style:E.saveBtn,disabled:ax.isPending,children:ax.isPending?"Saving...":"Save Connection"})]}),E1&&s.jsx("div",{style:{...E.statusMessage,background:E1.startsWith("Error")?"#fee":"#efe"},children:E1})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Display Settings"}),s.jsx("p",{style:E.blockHint,children:"Configure how tickets and timers are displayed on the KDS screen."}),s.jsxs("label",{style:E.label,children:["Poll Interval (seconds)",s.jsx("input",{type:"number",value:zc,onChange:j=>Vu(parseInt(j.target.value)||5),style:E.input,min:"1",max:"60"})]}),s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem"},children:"Courses & Timer Thresholds"}),s.jsx("p",{style:{fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},children:"Define courses in order. Each course has its own prep (time since called away) and away (time since food sent) timer thresholds in minutes."}),Li.map((j,V)=>s.jsxs("div",{style:{border:"1px solid #ddd",borderRadius:"6px",padding:"0.75rem",marginBottom:"0.5rem",background:"#fafafa"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.5rem"},children:[s.jsx("button",{onClick:()=>F8(V,-1),disabled:V===0,style:{...E.smallBtn,opacity:V===0?.3:1},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>F8(V,1),disabled:V===Li.length-1,style:{...E.smallBtn,opacity:V===Li.length-1?.3:1},title:"Move down",children:"▼"}),s.jsx("input",{type:"text",value:j.name,onChange:Pe=>em(V,"name",Pe.target.value),style:{...E.input,flex:1,marginBottom:0},placeholder:"Course name"}),s.jsx("button",{onClick:()=>PX(V),style:{...E.smallBtn,color:"#e94560",borderColor:"#e94560"},title:"Remove course",children:"✕"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"60px 1fr 1fr 1fr",gap:"0.4rem",alignItems:"center",fontSize:"0.85rem"},children:[s.jsx("span",{style:{fontWeight:"bold"},children:"Prep"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#27ae60",fontSize:"0.8rem"},children:"Green"}),s.jsx("input",{type:"number",value:j.prep_green,onChange:Pe=>em(V,"prep_green",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#f39c12",fontSize:"0.8rem"},children:"Amber"}),s.jsx("input",{type:"number",value:j.prep_amber,onChange:Pe=>em(V,"prep_amber",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#e94560",fontSize:"0.8rem"},children:"Red"}),s.jsx("input",{type:"number",value:j.prep_red,onChange:Pe=>em(V,"prep_red",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"60px 1fr 1fr 1fr",gap:"0.4rem",alignItems:"center",fontSize:"0.85rem",marginTop:"0.3rem"},children:[s.jsx("span",{style:{fontWeight:"bold"},children:"Away"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#27ae60",fontSize:"0.8rem"},children:"Green"}),s.jsx("input",{type:"number",value:j.away_green,onChange:Pe=>em(V,"away_green",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#f39c12",fontSize:"0.8rem"},children:"Amber"}),s.jsx("input",{type:"number",value:j.away_amber,onChange:Pe=>em(V,"away_amber",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[s.jsx("span",{style:{color:"#e94560",fontSize:"0.8rem"},children:"Red"}),s.jsx("input",{type:"number",value:j.away_red,onChange:Pe=>em(V,"away_red",parseFloat(Pe.target.value)||0),style:{...E.input,marginBottom:0,width:"60px"},min:"0",step:"0.5"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#999"},children:"min"})]})]})]},V)),s.jsx("button",{onClick:RX,style:{...E.saveBtn,background:"#3498db",marginBottom:"1rem"},children:"+ Add Course"}),s.jsxs("label",{style:E.label,children:["Show Completed Tickets For (seconds)",s.jsx("input",{type:"number",value:ui,onChange:j=>la(parseInt(j.target.value)||30),style:E.input,min:"0",max:"300"})]}),s.jsxs("label",{style:E.label,children:["Bookings Refresh Interval (seconds)",s.jsx("input",{type:"number",value:F1,onChange:j=>D1(parseInt(j.target.value)||60),style:E.input,min:"10",max:"600"})]}),s.jsx("div",{style:E.buttonRow,children:s.jsx("button",{onClick:FX,style:E.saveBtn,disabled:ax.isPending,children:ax.isPending?"Saving...":"Save Display Settings"})}),Oc&&s.jsx("div",{style:{...E.statusMessage,background:Oc.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:Oc})]})]}),o==="budget"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Spend Budget Settings"}),s.jsx("p",{style:E.hint,children:"Configure integration with the forecasting app to calculate spending budgets based on forecast revenue and GP targets."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Forecast API Connection"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Forecast API URL",s.jsx("input",{type:"text",value:I1,onChange:j=>vC(j.target.value),style:E.input,placeholder:"http://forecast-app:8000"})]}),s.jsxs("label",{style:E.label,children:["API Key",s.jsx("input",{type:"password",value:M1,onChange:j=>z1(j.target.value),style:E.input,placeholder:Jd!=null&&Jd.forecast_api_configured?"••••••••":"Enter API key"})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>SE.mutate(),style:E.testBtn,disabled:SE.isPending||!(Jd!=null&&Jd.forecast_api_configured),children:SE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:EX,style:E.saveBtn,disabled:wE.isPending,children:wE.isPending?"Saving...":"Save Settings"})]}),Q0&&s.jsx("div",{style:{...E.statusMessage,background:Q0.startsWith("Error")?"#fee":"#efe"},children:Q0})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Budget Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["GP Target (%)",s.jsx("input",{type:"number",min:"0",max:"100",step:"0.5",value:wC,onChange:j=>SC(j.target.value),style:{...E.input,width:"120px"}}),s.jsx("span",{style:E.fieldHint,children:"Budget = Forecast Revenue × (100 - GP%)"})]}),s.jsxs("label",{style:E.label,children:["Lookback Period (weeks)",s.jsxs("select",{value:jC,onChange:j=>O1(parseInt(j.target.value)),style:{...E.input,width:"120px"},children:[s.jsx("option",{value:2,children:"2 weeks"}),s.jsx("option",{value:4,children:"4 weeks"}),s.jsx("option",{value:6,children:"6 weeks"}),s.jsx("option",{value:8,children:"8 weeks"})]}),s.jsx("span",{style:E.fieldHint,children:"Used to calculate historical supplier spend percentages"})]})]})]}),N1&&s.jsx("div",{style:{...E.statusMessage,background:N1.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:N1}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Cost Distribution"}),s.jsx("p",{style:{marginBottom:"1rem",color:"#666"},children:"Configure how far into the future invoice costs can be spread when using the cost distribution feature on the Budget page."}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Maximum Days Into Future",s.jsx("input",{type:"number",min:"7",max:"365",value:S,onChange:j=>_(parseInt(j.target.value)||90),style:{...E.input,width:"120px"}}),s.jsx("span",{style:E.fieldHint,children:"Distributions cannot target dates beyond this many days from today (default: 90)"})]}),s.jsx("button",{onClick:()=>Jg.mutate({cost_distribution_max_days:S}),style:E.saveBtn,disabled:Jg.isPending,children:Jg.isPending?"Saving...":"Save"})]})]})]}),o==="kitchen"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Kitchen Details"}),s.jsx("p",{style:E.hint,children:"Your kitchen address and contact details appear on Purchase Order letterheads and emails sent to suppliers."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Business Details"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Display Name",s.jsx("input",{type:"text",value:fC,onChange:j=>Yd(j.target.value),style:E.input,placeholder:"e.g., Number Four at Stow"}),s.jsx("span",{style:E.fieldHint,children:"Name shown on PO letterhead (defaults to kitchen name if blank)"})]}),s.jsxs("label",{style:E.label,children:["Address Line 1",s.jsx("input",{type:"text",value:Ni,onChange:j=>K0(j.target.value),style:E.input,placeholder:"e.g., 4 The Square"})]}),s.jsxs("label",{style:E.label,children:["Address Line 2",s.jsx("input",{type:"text",value:Gu,onChange:j=>pC(j.target.value),style:E.input,placeholder:"e.g., Stow-on-the-Wold"})]}),s.jsxs("div",{style:{display:"flex",gap:"1rem"},children:[s.jsxs("label",{style:{...E.label,flex:2},children:["City / Town",s.jsx("input",{type:"text",value:Jl,onChange:j=>gC(j.target.value),style:E.input,placeholder:"e.g., Cheltenham"})]}),s.jsxs("label",{style:{...E.label,flex:1},children:["Postcode",s.jsx("input",{type:"text",value:mC,onChange:j=>yC(j.target.value),style:E.input,placeholder:"e.g., GL54 1BQ"})]})]}),s.jsxs("label",{style:E.label,children:["Phone",s.jsx("input",{type:"tel",value:X0,onChange:j=>Y0(j.target.value),style:E.input,placeholder:"e.g., 01451 830297"})]}),s.jsxs("label",{style:E.label,children:["Email",s.jsx("input",{type:"email",value:xC,onChange:j=>bC(j.target.value),style:E.input,placeholder:"e.g., kitchen@example.com"})]}),s.jsx("div",{style:E.buttonRow,children:s.jsx("button",{onClick:DX,style:E.saveBtn,disabled:vE.isPending,children:vE.isPending?"Saving...":"Save Details"})}),R1&&s.jsx("div",{style:{...E.statusMessage,background:R1.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:R1})]})]})]}),o==="suppliers"&&s.jsx("div",{style:E.section,children:s.jsx(DJ,{})}),o==="nextcloud"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Nextcloud File Storage"}),s.jsx("p",{style:E.hint,children:"Archive confirmed invoices to Nextcloud to reduce local storage. Files are organized by supplier, year, and month."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Nextcloud Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:H1,onChange:j=>TC(j.target.checked)}),"Enable Nextcloud archival"]}),s.jsxs("label",{style:E.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:Z0,onChange:j=>J0(j.target.checked),disabled:!H1}),"Delete local files after successful archive"]}),s.jsx("p",{style:{...E.hint,marginLeft:"1.5rem",marginTop:"-0.5rem",marginBottom:"1rem"},children:"Frees up Docker storage after files are safely archived to Nextcloud"}),s.jsxs("label",{style:E.label,children:["Nextcloud Host URL",s.jsx("input",{type:"text",value:kC,onChange:j=>U1(j.target.value),placeholder:"https://cloud.example.com",style:E.input})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:_C,onChange:j=>CC(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:$0,onChange:j=>pD(j.target.value),placeholder:ul!=null&&ul.nextcloud_password_set?"••••••••":"Enter password",style:E.input}),(ul==null?void 0:ul.nextcloud_password_set)&&s.jsx("span",{style:E.keyStatus,children:"Password is set"})]}),s.jsxs("label",{style:E.label,children:["Base Directory",s.jsx("input",{type:"text",value:ed,onChange:j=>AC(j.target.value),placeholder:"/Kitchen Invoices",style:E.input})]}),s.jsxs("p",{style:{...E.hint,marginTop:"0.5rem"},children:["Files organized as: ",ed||"/Kitchen Invoices","/Supplier/Year/Month/"]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{const j={nextcloud_host:kC,nextcloud_username:_C,nextcloud_base_path:ed,nextcloud_enabled:H1,nextcloud_delete_local:Z0};$0&&(j.nextcloud_password=$0),jE.mutate(j)},style:E.saveBtn,disabled:jE.isPending,children:jE.isPending?"Saving...":"Save Settings"}),s.jsx("button",{onClick:()=>kE.mutate(),style:E.testBtn,disabled:kE.isPending,children:kE.isPending?"Testing...":"Test Connection"})]}),V1&&s.jsx("div",{style:{...E.statusMessage,background:V1.startsWith("Error")?"#fee":"#efe"},children:V1}),ex&&s.jsx("div",{style:{...E.statusMessage,background:ex.startsWith("Error")?"#fee":"#efe"},children:ex})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Manual Archive"}),s.jsx("p",{style:E.hint,children:"Manually archive completed invoices that haven't been transferred to Nextcloud yet."}),qo&&s.jsxs("div",{style:E.dataActions,children:[s.jsx("div",{style:E.dataAction,children:s.jsxs("div",{children:[s.jsx("strong",{children:"Total local files:"})," ",qo.local_count," invoices",s.jsx("p",{style:E.actionDesc,children:"All invoices stored in Docker container"})]})}),s.jsx("div",{style:E.dataAction,children:s.jsxs("div",{children:[s.jsx("strong",{children:"Ready for archival:"})," ",qo.pending_count,s.jsx("p",{style:E.actionDesc,children:"Confirmed invoices that can be archived"})]})}),s.jsx("div",{style:E.dataAction,children:s.jsxs("div",{children:[s.jsx("strong",{children:"Already archived:"})," ",qo.archived_count," invoices"]})}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Archive All Pending"}),s.jsx("p",{style:E.actionDesc,children:"Transfer all eligible invoices to Nextcloud now"})]}),s.jsx("button",{onClick:()=>{confirm(`Archive ${qo.pending_count} invoices to Nextcloud?`)&&_E.mutate()},style:E.actionBtn,disabled:_E.isPending||qo.pending_count===0||!qo.nextcloud_configured,children:_E.isPending?"Archiving...":"Archive All"})]})]})]}),K1&&s.jsx("div",{style:{...E.statusMessage,background:K1.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:K1})]}),o==="search"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Search & Pricing"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Price Change Detection"}),s.jsx("p",{style:{marginBottom:"1rem",color:"#666"},children:"Configure how price changes are detected and flagged on invoices. When a line item's price differs from historical prices, it will be marked with a warning indicator."}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Lookback Period (days)",s.jsx("input",{type:"number",value:en,onChange:j=>rn(parseInt(j.target.value)||30),min:"1",max:"365",style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"How far back to check for price history (default: 30 days)"})]}),s.jsxs("label",{style:E.label,children:["Amber Warning Threshold (%)",s.jsx("input",{type:"number",value:Nn,onChange:j=>Qn(parseInt(j.target.value)||10),min:"1",max:"100",style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"Price changes above this % show amber warning (default: 10%)"})]}),s.jsxs("label",{style:E.label,children:["Red Warning Threshold (%)",s.jsx("input",{type:"number",value:gr,onChange:j=>br(parseInt(j.target.value)||20),min:"1",max:"100",style:E.input}),s.jsx("span",{style:{fontSize:"0.85rem",color:"#666"},children:"Price changes above this % show red warning (default: 20%)"})]}),s.jsx("button",{onClick:()=>{TE.mutate({price_change_lookback_days:en,price_change_amber_threshold:Nn,price_change_red_threshold:gr})},style:E.btn,disabled:TE.isPending,children:TE.isPending?"Saving...":"Save Settings"}),mr&&s.jsx("div",{style:{...E.statusMessage,background:mr.startsWith("Error")?"#fee":"#efe"},children:mr})]})]}),s.jsx("h3",{style:{...E.subsectionTitle,marginTop:"2rem"},children:"Price Status Legend"}),s.jsxs("div",{style:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{color:"#22c55e",fontWeight:"bold",fontSize:"1.2rem"},children:"✓"}),s.jsx("span",{children:"Price consistent (no significant change)"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{color:"#f59e0b",fontWeight:"bold",fontSize:"1.2rem"},children:"?"}),s.jsx("span",{children:"Small price change (amber threshold)"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{color:"#ef4444",fontWeight:"bold",fontSize:"1.2rem"},children:"!"}),s.jsx("span",{children:"Large price change (red threshold)"})]})]}),s.jsx("p",{style:{color:"#666",fontSize:"0.9rem"},children:"Click on a price status icon to view the full price history and acknowledge the change."})]}),o==="backup"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Backup & Restore"}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Backup Settings"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Frequency",s.jsxs("select",{value:Y1,onChange:j=>Q1(j.target.value),style:E.input,children:[s.jsx("option",{value:"manual",children:"Manual Only"}),s.jsx("option",{value:"daily",children:"Daily"}),s.jsx("option",{value:"weekly",children:"Weekly (Sundays)"})]})]}),s.jsxs("label",{style:E.label,children:["Time (for scheduled backups)",s.jsx("input",{type:"time",value:tx,onChange:j=>qn(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Retention (number of backups to keep)",s.jsx("input",{type:"number",min:"1",max:"100",value:Ku,onChange:j=>FC(parseInt(j.target.value)||7),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Destination",s.jsxs("select",{value:dl,onChange:j=>DC(j.target.value),style:E.input,children:[s.jsx("option",{value:"local",children:"Local Storage"}),s.jsx("option",{value:"nextcloud",children:"Nextcloud"}),s.jsx("option",{value:"smb",children:"SMB Network Share"})]})]}),dl==="nextcloud"&&s.jsxs(s.Fragment,{children:[!(qo!=null&&qo.nextcloud_configured)&&s.jsx("div",{style:{...E.statusMessage,background:"#fee",marginTop:"0.5rem"},children:"⚠️ Nextcloud is not configured. Please set up Nextcloud credentials in the Nextcloud Storage settings first."}),s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem"},children:"Nextcloud Backup Settings"}),s.jsxs("label",{style:E.label,children:["Backup Directory Path",s.jsx("input",{type:"text",value:Qd,onChange:j=>Nc(j.target.value),placeholder:"/Backups",style:E.input,disabled:!(qo!=null&&qo.nextcloud_configured)})]}),s.jsx("p",{style:E.hint,children:"Path on Nextcloud where backups will be stored (separate from invoice archives)"})]}),dl==="smb"&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{style:{marginTop:"1rem",marginBottom:"0.5rem"},children:"SMB Network Share Settings"}),s.jsxs("label",{style:E.label,children:["SMB Host",s.jsx("input",{type:"text",value:Xu,onChange:j=>$1(j.target.value),placeholder:"192.168.1.100",style:E.input})]}),s.jsxs("label",{style:E.label,children:["Share Name",s.jsx("input",{type:"text",value:Yu,onChange:j=>Z1(j.target.value),placeholder:"backups",style:E.input})]}),s.jsxs("label",{style:E.label,children:["Username",s.jsx("input",{type:"text",value:J1,onChange:j=>ew(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["Password",s.jsx("input",{type:"password",value:nx,onChange:j=>EC(j.target.value),placeholder:Nr!=null&&Nr.backup_smb_password_set?"••••••••":"Enter password",style:E.input}),(Nr==null?void 0:Nr.backup_smb_password_set)&&s.jsx("span",{style:E.keyStatus,children:"Password is set"})]}),s.jsxs("label",{style:E.label,children:["Path on Share",s.jsx("input",{type:"text",value:tw,onChange:j=>B(j.target.value),placeholder:"/kitchen-backups",style:E.input})]})]}),s.jsx("div",{style:E.buttonRow,children:s.jsx("button",{onClick:()=>{const j={backup_frequency:Y1,backup_retention_count:Ku,backup_destination:dl,backup_time:tx};dl==="nextcloud"&&(j.backup_nextcloud_path=Qd),dl==="smb"&&(j.backup_smb_host=Xu,j.backup_smb_share=Yu,j.backup_smb_username=J1,j.backup_smb_path=tw,nx&&(j.backup_smb_password=nx)),CE.mutate(j)},style:E.saveBtn,disabled:CE.isPending||dl==="nextcloud"&&!(qo!=null&&qo.nextcloud_configured),children:CE.isPending?"Saving...":"Save Backup Settings"})}),oe&&s.jsx("div",{style:{...E.statusMessage,background:oe.startsWith("Error")?"#fee":"#efe"},children:oe})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Manual Backup"}),s.jsx("div",{style:E.dataActions,children:s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Last Backup:"})," ",Nr!=null&&Nr.backup_last_run_at?new Date(Nr.backup_last_run_at).toLocaleString():"Never",(Nr==null?void 0:Nr.backup_last_status)&&s.jsx("span",{style:{marginLeft:"1rem",color:Nr.backup_last_status==="success"?"#28a745":"#dc3545"},children:Nr.backup_last_status==="success"?"Success":"Failed"}),(Nr==null?void 0:Nr.backup_last_error)&&s.jsx("p",{style:{...E.actionDesc,color:"#dc3545"},children:Nr.backup_last_error})]}),s.jsx("button",{onClick:()=>AE.mutate(),style:E.saveBtn,disabled:AE.isPending,children:AE.isPending?"Creating...":"Create Backup Now"})]})})]}),Ae&&s.jsx("div",{style:{...E.statusMessage,background:Ae.startsWith("Error")?"#fee":"#efe",marginTop:"1rem"},children:Ae}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Restore from File"}),s.jsx("div",{style:E.dataActions,children:s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Upload Backup File"}),s.jsx("p",{style:E.actionDesc,children:"Restore invoice files from a previously downloaded backup ZIP file. Only missing files will be restored (existing files are not overwritten)."})]}),s.jsx("input",{type:"file",accept:".zip",onChange:j=>{var Pe;const V=(Pe=j.target.files)==null?void 0:Pe[0];V&&(confirm("Restore from this backup file? Only missing files will be restored.")&&YC.mutate(V),j.target.value="")},style:{display:"none"},id:"backup-upload-input"}),s.jsx("label",{htmlFor:"backup-upload-input",style:{...E.saveBtn,cursor:YC.isPending?"not-allowed":"pointer",opacity:YC.isPending?.6:1,display:"inline-block"},children:YC.isPending?"Uploading...":"Upload & Restore"})]})})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Backup History"}),HD&&HD.length>0?s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:E.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:E.th,children:"Date"}),s.jsx("th",{style:E.th,children:"Type"}),s.jsx("th",{style:E.th,children:"Destination"}),s.jsx("th",{style:E.th,children:"Status"}),s.jsx("th",{style:E.th,children:"Size"}),s.jsx("th",{style:E.th,children:"Actions"})]})}),s.jsx("tbody",{children:HD.map(j=>s.jsxs("tr",{children:[s.jsx("td",{style:E.td,children:new Date(j.started_at).toLocaleString()}),s.jsx("td",{style:E.td,children:j.backup_type}),s.jsx("td",{style:E.td,children:j.destination}),s.jsx("td",{style:E.td,children:s.jsx("span",{style:{color:j.status==="success"?"#28a745":j.status==="running"?"#ffc107":"#dc3545"},children:j.status})}),s.jsx("td",{style:E.td,children:j.file_size_bytes?`${(j.file_size_bytes/1024/1024).toFixed(1)} MB`:"-"}),s.jsx("td",{style:E.td,children:s.jsxs("div",{style:E.actionButtons,children:[s.jsx("button",{onClick:()=>{window.open(`/api/backup/${j.id}/download?token=${e}`,"_blank")},style:E.actionBtn,disabled:j.status!=="success",title:"Download",children:"Download"}),s.jsx("button",{onClick:()=>{confirm("Restore from this backup? This will restore files that are missing locally.")&&_8.mutate(j.id)},style:E.actionBtn,disabled:j.status!=="success"||_8.isPending,title:"Restore",children:"Restore"}),s.jsx("button",{onClick:()=>{confirm("Delete this backup?")&&C8.mutate(j.id)},style:E.deleteBtn,disabled:C8.isPending,title:"Delete",children:"Delete"})]})})]},j.id))})]})}):s.jsx("p",{style:E.hint,children:"No backups yet. Create your first backup above."})]})]}),o==="food_flags"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Food Flags"}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[s.jsx("p",{style:{...E.hint,marginBottom:0},children:"Manage allergen and dietary flag categories and their individual flags."}),s.jsx("button",{onClick:async()=>{t8(!0),Hi(null);try{const j=await fetch("/api/food-flags/seed-defaults",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(V.created_flags===0&&V.created_categories===0?Hi("All default flags already exist."):Hi(`Loaded ${V.created_flags} flags in ${V.created_categories} categories + ${V.seeded_keywords} keywords.`),i.invalidateQueries({queryKey:["food-flag-categories"]}),i.invalidateQueries({queryKey:["allergen-keywords"]})):Hi(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{Hi("Error: Network error")}t8(!1)},disabled:BC,style:{padding:"0.4rem 0.75rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:BC?"wait":"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap",opacity:BC?.6:1},children:BC?"Loading...":"Load UK 14 Defaults"})]}),vD&&s.jsx("div",{style:{...E.statusMessage,background:vD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:vD}),b8&&b8.map(j=>s.jsxs("div",{style:E.settingsBlock,children:[dw===j.id?s.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap",marginBottom:"1rem"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"200px"},children:["Category Name",s.jsx("input",{type:"text",value:cw,onChange:V=>uw(V.target.value),style:E.input})]}),s.jsxs("label",{style:{...E.label,minWidth:"160px"},children:["Propagation Type",s.jsxs("select",{value:Yg,onChange:V=>ix(V.target.value),style:E.input,children:[s.jsx("option",{value:"contains",children:"Contains (allergens)"}),s.jsx("option",{value:"suitable_for",children:"Suitable For (dietary)"})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>XD.mutate({id:j.id,data:{name:cw,propagation_type:Yg}}),style:E.saveBtn,disabled:XD.isPending,children:"Save"}),s.jsx("button",{onClick:()=>Xg(null),style:E.actionBtn,children:"Cancel"})]})]}):s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[s.jsxs("div",{children:[s.jsx("h3",{style:{...E.blockTitle,marginBottom:"0.25rem"},children:j.name}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:"0.8rem",color:"#666",background:j.propagation_type==="contains"?"#fff3cd":"#d4edda",padding:"0.15rem 0.5rem",borderRadius:"4px"},children:j.propagation_type==="contains"?"Contains (allergen)":"Suitable For (dietary)"}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"0.8rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:j.required,onChange:()=>XD.mutate({id:j.id,data:{required:!j.required}}),style:{margin:0}}),"Required"]})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>{Xg(j.id),uw(j.name),ix(j.propagation_type)},style:E.smallBtn,title:"Edit category",children:"✎"}),s.jsx("button",{onClick:()=>{confirm(`Delete category "${j.name}" and all its flags?`)&&nX.mutate(j.id)},style:{...E.smallBtn,color:"#dc3545"},title:"Delete category",children:"✕"})]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[j.flags.map(V=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:gD===V.id?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:pw,onChange:Pe=>X3(Pe.target.value),style:{...E.input,flex:2},placeholder:"Name"}),s.jsx("input",{type:"text",value:Y3,onChange:Pe=>Q3(Pe.target.value),style:{...E.input,flex:1},placeholder:"Code"}),s.jsx("input",{type:"text",value:$3,onChange:Pe=>Z3(Pe.target.value),style:{...E.input,flex:1},placeholder:"Icon"}),s.jsx("button",{onClick:()=>w8.mutate({id:V.id,data:{name:pw,code:Y3||void 0,icon:$3||void 0}}),style:E.saveBtn,disabled:w8.isPending,children:"Save"}),s.jsx("button",{onClick:()=>Nf(null),style:E.actionBtn,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[V.icon&&s.jsx("span",{style:{fontSize:"1.2rem"},children:V.icon}),s.jsx("span",{style:{flex:2,fontWeight:"500"},children:V.name}),s.jsx("span",{style:{flex:1,color:"#666",fontSize:"0.85rem"},children:V.code||"-"}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[s.jsx("button",{onClick:()=>{Nf(V.id),X3(V.name),Q3(V.code||""),Z3(V.icon||"")},style:E.smallBtn,title:"Edit flag",children:"✎"}),s.jsx("button",{onClick:()=>{confirm(`Delete flag "${V.name}"?`)&&rX.mutate(V.id)},style:{...E.smallBtn,color:"#dc3545"},title:"Delete flag",children:"✕"})]})]})},V.id)),HK===j.id?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"6px",border:"1px dashed #ccc"},children:[s.jsx("input",{type:"text",value:RC,onChange:V=>yD(V.target.value),style:{...E.input,flex:2},placeholder:"Flag name"}),s.jsx("input",{type:"text",value:J3,onChange:V=>xD(V.target.value),style:{...E.input,flex:1},placeholder:"Code (e.g. GF)"}),s.jsx("input",{type:"text",value:e8,onChange:V=>bD(V.target.value),style:{...E.input,flex:1},placeholder:"Icon (emoji)"}),s.jsx("button",{onClick:()=>{RC.trim()&&v8.mutate({category_id:j.id,name:RC.trim(),code:J3.trim()||void 0,icon:e8.trim()||void 0})},style:E.saveBtn,disabled:v8.isPending||!RC.trim(),children:"Add"}),s.jsx("button",{onClick:()=>{mD(null),yD(""),xD(""),bD("")},style:E.actionBtn,children:"Cancel"})]}):s.jsx("button",{onClick:()=>mD(j.id),style:{...E.secondaryButton,alignSelf:"flex-start",marginTop:"0.25rem"},children:"+ Add Flag"})]})]},j.id)),Qg?s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"New Category"}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"200px"},children:["Category Name",s.jsx("input",{type:"text",value:Lf,onChange:j=>hw(j.target.value),style:E.input,placeholder:"e.g., Allergens, Dietary Preferences"})]}),s.jsxs("label",{style:{...E.label,minWidth:"160px"},children:["Propagation Type",s.jsxs("select",{value:PC,onChange:j=>Zu(j.target.value),style:E.input,children:[s.jsx("option",{value:"contains",children:"Contains (allergens)"}),s.jsx("option",{value:"suitable_for",children:"Suitable For (dietary)"})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>{Lf.trim()&&KD.mutate({name:Lf.trim(),propagation_type:PC})},style:E.saveBtn,disabled:KD.isPending||!Lf.trim(),children:KD.isPending?"Creating...":"Create Category"}),s.jsx("button",{onClick:()=>{fw(!1),hw(""),Zu("contains")},style:E.actionBtn,children:"Cancel"})]})]}),s.jsxs("p",{style:{...E.hint,marginTop:"0.5rem",marginBottom:0},children:[s.jsx("strong",{children:"Contains"}),': Flag propagates if ANY ingredient has it (e.g., "Contains Nuts").',s.jsx("br",{}),s.jsx("strong",{children:"Suitable For"}),': Flag propagates only if ALL ingredients have it (e.g., "Vegan").']})]}):s.jsx("button",{onClick:()=>fw(!0),style:{...E.button,marginTop:"0.5rem"},children:"+ Add Category"})]}),o==="allergen_keywords"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Allergen Keywords"}),s.jsx("p",{style:E.hint,children:"Manage ingredient name keywords that trigger allergen flag suggestions. When creating or editing ingredients, names and product ingredient lists are matched against these keywords to suggest relevant flags."}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"1rem"},children:s.jsx("button",{onClick:()=>{confirm("Reset all default keywords to their original values? Your custom-added keywords will be preserved.")&&ZD.mutate()},style:E.actionBtn,disabled:ZD.isPending,children:ZD.isPending?"Resetting...":"Reset to Defaults"})}),jD&&s.jsx("div",{style:{...E.statusMessage,background:jD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:jD}),YD&&YD.length>0?YD.map(j=>s.jsxs("div",{style:E.settingsBlock,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:[s.jsxs("h3",{style:{...E.blockTitle,marginBottom:0},children:[j.flag_name,j.flag_code&&s.jsxs("span",{style:{color:"#888",fontWeight:400,marginLeft:"0.5rem"},children:["(",j.flag_code,")"]}),s.jsx("span",{style:{color:"#aaa",fontWeight:400,fontSize:"0.8rem",marginLeft:"0.5rem"},children:j.category_name})]}),qK===j.flag_id?s.jsxs("div",{style:{display:"flex",gap:"0.35rem",alignItems:"center"},children:[s.jsx("input",{type:"text",value:sx,onChange:V=>wD(V.target.value),style:{...E.input,width:"150px",padding:"0.3rem 0.5rem",fontSize:"0.8rem"},placeholder:"New keyword...",onKeyDown:V=>{V.key==="Enter"&&sx.trim()&&$D.mutate({food_flag_id:j.flag_id,keyword:sx.trim().toLowerCase()})},autoFocus:!0}),s.jsx("button",{onClick:()=>{sx.trim()&&$D.mutate({food_flag_id:j.flag_id,keyword:sx.trim().toLowerCase()})},style:E.saveBtn,disabled:!sx.trim()||$D.isPending,children:"Add"}),s.jsx("button",{onClick:()=>{SD(null),wD("")},style:E.actionBtn,children:"Cancel"})]}):s.jsx("button",{onClick:()=>SD(j.flag_id),style:E.secondaryButton,children:"+ Add"})]}),s.jsxs("div",{style:{display:"flex",gap:"0.3rem",flexWrap:"wrap"},children:[j.keywords.map(V=>s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.25rem",padding:"0.2rem 0.5rem",background:V.is_default?"#f0f0f0":"#e8f0fe",border:`1px solid ${V.is_default?"#ddd":"#90caf9"}`,borderRadius:"12px",fontSize:"0.78rem",color:"#555"},children:[V.keyword,s.jsx("button",{onClick:()=>iX.mutate(V.id),style:{background:"none",border:"none",cursor:"pointer",color:"#999",fontSize:"0.7rem",padding:"0 0.15rem",lineHeight:1},title:"Remove keyword",children:"✕"})]},V.id)),j.keywords.length===0&&s.jsx("span",{style:{fontSize:"0.8rem",color:"#aaa",fontStyle:"italic"},children:"No keywords"})]})]},j.flag_id)):s.jsx("p",{style:E.hint,children:"No allergen keywords configured. Keywords are seeded automatically when food flags are created."})]}),o==="ingredient_categories"&&s.jsxs("div",{style:E.section,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("h2",{style:E.sectionTitle,children:"Ingredient Categories"}),s.jsx("button",{onClick:async()=>{yo(null);try{const j=await fetch("/api/ingredients/categories/seed-defaults",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(V.created===0?yo("All default categories already exist."):yo(`Loaded ${V.created} default categories.`),qC()):yo(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{yo("Error: Network error")}},style:{padding:"0.4rem 0.75rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap"},children:"Load Defaults"})]}),s.jsx("p",{style:E.hint,children:"Manage ingredient groupings (e.g. Dairy, Meat, Produce). Categories help organise your ingredient library and can be used to filter the ingredients list."}),TD&&s.jsx("div",{style:{...E.statusMessage,background:TD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:TD}),Ps&&Ps.length>0?s.jsx("div",{style:E.settingsBlock,children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Order"}),s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Name"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Ingredients"}),s.jsx("th",{style:{textAlign:"right",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Actions"})]})}),s.jsx("tbody",{children:Ps.map((j,V)=>s.jsx("tr",{style:{borderBottom:"1px solid #eee"},children:VK===j.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem"},children:s.jsx("input",{type:"number",value:i8,onChange:Pe=>s8(parseInt(Pe.target.value)||0),style:{...E.input,width:"60px",marginBottom:0}})}),s.jsx("td",{style:{padding:"0.5rem 0.75rem"},children:s.jsx("input",{type:"text",value:n8,onChange:Pe=>r8(Pe.target.value),style:{...E.input,marginBottom:0}})}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.ingredient_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>VC.mutate({id:j.id,data:{name:n8,sort_order:i8}}),style:E.saveBtn,disabled:VC.isPending,children:"Save"}),s.jsx("button",{onClick:()=>kD(null),style:E.actionBtn,children:"Cancel"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem"},children:s.jsxs("div",{style:{display:"flex",gap:"0.25rem",alignItems:"center"},children:[s.jsx("button",{onClick:()=>S8(j.id,"up"),disabled:V===0,style:{background:"none",border:"none",cursor:V===0?"default":"pointer",opacity:V===0?.3:1,fontSize:"1rem",padding:"0 2px"},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>S8(j.id,"down"),disabled:V===Ps.length-1,style:{background:"none",border:"none",cursor:V===Ps.length-1?"default":"pointer",opacity:V===Ps.length-1?.3:1,fontSize:"1rem",padding:"0 2px"},title:"Move down",children:"▼"})]})}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",fontWeight:500},children:j.name}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.ingredient_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>{kD(j.id),r8(j.name),s8(j.sort_order)},style:E.smallBtn,title:"Edit",children:"✎"}),s.jsx("button",{onClick:()=>{confirm(`Delete "${j.name}"?${j.ingredient_count>0?` ${j.ingredient_count} ingredient(s) will become uncategorised.`:""}`)&&sX.mutate(j.id)},style:{...E.smallBtn,color:"#dc3545"},title:"Delete",children:"✕"})]})})]})},j.id))})]})}):s.jsx("p",{style:E.hint,children:"No ingredient categories yet. Create your first category below."}),GK?s.jsxs("div",{style:{...E.settingsBlock,marginTop:"1rem"},children:[s.jsx("h3",{style:E.blockTitle,children:"New Category"}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap"},children:[s.jsxs("label",{style:{...E.label,flex:1,minWidth:"200px"},children:["Name",s.jsx("input",{type:"text",value:_D,onChange:j=>CD(j.target.value),placeholder:"e.g. Dairy, Produce, Proteins...",style:E.input})]}),s.jsxs("label",{style:{...E.label,minWidth:"80px"},children:["Sort Order",s.jsx("input",{type:"number",value:o8,onChange:j=>IC(parseInt(j.target.value)||0),style:{...E.input,width:"80px"}})]}),s.jsx("button",{onClick:()=>JD.mutate({name:_D.trim(),sort_order:o8}),style:E.saveBtn,disabled:!_D.trim()||JD.isPending,children:JD.isPending?"Creating...":"Create"}),s.jsx("button",{onClick:()=>{AD(!1),CD(""),IC(0)},style:E.actionBtn,children:"Cancel"})]})]}):s.jsx("button",{onClick:()=>{AD(!0),IC((Ps==null?void 0:Ps.length)||0)},style:{...E.button,marginTop:"0.5rem"},children:"+ Add Category"})]}),o==="recipe_sections"&&s.jsxs("div",{style:E.section,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("h2",{style:E.sectionTitle,children:"Recipe Sections"}),s.jsx("button",{onClick:async()=>{MC(null);try{const j=await fetch("/api/recipes/menu-sections/seed-defaults?section_type=recipe",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(MC(V.created===0?"All default sections already exist.":`Loaded ${V.created} default sections.`),GC()):MC(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{MC("Error: Network error")}},style:{padding:"0.4rem 0.75rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap"},children:"Load Defaults"})]}),s.jsx("p",{style:E.hint,children:"Recipe sections group component recipes (e.g. Sauces & Jus, Meats & Protein). Used to organise recipes in the recipe list."}),FD&&s.jsx("div",{style:{...E.statusMessage,background:FD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:FD}),th&&th.length>0?s.jsx("div",{style:E.settingsBlock,children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Name"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Recipes"}),s.jsx("th",{style:{textAlign:"right",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Actions"})]})}),s.jsx("tbody",{children:th.map(j=>s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem",fontWeight:500},children:j.name}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.recipe_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsx("button",{onClick:async()=>{confirm(`Delete "${j.name}"?${j.recipe_count>0?` ${j.recipe_count} recipe(s) will become unsectioned.`:""}`)&&(await fetch(`/api/recipes/menu-sections/${j.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})).ok&&GC()},style:{...E.smallBtn,color:"#dc3545"},title:"Delete",children:"✕"})})]},j.id))})]})}):s.jsx("p",{style:E.hint,children:'No recipe sections yet. Click "Load Defaults" or add one below.'}),s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"0.5rem",alignItems:"flex-end"},children:[s.jsx("input",{type:"text",placeholder:"New section name...",id:"newRecipeSectionName",style:{...E.input,marginBottom:0,flex:1,maxWidth:"300px"},onKeyDown:async j=>{if(j.key==="Enter"){const V=j.currentTarget,Pe=V.value.trim();if(!Pe)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:Pe,section_type:"recipe",sort_order:(th==null?void 0:th.length)||0})})).ok&&(V.value="",GC())}}}),s.jsx("button",{onClick:async()=>{const j=document.getElementById("newRecipeSectionName"),V=j==null?void 0:j.value.trim();if(!V)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:V,section_type:"recipe",sort_order:(th==null?void 0:th.length)||0})})).ok&&(j.value="",GC())},style:E.saveBtn,children:"Add"})]})]}),o==="dish_courses"&&s.jsxs("div",{style:E.section,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("h2",{style:E.sectionTitle,children:"Dish Courses"}),s.jsx("button",{onClick:async()=>{zC(null);try{const j=await fetch("/api/recipes/menu-sections/seed-defaults?section_type=dish",{method:"POST",headers:{Authorization:`Bearer ${e}`}}),V=await j.json();j.ok?(zC(V.created===0?"All default courses already exist.":`Loaded ${V.created} default courses.`),KC()):zC(`Error: ${V.detail||"Failed to seed defaults"}`)}catch{zC("Error: Network error")}},style:{padding:"0.4rem 0.75rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,whiteSpace:"nowrap"},children:"Load Defaults"})]}),s.jsx("p",{style:E.hint,children:"Dish courses categorise menu items (e.g. Starter, Main, Dessert). Used to organise dishes in the dish list."}),DD&&s.jsx("div",{style:{...E.statusMessage,background:DD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:DD}),nh&&nh.length>0?s.jsx("div",{style:E.settingsBlock,children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{textAlign:"left",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Name"}),s.jsx("th",{style:{textAlign:"center",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Dishes"}),s.jsx("th",{style:{textAlign:"right",padding:"0.5rem 0.75rem",borderBottom:"2px solid #dee2e6",fontSize:"0.85rem",color:"#666"},children:"Actions"})]})}),s.jsx("tbody",{children:nh.map(j=>s.jsxs("tr",{style:{borderBottom:"1px solid #eee"},children:[s.jsx("td",{style:{padding:"0.5rem 0.75rem",fontWeight:500},children:j.name}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"center",color:"#666",fontSize:"0.85rem"},children:j.recipe_count}),s.jsx("td",{style:{padding:"0.5rem 0.75rem",textAlign:"right"},children:s.jsx("button",{onClick:async()=>{confirm(`Delete "${j.name}"?${j.recipe_count>0?` ${j.recipe_count} dish(es) will become uncategorised.`:""}`)&&(await fetch(`/api/recipes/menu-sections/${j.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})).ok&&KC()},style:{...E.smallBtn,color:"#dc3545"},title:"Delete",children:"✕"})})]},j.id))})]})}):s.jsx("p",{style:E.hint,children:'No dish courses yet. Click "Load Defaults" or add one below.'}),s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"0.5rem",alignItems:"flex-end"},children:[s.jsx("input",{type:"text",placeholder:"New course name...",id:"newDishCourseName",style:{...E.input,marginBottom:0,flex:1,maxWidth:"300px"},onKeyDown:async j=>{if(j.key==="Enter"){const V=j.currentTarget,Pe=V.value.trim();if(!Pe)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:Pe,section_type:"dish",sort_order:(nh==null?void 0:nh.length)||0})})).ok&&(V.value="",KC())}}}),s.jsx("button",{onClick:async()=>{const j=document.getElementById("newDishCourseName"),V=j==null?void 0:j.value.trim();if(!V)return;(await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:V,section_type:"dish",sort_order:(nh==null?void 0:nh.length)||0})})).ok&&(j.value="",KC())},style:E.saveBtn,children:"Add"})]})]}),o==="api_access"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"API Access"}),s.jsxs("p",{style:E.hint,children:["Manage API key access for external applications such as menu display plugins. External apps authenticate using the ",s.jsx("code",{children:"X-API-Key"})," header."]}),RD&&s.jsx("div",{style:{...E.statusMessage,background:RD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:RD}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Key Settings"}),s.jsxs("label",{style:{...E.checkboxLabel,marginTop:0,marginBottom:"1.5rem"},children:[s.jsx("input",{type:"checkbox",checked:a8,onChange:j=>{ED(j.target.checked),oX.mutate({api_key_enabled:j.target.checked})}}),s.jsx("span",{children:"Enable API Access"})]}),s.jsxs("label",{style:E.label,children:["Current API Key",s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("input",{type:"text",readOnly:!0,value:$d?OC?$d:$d.substring(0,8)+"..."+$d.substring($d.length-4):"No API key generated",style:{...E.input,flex:1,fontFamily:"monospace",background:"#f8f9fa",color:$d?"#333":"#999"}}),$d&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>l8(!OC),style:E.smallBtn,title:OC?"Hide key":"Reveal key",children:OC?"👁":"🔒"}),s.jsx("button",{onClick:()=>{$d&&(navigator.clipboard.writeText($d),Wf("API key copied to clipboard"),setTimeout(()=>Wf(null),3e3))},style:E.smallBtn,title:"Copy to clipboard",children:"📋"})]})]}),s.jsx("span",{style:E.fieldHint,children:a8?"API access is enabled. External apps can use this key to access recipe and food flag data.":"API access is disabled. Enable it above to allow external apps to connect."})]}),s.jsx("div",{style:{...E.buttonRow,marginTop:"1rem"},children:s.jsx("button",{onClick:()=>{$d?confirm("Regenerate API key? The old key will stop working immediately.")&&XC.mutate():XC.mutate()},style:E.saveBtn,disabled:XC.isPending,children:XC.isPending?"Generating...":$d?"Regenerate API Key":"Generate API Key"})})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Usage"}),s.jsx("p",{style:{...E.hint,marginBottom:"0.5rem"},children:"External applications can access the following endpoints using the API key:"}),s.jsxs("div",{style:{fontFamily:"monospace",fontSize:"0.85rem",background:"white",padding:"0.75rem",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{marginBottom:"0.25rem"},children:[s.jsx("strong",{children:"GET"})," /api/external/recipes/dishes"]}),s.jsxs("div",{style:{marginBottom:"0.25rem"},children:[s.jsx("strong",{children:"GET"})," /api/external/recipes/:id"]}),s.jsxs("div",{children:[s.jsx("strong",{children:"GET"})," /api/external/food-flags"]})]}),s.jsxs("p",{style:{...E.hint,marginTop:"0.75rem",marginBottom:0},children:["Include the header ",s.jsx("code",{style:{background:"#f0f0f5",padding:"0.1rem 0.3rem",borderRadius:"3px"},children:"X-API-Key: your-key-here"})," with every request."]})]})]}),o==="llm"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"AI Features (Claude)"}),s.jsx("p",{style:E.hint,children:"Configure Anthropic Claude integration for allergen detection, ingredient matching, and more."}),zD&&s.jsx("div",{style:{...E.statusMessage,background:zD.startsWith("Error")?"#fee":"#efe",marginBottom:"1rem"},children:zD}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Master Switch"}),s.jsxs("label",{style:{...E.checkboxLabel,marginTop:0},children:[s.jsx("input",{type:"checkbox",checked:mw,onChange:j=>d8(j.target.checked)}),s.jsx("span",{children:"Enable AI Features"})]}),s.jsx("p",{style:{...E.hint,marginTop:"0.5rem",marginBottom:0},children:mw?"AI features are active. Allergen analysis, smart matching, and other AI tools will appear throughout the app.":"All AI features are hidden. No API calls are made, and no AI elements are shown anywhere in the app."})]}),mw&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"API Configuration"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["Anthropic API Key",s.jsx("input",{type:"password",value:LC,onChange:j=>c8(j.target.value),style:E.input,placeholder:Lt!=null&&Lt.anthropic_api_key_set?"••••••••••••••••":"Enter your Anthropic API key"}),(Lt==null?void 0:Lt.anthropic_api_key_set)&&!LC&&s.jsx("span",{style:E.keyStatus,children:"Key is configured"}),s.jsx("span",{style:E.fieldHint,children:"Get your key from console.anthropic.com. Stored securely in your database."})]}),s.jsxs("div",{style:E.label,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{children:"Model"}),s.jsx("button",{type:"button",onClick:()=>dX(),disabled:j8,style:{background:"none",border:"1px solid #ccc",borderRadius:"4px",padding:"0.15rem 0.5rem",fontSize:"0.75rem",cursor:"pointer",color:"#666"},children:j8?"Fetching...":"Refresh Models"})]}),Uf&&Uf.models.length>0?s.jsx("select",{value:BD,onChange:j=>ID(j.target.value),style:E.input,children:Uf.models.map(j=>s.jsxs("option",{value:j.id,children:[j.display_name,j.id===Uf.default?" (default)":""]},j.id))}):s.jsx("input",{type:"text",value:BD,onChange:j=>ID(j.target.value),style:E.input,placeholder:lX?"Loading models...":"e.g. claude-haiku-4-5-20251001"}),s.jsxs("span",{style:E.fieldHint,children:[Uf!=null&&Uf.models.length?`${Uf.models.length} models available.`:"Save your API key first to see available models."," ","Haiku is recommended — Sonnet costs ~10x more."]})]}),s.jsxs("label",{style:E.label,children:["Confidence Threshold",s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("input",{type:"range",min:"0.50",max:"0.99",step:"0.01",value:MD,onChange:j=>u8(parseFloat(j.target.value)),style:{flex:1}}),s.jsxs("span",{style:{fontFamily:"monospace",minWidth:"3.5rem"},children:[(MD*100).toFixed(0),"%"]})]}),s.jsx("span",{style:E.fieldHint,children:"Minimum confidence for AI suggestions to be shown. Lower = more suggestions, higher = more precise."})]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Cost Controls"}),s.jsx("div",{style:E.form,children:s.jsxs("label",{style:E.label,children:["Monthly Token Budget",s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("input",{type:"number",value:$g,onChange:j=>h8(parseInt(j.target.value)||0),style:{...E.input,flex:1},min:"0",step:"50000"}),s.jsxs("span",{style:{fontFamily:"monospace",minWidth:"5rem",color:"#666",fontSize:"0.85rem"},children:["~$",($g/1e6*1.25).toFixed(2),"/mo"]})]}),s.jsx("span",{style:E.fieldHint,children:"Set to 0 to pause all AI features without removing the API key. 500,000 tokens ~= $0.63/month on Haiku."})]})}),ec&&(ec.total_calls>0||(Lt==null?void 0:Lt.anthropic_api_key_set))&&s.jsxs("div",{style:{marginTop:"1rem",background:"white",padding:"1rem",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[s.jsx("strong",{style:{fontSize:"0.9rem"},children:"This Month's Usage"}),s.jsx("button",{onClick:()=>aX(),style:{...E.smallBtn,width:"auto",padding:"0.2rem 0.5rem",fontSize:"0.75rem"},children:"Refresh"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"0.75rem"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:"API Calls"}),s.jsxs("div",{style:{fontWeight:"600"},children:[ec.successful_calls," / ",ec.total_calls]})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:"Tokens Used"}),s.jsx("div",{style:{fontWeight:"600"},children:ec.total_tokens.toLocaleString()})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:"Est. Cost"}),s.jsxs("div",{style:{fontWeight:"600"},children:["$",ec.estimated_cost_usd.toFixed(4)]})]})]}),$g>0&&s.jsxs("div",{style:{marginTop:"0.75rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"0.75rem",color:"#888",marginBottom:"0.25rem"},children:[s.jsx("span",{children:"Budget"}),s.jsxs("span",{children:[(ec.total_tokens/$g*100).toFixed(1),"%"]})]}),s.jsx("div",{style:{height:"6px",background:"#e9ecef",borderRadius:"3px",overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:`${Math.min(100,ec.total_tokens/$g*100)}%`,background:ec.total_tokens/$g>.8?"#e94560":"#28a745",borderRadius:"3px",transition:"width 0.3s"}})})]}),ec.cache_entries_this_month>0&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#888",marginTop:"0.5rem"},children:[ec.cache_entries_this_month," cached results this month"]})]})]}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Feature Toggles"}),s.jsx("p",{style:{...E.hint,marginBottom:"0.75rem"},children:"Enable or disable individual AI features. Disabled features fall back to existing keyword/trigram matching."}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.25rem"},children:[{key:"label_parsing",label:"Label Allergen Parsing",desc:"Auto-analyse product ingredient labels"},{key:"recipe_scanning",label:"Recipe Text Scanning",desc:"Detect allergens in recipe text"},{key:"invoice_assist",label:"Invoice AI Assist",desc:"Smart OCR correction suggestions"},{key:"ingredient_match",label:"Ingredient Matching",desc:"AI-powered ingredient suggestions"},{key:"line_item_reconciliation",label:"Line Item Reconciliation",desc:"Match items from supplier history"},{key:"duplicate_detection",label:"Duplicate Detection",desc:"Find semantic duplicates"},{key:"menu_description",label:"Menu Descriptions",desc:"Generate dish descriptions"},{key:"dispute_email",label:"Dispute Email Drafting",desc:"Draft supplier dispute emails"},{key:"supplier_alias",label:"Supplier Alias Resolution",desc:"Match unknown vendor names"},{key:"yield_estimation",label:"Yield Estimation",desc:"Suggest ingredient yields"}].map(({key:j,label:V,desc:Pe})=>s.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem",cursor:"pointer",borderRadius:"4px"},children:[s.jsx("input",{type:"checkbox",checked:f8[j]??!0,onChange:St=>p8(yr=>({...yr,[j]:St.target.checked})),style:{marginTop:"0.15rem"}}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.9rem",fontWeight:500},children:V}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:Pe})]})]},j))})]})]}),s.jsxs("div",{style:E.buttonRow,children:[mw&&(Lt==null?void 0:Lt.anthropic_api_key_set)&&s.jsx("button",{onClick:()=>tE.mutate(),style:E.testBtn,disabled:tE.isPending,children:tE.isPending?"Testing...":"Test Connection"}),s.jsx("button",{onClick:cX,style:E.saveBtn,disabled:eE.isPending,children:eE.isPending?"Saving...":"Save AI Settings"})]}),LD&&s.jsx("div",{style:{...E.statusMessage,background:LD.startsWith("Error")?"#fee":"#efe"},children:LD})]}),o==="data"&&s.jsxs("div",{style:E.section,children:[s.jsx("h2",{style:E.sectionTitle,children:"Data Management"}),s.jsx("p",{style:E.hint,children:"Tools for reprocessing invoices and fixing supplier matching issues."}),s.jsxs("div",{style:E.settingsBlock,children:[s.jsx("h3",{style:E.blockTitle,children:"Data Actions"}),s.jsxs("div",{style:E.dataActions,children:[s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Reprocess All Invoices"}),s.jsx("p",{style:E.actionDesc,children:"Re-run OCR processing on all non-confirmed invoices."})]}),s.jsx("button",{onClick:()=>{confirm("Reprocess all non-confirmed invoices?")&&iE.mutate()},style:E.actionBtn,disabled:iE.isPending,children:iE.isPending?"Reprocessing...":"Reprocess"})]}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Clear Fuzzy Matches"}),s.jsx("p",{style:E.actionDesc,children:"Clear all fuzzy supplier matches and re-run matching."})]}),s.jsx("button",{onClick:()=>{confirm("Clear all fuzzy supplier matches?")&&aE.mutate()},style:E.actionBtn,disabled:aE.isPending,children:aE.isPending?"Clearing...":"Clear Matches"})]}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Clear Cache & Reload"}),s.jsx("p",{style:E.actionDesc,children:"Clear all cached files, service worker data, and reload with fresh assets."})]}),s.jsx("button",{onClick:async()=>{var j;try{const V=await caches.keys();await Promise.all(V.map(St=>caches.delete(St)));const Pe=await((j=navigator.serviceWorker)==null?void 0:j.getRegistrations());Pe&&await Promise.all(Pe.map(St=>St.unregister())),i.clear(),window.location.reload()}catch{window.location.reload()}},style:E.actionBtn,children:"Clear & Reload"})]}),s.jsxs("div",{style:E.dataAction,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Cleanup False Price Changes"}),s.jsx("p",{style:E.actionDesc,children:"Remove recipe change log entries where old and new price are identical (e.g. £0.0086/g → £0.0086/g)."})]}),s.jsx("button",{onClick:()=>{confirm("Remove all false price change entries from recipe change logs?")&&sE.mutate()},style:E.actionBtn,disabled:sE.isPending,children:sE.isPending?"Cleaning...":"Cleanup"})]}),s.jsxs("div",{style:E.actionRow,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Backfill Invoice References"}),s.jsx("p",{style:E.actionDesc,children:"Link existing price change entries to their triggering invoice (for entries created before this feature was added)."})]}),s.jsx("button",{onClick:()=>{confirm("Scan price change entries and link them to triggering invoices?")&&oE.mutate()},style:E.actionBtn,disabled:oE.isPending,children:oE.isPending?"Backfilling...":"Backfill"})]})]})]}),ct&&s.jsx("div",{style:{...E.statusMessage,background:ct.startsWith("Error")?"#fee":"#efe"},children:ct})]})]}),Dr&&Zd&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Select GL Accounts for Revenue Tracking"}),s.jsx("div",{style:E.glList,children:(()=>{const j={};return Zd.forEach(Pe=>{const St=Pe.gl_group_name||"Ungrouped";j[St]||(j[St]=[]),j[St].push(Pe)}),Object.keys(j).sort().map(Pe=>{const St=j[Pe],yr=St.every(Vi=>Vi.is_tracked),dr=St.some(Vi=>Vi.is_tracked),xo=()=>{const Vi=!yr;mX.mutate(St.map(DE=>({id:DE.id,is_tracked:Vi})))};return s.jsxs("div",{style:E.glGroup,children:[s.jsxs("label",{style:E.glGroupHeader,children:[s.jsx("input",{type:"checkbox",checked:yr,ref:Vi=>{Vi&&(Vi.indeterminate=dr&&!yr)},onChange:xo,style:{marginRight:"0.5rem"}}),Pe,s.jsxs("span",{style:E.glGroupCount,children:["(",St.filter(Vi=>Vi.is_tracked).length,"/",St.length,")"]})]}),s.jsx("div",{style:E.glGroupItems,children:St.map(Vi=>s.jsxs("label",{style:E.glItem,children:[s.jsx("input",{type:"checkbox",checked:Vi.is_tracked,onChange:DE=>gX.mutate({id:Vi.id,is_tracked:DE.target.checked})}),s.jsx("span",{children:Vi.gl_name}),Vi.gl_code&&s.jsxs("span",{style:E.glCode,children:["(",Vi.gl_code,")"]})]},Vi.id))})]},Pe)})})()}),s.jsx("button",{onClick:()=>xr(!1),style:E.btn,children:"Close"})]})}),Ss&&cl&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Select Room Categories for Occupancy"}),s.jsx("p",{style:{color:"#666",fontSize:"0.9rem",marginBottom:"1rem"},children:"Select which room types to include in occupancy and guest calculations."}),s.jsx("div",{style:E.glList,children:cl.map(j=>s.jsxs("label",{style:E.glItem,children:[s.jsx("input",{type:"checkbox",checked:j.is_included,onChange:V=>{fE.mutate([{id:j.id,is_included:V.target.checked}])}}),s.jsx("span",{children:j.site_name}),s.jsxs("span",{style:E.glCode,children:["(",j.room_count," rooms)"]})]},j.id))}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>{fE.mutate(cl.map(j=>({id:j.id,is_included:!0})))},style:E.actionBtn,children:"Select All"}),s.jsx("button",{onClick:()=>{fE.mutate(cl.map(j=>({id:j.id,is_included:!1})))},style:E.actionBtn,children:"Deselect All"}),s.jsx("button",{onClick:()=>rs(!1),style:E.btn,children:"Close"})]})]})}),Xs&&s.jsx("div",{style:E.modal,children:s.jsxs("div",{style:E.modalContent,children:[s.jsx("h3",{children:"Fetch Historical Data"}),s.jsxs("div",{style:E.form,children:[s.jsxs("label",{style:E.label,children:["From Date",s.jsx("input",{type:"date",value:Ea,onChange:j=>zn(j.target.value),style:E.input})]}),s.jsxs("label",{style:E.label,children:["To Date",s.jsx("input",{type:"date",value:gi,onChange:j=>je(j.target.value),style:E.input})]}),s.jsxs("div",{style:E.buttonRow,children:[s.jsx("button",{onClick:()=>uE.mutate({date_from:Ea,date_to:gi}),style:E.saveBtn,disabled:!Ea||!gi||uE.isPending,children:uE.isPending?"Syncing...":"Sync"}),s.jsx("button",{onClick:()=>Jt(!1),style:E.btn,children:"Cancel"})]})]})]})})]})}const E={layout:{display:"flex",gap:"2rem",maxWidth:"1200px",margin:"0 auto"},sidebar:{width:"200px",flexShrink:0,background:"white",borderRadius:"12px",padding:"1rem",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",height:"fit-content",position:"sticky",top:"1rem"},sidebarTitle:{margin:"0 0 1rem 0",fontSize:"1.1rem",color:"#1a1a2e"},nav:{display:"flex",flexDirection:"column",gap:"0.25rem"},navItem:{padding:"0.75rem 1rem",border:"none",background:"transparent",textAlign:"left",cursor:"pointer",borderRadius:"6px",fontSize:"0.95rem",color:"#333"},navItemActive:{background:"#e94560",color:"white"},content:{flex:1,minWidth:0},section:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},sectionTitle:{color:"#1a1a2e",marginTop:0,marginBottom:"1rem"},subsectionTitle:{color:"#1a1a2e",marginTop:"1.5rem",marginBottom:"0.75rem",fontSize:"1rem"},hint:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},fieldHint:{color:"#888",fontSize:"0.8rem",fontWeight:"normal"},form:{display:"flex",flexDirection:"column",gap:"1rem",maxWidth:"500px"},infoGrid:{display:"grid",gap:"0.5rem"},label:{display:"flex",flexDirection:"column",gap:"0.5rem",color:"#333",fontWeight:"500"},input:{padding:"0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"1rem"},keyStatus:{fontSize:"0.8rem",color:"#5cb85c"},buttonRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap"},btn:{padding:"0.5rem 1rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},testBtn:{padding:"0.5rem 1rem",background:"#5bc0de",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},saveBtn:{padding:"0.5rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"500"},smallBtn:{width:"28px",height:"28px",background:"white",border:"1px solid #ccc",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"0.75rem",flexShrink:0},actionBtn:{padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},secondaryButton:{padding:"0.5rem 1rem",background:"#5bc0de",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},button:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"500",fontSize:"1rem"},statusMessage:{padding:"0.75rem",borderRadius:"6px",marginTop:"0.5rem"},checkboxLabel:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"1rem",cursor:"pointer"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"0.75rem",borderBottom:"2px solid #eee",color:"#666",fontSize:"0.85rem"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},disabledRow:{opacity:.6,background:"#f9f9f9"},activeStatus:{color:"#28a745",fontWeight:"500"},inactiveStatus:{color:"#dc3545",fontWeight:"500"},actionButtons:{display:"flex",gap:"0.5rem"},disableBtn:{padding:"0.35rem 0.75rem",background:"#ffc107",color:"#212529",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},enableBtn:{padding:"0.35rem 0.75rem",background:"#28a745",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},deleteBtn:{padding:"0.35rem 0.75rem",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},promoteBtn:{padding:"0.35rem 0.75rem",background:"#6f42c1",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},demoteBtn:{padding:"0.35rem 0.75rem",background:"#6c757d",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},checkboxGroup:{display:"flex",flexDirection:"column",gap:"0.5rem",marginBottom:"1rem"},youLabel:{color:"#666",fontSize:"0.85rem",fontStyle:"italic"},dataActions:{display:"flex",flexDirection:"column",gap:"1rem"},dataAction:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"1rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},actionDesc:{margin:"0.25rem 0 0 0",fontSize:"0.85rem",color:"#666"},loading:{padding:"2rem",textAlign:"center",color:"#666"},modal:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modalContent:{background:"white",padding:"1.5rem",borderRadius:"12px",maxWidth:"500px",width:"90%",maxHeight:"80vh",overflow:"auto"},glList:{display:"flex",flexDirection:"column",gap:"0.5rem",margin:"1rem 0",maxHeight:"300px",overflow:"auto"},glItem:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"#f8f9fa",borderRadius:"4px",cursor:"pointer"},glCode:{color:"#666",fontSize:"0.85rem"},glGroup:{marginBottom:"1.25rem"},glGroupHeader:{display:"flex",alignItems:"center",fontWeight:"bold",fontSize:"0.95rem",color:"#1a1a2e",padding:"0.5rem 0.75rem",background:"#f0f0f5",borderLeft:"3px solid #e94560",marginBottom:"0.5rem",cursor:"pointer"},glGroupItems:{paddingLeft:"1.25rem",borderLeft:"1px solid #e0e0e0",marginLeft:"0.5rem"},glGroupCount:{marginLeft:"auto",fontSize:"0.8rem",color:"#666",fontWeight:"normal"},mealMappingList:{display:"flex",flexDirection:"column",gap:"0.25rem",maxHeight:"150px",overflow:"auto",padding:"0.5rem",background:"#f8f9fa",borderRadius:"6px",marginTop:"0.5rem"},mealMappingItem:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem",cursor:"pointer"},mealMappingEmpty:{color:"#999",fontSize:"0.85rem",fontStyle:"italic"},sambaCategoryGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(180px, 1fr))",gap:"0.5rem",marginTop:"1rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",maxHeight:"300px",overflowY:"auto"},sortableList:{display:"flex",flexDirection:"column",gap:"0.25rem",background:"#f8f9fa",borderRadius:"8px",padding:"0.5rem"},sortableItem:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"6px",boxShadow:"0 1px 3px rgba(0,0,0,0.08)"},sortableOrder:{width:"24px",height:"24px",display:"flex",alignItems:"center",justifyContent:"center",background:"#e94560",color:"white",borderRadius:"50%",fontSize:"0.8rem",fontWeight:"bold"},sortableName:{flex:1,fontWeight:500},sortableButtons:{display:"flex",gap:"0.25rem"},arrowBtn:{width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid #ddd",background:"white",borderRadius:"4px",cursor:"pointer",fontSize:"0.75rem"},removeBtn:{width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"#fee",color:"#c00",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},addCourseBtn:{padding:"0.5rem 0.75rem",background:"#e8f4fd",border:"1px dashed #0077cc",borderRadius:"6px",color:"#0077cc",cursor:"pointer",fontSize:"0.9rem"},excludedItemsGrid:{display:"flex",flexDirection:"column",gap:"0.25rem",marginTop:"1rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",maxHeight:"300px",overflowY:"auto"},excludedItem:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"white",borderRadius:"4px",cursor:"pointer",fontSize:"0.9rem"},settingsBlock:{background:"#f8f9fa",padding:"1.5rem",borderRadius:"8px",marginBottom:"1.5rem",border:"1px solid #e0e0e0"},blockTitle:{color:"#1a1a2e",marginTop:0,marginBottom:"0.75rem",fontSize:"1.1rem",fontWeight:"600",borderBottom:"2px solid #e94560",paddingBottom:"0.5rem"}},PJ=["January","February","March","April","May","June","July","August","September","October","November","December"],RJ=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function BJ(){const{token:n}=gn(),e=new Date,[t,r]=k.useState(e.getFullYear()),[i,o]=k.useState(e.getMonth()+1),[a,l]=k.useState(null),{data:d}=Oe({queryKey:["settings"],queryFn:async()=>{const _=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${n}`}});if(!_.ok)throw new Error("Failed to fetch settings");return _.json()},enabled:!!n}),c=(d==null?void 0:d.currency_symbol)||"£",{data:u,isLoading:f}=Oe({queryKey:["newbook-calendar",t,i],queryFn:async()=>{const _=await fetch(`/api/newbook/calendar/${t}/${i}`,{headers:{Authorization:`Bearer ${n}`}});if(!_.ok)throw new Error("Failed to fetch calendar data");return _.json()},enabled:!!n}),p=()=>{i===1?(o(12),r(t-1)):o(i-1)},g=()=>{i===12?(o(1),r(t+1)):o(i+1)},m=()=>{r(e.getFullYear()),o(e.getMonth()+1)},y=new Date(t,i-1,1).getDay(),v=new Date(t,i,0).getDate(),x=[];for(let _=0;_{if(_===null)return"-";const b=new Intl.NumberFormat("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2}).format(_);return`${c}${b}`},S=_=>new Date(_).toLocaleDateString("en-AU",{weekday:"long",day:"numeric",month:"long",year:"numeric"});return s.jsxs("div",{style:Nt.container,children:[s.jsxs("div",{style:Nt.titleRow,children:[s.jsx("a",{href:"/settings",style:Nt.backLink,children:"← Back to Settings"}),s.jsx("h1",{style:Nt.title,children:"Newbook Data"})]}),s.jsxs("div",{style:Nt.calendarHeader,children:[s.jsx("button",{onClick:p,style:Nt.navBtn,children:"< Prev"}),s.jsxs("div",{style:Nt.monthTitle,children:[s.jsxs("h2",{style:Nt.monthName,children:[PJ[i-1]," ",t]}),s.jsx("button",{onClick:m,style:Nt.todayBtn,children:"Today"})]}),s.jsx("button",{onClick:g,style:Nt.navBtn,children:"Next >"})]}),s.jsxs("div",{style:Nt.legend,children:[s.jsxs("div",{style:Nt.legendItem,children:[s.jsx("span",{style:{...Nt.legendDot,background:"#4ade80"}}),s.jsx("span",{children:"Historical (locked)"})]}),s.jsxs("div",{style:Nt.legendItem,children:[s.jsx("span",{style:{...Nt.legendDot,background:"#fbbf24"}}),s.jsx("span",{children:"Forecast (updates on sync)"})]}),s.jsxs("div",{style:Nt.legendItem,children:[s.jsx("span",{style:{...Nt.legendDot,background:"#e5e7eb"}}),s.jsx("span",{children:"No data"})]})]}),f?s.jsx("div",{style:Nt.loading,children:"Loading calendar data..."}):s.jsx(s.Fragment,{children:s.jsxs("div",{style:Nt.calendar,children:[RJ.map(_=>s.jsx("div",{style:Nt.dayHeader,children:_},_)),x.map((_,b)=>{if(_===null)return s.jsx("div",{style:Nt.emptyCell},`empty-${b}`);const C=new Date(_.date).getDate(),T=_.date===e.toISOString().split("T")[0];let F={...Nt.dayCell};return _.has_data&&(_.is_forecast?F={...F,...Nt.forecastCell}:F={...F,...Nt.historicalCell}),T&&(F={...F,...Nt.todayCell}),s.jsxs("div",{style:F,onClick:()=>_.has_data&&l(_),children:[s.jsx("div",{style:Nt.dayNumber,children:C}),_.has_data&&s.jsxs("div",{style:Nt.dayData,children:[_.total_revenue!==null&&s.jsxs("div",{style:Nt.revenueTag,children:[c,Math.round(_.total_revenue)," net"]}),_.occupied_rooms!==null&&s.jsxs("div",{style:Nt.occupancyTag,children:[_.occupied_rooms,"/",_.total_rooms," (",_.total_guests??"-",") ",Math.round(_.occupancy_percentage??0),"%"]})]})]},_.date)})]})}),a&&s.jsx("div",{style:Nt.modalOverlay,onClick:()=>l(null),children:s.jsxs("div",{style:Nt.modal,onClick:_=>_.stopPropagation(),children:[s.jsxs("div",{style:Nt.modalHeader,children:[s.jsx("h3",{style:Nt.modalTitle,children:S(a.date)}),s.jsx("span",{style:{...Nt.badge,background:a.is_forecast?"#fbbf24":"#4ade80",color:a.is_forecast?"#78350f":"#14532d"},children:a.is_forecast?"Forecast":"Historical"})]}),s.jsxs("div",{style:Nt.modalContent,children:[s.jsxs("div",{style:Nt.section,children:[s.jsx("h4",{style:Nt.sectionTitle,children:"Occupancy"}),s.jsxs("div",{style:Nt.dataGrid,children:[s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Occupancy Rate"}),s.jsx("span",{style:Nt.dataValue,children:a.occupancy_percentage!==null?`${a.occupancy_percentage}%`:"-"})]}),s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Rooms"}),s.jsx("span",{style:Nt.dataValue,children:a.occupied_rooms!==null&&a.total_rooms!==null?`${a.occupied_rooms} / ${a.total_rooms}`:"-"})]}),s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Total Guests"}),s.jsx("span",{style:Nt.dataValue,children:a.total_guests??"-"})]})]})]}),s.jsxs("div",{style:Nt.section,children:[s.jsx("h4",{style:Nt.sectionTitle,children:"Meal Allocations"}),s.jsxs("div",{style:Nt.dataGrid,children:[s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Breakfast"}),s.jsx("span",{style:Nt.dataValue,children:a.breakfast_allocation_qty!==null?`${a.breakfast_allocation_qty} pax`:"-"}),a.is_forecast&&a.breakfast_allocation_netvalue!==null&&s.jsxs("span",{style:Nt.dataSubValue,children:[w(a.breakfast_allocation_netvalue)," net (est)"]})]}),s.jsxs("div",{style:Nt.dataItem,children:[s.jsx("span",{style:Nt.dataLabel,children:"Dinner"}),s.jsx("span",{style:Nt.dataValue,children:a.dinner_allocation_qty!==null?`${a.dinner_allocation_qty} pax`:"-"}),a.is_forecast&&a.dinner_allocation_netvalue!==null&&s.jsxs("span",{style:Nt.dataSubValue,children:[w(a.dinner_allocation_netvalue)," net (est)"]})]})]})]}),s.jsxs("div",{style:Nt.section,children:[s.jsx("h4",{style:Nt.sectionTitle,children:"Revenue (net)"}),s.jsxs("div",{style:Nt.revenueTotal,children:[s.jsx("span",{children:"Total"}),s.jsx("span",{style:Nt.revenueTotalValue,children:w(a.total_revenue)})]}),a.revenue_by_account&&a.revenue_by_account.length>0&&s.jsx("div",{style:Nt.revenueBreakdown,children:a.revenue_by_account.map((_,b)=>s.jsxs("div",{style:Nt.revenueItem,children:[s.jsx("span",{style:Nt.revenueGLName,children:_.gl_name}),s.jsx("span",{style:Nt.revenueAmount,children:w(_.amount)})]},b))})]})]}),s.jsx("button",{onClick:()=>l(null),style:Nt.closeBtn,children:"Close"})]})})]})}const Nt={container:{padding:"1rem"},titleRow:{marginBottom:"1rem"},backLink:{display:"inline-block",color:"#6b7280",textDecoration:"none",fontSize:"0.875rem",marginBottom:"0.5rem"},title:{fontSize:"1.75rem",fontWeight:"bold",marginBottom:"0.5rem",color:"#1a1a2e",margin:0},calendarHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},monthTitle:{display:"flex",alignItems:"center",gap:"1rem"},monthName:{fontSize:"1.5rem",fontWeight:"600",color:"#1a1a2e",margin:0},navBtn:{padding:"0.5rem 1rem",background:"#f3f4f6",border:"1px solid #d1d5db",borderRadius:"6px",cursor:"pointer",fontWeight:"500"},todayBtn:{padding:"0.25rem 0.75rem",background:"#e94560",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.875rem"},legend:{display:"flex",gap:"1.5rem",marginBottom:"1rem",padding:"0.75rem 1rem",background:"#f9fafb",borderRadius:"8px"},legendItem:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.875rem",color:"#4b5563"},legendDot:{width:"16px",height:"16px",borderRadius:"4px"},loading:{textAlign:"center",padding:"3rem",color:"#6b7280"},calendar:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:"4px",background:"#e5e7eb",borderRadius:"12px",padding:"4px"},dayHeader:{padding:"0.75rem",textAlign:"center",fontWeight:"600",color:"#374151",background:"#f9fafb"},emptyCell:{background:"#f9fafb",minHeight:"100px"},dayCell:{background:"white",minHeight:"100px",padding:"0.5rem",cursor:"default",position:"relative",borderRadius:"4px"},historicalCell:{background:"#dcfce7",cursor:"pointer"},forecastCell:{background:"#fef3c7",cursor:"pointer"},todayCell:{boxShadow:"inset 0 0 0 2px #e94560"},dayNumber:{fontWeight:"600",fontSize:"0.875rem",color:"#374151"},dayData:{marginTop:"0.5rem",display:"flex",flexDirection:"column",gap:"0.25rem"},revenueTag:{fontSize:"0.75rem",color:"#047857",fontWeight:"500"},occupancyTag:{fontSize:"0.75rem",color:"#6366f1",fontWeight:"500"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0, 0, 0, 0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",padding:"1.5rem",width:"90%",maxWidth:"500px",maxHeight:"80vh",overflow:"auto",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",paddingBottom:"1rem",borderBottom:"1px solid #e5e7eb"},modalTitle:{margin:0,fontSize:"1.25rem",fontWeight:"600",color:"#1a1a2e"},badge:{padding:"0.25rem 0.75rem",borderRadius:"9999px",fontSize:"0.75rem",fontWeight:"600"},modalContent:{display:"flex",flexDirection:"column",gap:"1.5rem"},section:{background:"#f9fafb",borderRadius:"8px",padding:"1rem"},sectionTitle:{margin:"0 0 0.75rem 0",fontSize:"0.875rem",fontWeight:"600",color:"#6b7280",textTransform:"uppercase",letterSpacing:"0.05em"},dataGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(120px, 1fr))",gap:"1rem"},dataItem:{display:"flex",flexDirection:"column",gap:"0.25rem"},dataLabel:{fontSize:"0.75rem",color:"#6b7280"},dataValue:{fontSize:"1.125rem",fontWeight:"600",color:"#1a1a2e"},dataSubValue:{fontSize:"0.875rem",color:"#6b7280"},revenueTotal:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem",background:"white",borderRadius:"6px",marginBottom:"0.75rem"},revenueTotalValue:{fontSize:"1.25rem",fontWeight:"700",color:"#047857"},revenueBreakdown:{display:"flex",flexDirection:"column",gap:"0.5rem"},revenueItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0.75rem",background:"white",borderRadius:"4px",fontSize:"0.875rem"},revenueGLName:{color:"#4b5563"},revenueAmount:{fontWeight:"500",color:"#1a1a2e"},closeBtn:{width:"100%",padding:"0.75rem",marginTop:"1.5rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"500"}},IJ=["January","February","March","April","May","June","July","August","September","October","November","December"],MJ=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];function zJ(){const{token:n}=gn(),[e,t]=K_(),r=new Date,[i,o]=k.useState(r.getFullYear()),[a,l]=k.useState(r.getMonth()+1),[d,c]=k.useState(null),[u,f]=k.useState(new Set),[p,g]=k.useState("all");k.useEffect(()=>{const ee=e.get("date");if(ee&&/^\d{4}-\d{2}-\d{2}$/.test(ee)){const Z=new Date(ee);o(Z.getFullYear()),l(Z.getMonth()+1),c(ee),t({},{replace:!0})}},[]);const[m,y]=k.useState(!1),[v,x]=k.useState(null),[w,S]=k.useState({event_date:"",event_type:"reminder",title:"",description:""});k.useEffect(()=>{f(new Set)},[d]);const{data:_}=Oe({queryKey:["resos-settings"],queryFn:async()=>{const ee=await fetch("/api/resos/settings",{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch settings");return ee.json()},enabled:!!n}),{data:b,isLoading:C}=Oe({queryKey:["resos-daily-stats",i,a],queryFn:async()=>{const ee=`${i}-${String(a).padStart(2,"0")}-01`,Z=new Date(i,a,0),ge=`${i}-${String(a).padStart(2,"0")}-${String(Z.getDate()).padStart(2,"0")}`,Te=await fetch(`/api/resos/daily-stats?from_date=${ee}&to_date=${ge}`,{headers:{Authorization:`Bearer ${n}`}});if(!Te.ok)throw new Error("Failed to fetch daily stats");return Te.json()},enabled:!!n}),{data:T}=Oe({queryKey:["resos-stats-prev",i,a],queryFn:async()=>{const ee=a===1?12:a-1,Z=a===1?i-1:i,ge=`${Z}-${String(ee).padStart(2,"0")}-01`,Te=new Date(Z,ee,0),Be=`${Z}-${String(ee).padStart(2,"0")}-${String(Te.getDate()).padStart(2,"0")}`,he=await fetch(`/api/resos/daily-stats?from_date=${ge}&to_date=${Be}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch previous month stats");return he.json()},enabled:!!n}),{data:F,refetch:A}=Oe({queryKey:["calendar-events",i,a],queryFn:async()=>{const ee=`${i}-${String(a).padStart(2,"0")}-01`,Z=new Date(i,a,0),ge=`${i}-${String(a).padStart(2,"0")}-${String(Z.getDate()).padStart(2,"0")}`,Te=await fetch(`/api/calendar-events/?from_date=${ee}&to_date=${ge}`,{headers:{Authorization:`Bearer ${n}`}});if(!Te.ok)throw new Error("Failed to fetch calendar events");return Te.json()},enabled:!!n}),{data:D}=Oe({queryKey:["resos-bookings",d],queryFn:async()=>{if(!d)return[];const ee=await fetch(`/api/resos/bookings/${d}`,{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch bookings");return ee.json()},enabled:!!n&&!!d}),{data:P}=Oe({queryKey:["resos-all-opening-hours"],queryFn:async()=>{const ee=await fetch("/api/resos/opening-hours",{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch opening hours");return ee.json()},enabled:!!n}),L=P!=null&&P.opening_hours?(()=>{const ee=P.opening_hours.filter(he=>!he.special);if(ee.length===0)return null;let Z=2400,ge=0;ee.forEach(he=>{const He=he.open||0,Ge=he.close||0;Hege&&(ge=Ge)});const Te=Math.floor(Z/100);let Be=Math.floor(ge/100);return ge%100>0&&Be++,{startHour:Te,endHour:Be}})():null,{data:W}=Oe({queryKey:["resos-opening-hours",d],queryFn:async()=>{if(!d)return[];const ee=await fetch(`/api/resos/opening-hours/${d}`,{headers:{Authorization:`Bearer ${n}`}});if(!ee.ok)throw new Error("Failed to fetch opening hours");return ee.json()},enabled:!!d&&!!n}),O=()=>{a===1?(l(12),o(i-1)):l(a-1)},U=()=>{a===12?(l(1),o(i+1)):l(a+1)},M=()=>{o(r.getFullYear()),l(r.getMonth()+1)},I=ee=>{if(!(_!=null&&_.resos_opening_hours_mapping))return ee;const Z=_.resos_opening_hours_mapping.find(ge=>{var Te;return((Te=ge.display_name)==null?void 0:Te.toLowerCase())===ee.toLowerCase()});return Z!=null&&Z.service_type?Z.service_type.charAt(0).toUpperCase()+Z.service_type.slice(1):ee},H=ee=>{const Z=(_==null?void 0:_.resos_flag_icon_mapping)||{},ge={allergies:"🦀",large_group:"👥",note_keyword_birthday:"🎂",note_keyword_anniversary:"💍"};if(Z[ee])return Z[ee];if(ee.startsWith("note_keyword_")){const Te=ee.replace("note_keyword_","");if(Z[Te])return Z[Te]}return ge[ee]?ge[ee]:"⚠️"},z=ee=>{if(!ee)return"⚠️";const Z=ee.split(",").map(ge=>ge.trim());return H(Z[0])},G=ee=>ee?ee.split(",").map(ge=>ge.trim().toLowerCase()).includes("notes"):!1,te=ee=>{if(!ee||!(_!=null&&_.resos_note_keywords))return{hasKeywords:!1,matchedKeyword:null};const Z=_.resos_note_keywords.split(",").map(Te=>Te.trim().toLowerCase()),ge=ee.toLowerCase();for(const Te of Z)if(ge.includes(Te))return{hasKeywords:!0,matchedKeyword:Te};return{hasKeywords:!1,matchedKeyword:null}},re=ee=>{const Z=(_==null?void 0:_.resos_large_group_threshold)||8;return ee>=Z},me=()=>H("large_group"),J=ee=>{f(Z=>{const ge=new Set(Z);return ge.has(ee)?ge.delete(ee):ge.add(ee),ge})},ne=ee=>{if(!ee||ee.length===0)return[];const Z=new Set;for(const ge of ee){const Te=H(ge);Z.add(Te)}return Array.from(Z)},ye=new Map;b==null||b.forEach(ee=>{ye.set(ee.date,ee)});const ke=new Date(i,a-1,1),Ye=new Date(i,a,0),De=(ke.getDay()+6)%7,qe=Ye.getDate(),ue=[];for(let ee=0;ee{const Z=ee.event_date;Ze.has(Z)||Ze.set(Z,[]),Ze.get(Z).push(ee)}),s.jsxs("div",{style:ht.container,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsxs("div",{children:[s.jsx("h1",{style:ht.title,children:"Restaurant Calendar"}),s.jsx("p",{style:ht.subtitle,children:"View synced booking data, covers, and flagged reservations from Resos"})]}),s.jsx("button",{onClick:()=>{x(null),S({event_date:new Date().toISOString().split("T")[0],event_type:"reminder",title:"",description:""}),y(!0)},style:{...ht.todayButton,padding:"0.75rem 1.5rem",fontSize:"0.95rem"},children:"+ Create Event"})]}),s.jsxs("div",{style:ht.navBar,children:[s.jsx("button",{onClick:O,style:ht.navButton,children:"← Previous"}),s.jsxs("div",{style:ht.monthYearDisplay,children:[IJ[a-1]," ",i]}),s.jsx("button",{onClick:M,style:ht.todayButton,children:"Today"}),s.jsx("button",{onClick:U,style:ht.navButton,children:"Next →"})]}),C?s.jsx("div",{style:ht.loading,children:"Loading calendar data..."}):s.jsxs("div",{style:ht.calendar,children:[s.jsx("div",{style:ht.calendarHeader,children:MJ.map(ee=>s.jsx("div",{style:ht.dayHeader,children:ee},ee))}),s.jsx("div",{style:ht.calendarGrid,children:ue.map((ee,Z)=>{if(!ee)return s.jsx("div",{style:ht.emptyCell},`empty-${Z}`);const ge=`${i}-${String(a).padStart(2,"0")}-${String(ee.getDate()).padStart(2,"0")}`,Te=ye.get(ge),Be=ge===r.toISOString().split("T")[0],he=((Te==null?void 0:Te.flagged_booking_count)||0)>0,He=Ze.has(ge);return s.jsxs("div",{style:{...ht.dayCell,...Te?ht.dayCellWithData:{},...Be?ht.dayCellToday:{},...he?ht.dayCellFlagged:{},...Te!=null&&Te.is_forecast?ht.dayCellForecast:{}},onClick:()=>Te&&c(ge),children:[s.jsxs("div",{style:ht.dayNumber,children:[ee.getDate(),He&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.9rem"},children:"⭐"}),he&&s.jsx("span",{style:ht.flagIcon,children:ne((Te==null?void 0:Te.unique_flag_types)||null).map((Ge,ae)=>s.jsx("span",{children:Ge},ae))})]}),Te&&s.jsxs("div",{style:ht.dayStats,children:[s.jsxs("div",{style:ht.statLine,children:[s.jsx("strong",{children:Te.total_bookings})," bookings"]}),s.jsxs("div",{style:ht.statLine,children:[s.jsx("strong",{children:Te.total_covers})," covers"]}),Te.service_breakdown.length>0&&s.jsx("div",{style:ht.serviceBreakdown,children:Te.service_breakdown.map(Ge=>s.jsxs("div",{style:ht.serviceLine,children:[I(Ge.period),": ",Ge.bookings," : ",Ge.covers]},Ge.period))})]})]},ge)})}),b&&T&&s.jsxs("div",{style:ht.chartContainer,children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsx("h3",{style:ht.chartTitle,children:"Current vs Previous Month"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("label",{htmlFor:"serviceTypeFilter",style:{fontSize:"0.9rem",fontWeight:"600"},children:"Service Type:"}),s.jsxs("select",{id:"serviceTypeFilter",value:p,onChange:ee=>g(ee.target.value),style:{padding:"0.5rem",borderRadius:"4px",border:"1px solid #ccc",fontSize:"0.9rem",cursor:"pointer"},children:[s.jsx("option",{value:"all",children:"All Services"}),s.jsx("option",{value:"breakfast",children:"Breakfast"}),s.jsx("option",{value:"lunch",children:"Lunch"}),s.jsx("option",{value:"dinner",children:"Dinner"}),s.jsx("option",{value:"other",children:"Other"})]})]})]}),(()=>{const ee=new Date(i,a,0).getDate(),Z=a===1?12:a-1,ge=a===1?i-1:i,Te=Le=>{if(p==="all")return{bookings:Le.total_bookings,covers:Le.total_covers};const rt=Le.service_breakdown.find($e=>$e.period.toLowerCase()===p);return rt?{bookings:rt.bookings,covers:rt.covers}:{bookings:0,covers:0}},Be=new Array(ee).fill(0),he=new Array(ee).fill(0),He=new Array(ee).fill(0),Ge=new Array(ee).fill(0);b.forEach(Le=>{const rt=new Date(Le.date).getDate(),{bookings:$e,covers:ce}=Te(Le);Be[rt-1]=$e,he[rt-1]=ce});const ae=new Map;T.forEach(Le=>{const{bookings:rt,covers:$e}=Te(Le);ae.set(Le.date,{bookings:rt,covers:$e})});const de=new Date(i,a-1,1).getDay();let Y=new Date(ge,Z-1,1);for(;Y.getDay()!==de;)Y.setDate(Y.getDate()+1);for(let Le=1;Le<=ee;Le++){const rt=Le-1,$e=new Date(Y);$e.setDate(Y.getDate()+rt);const ce=$e.toISOString().split("T")[0],Je=ae.get(ce);Je&&(He[Le-1]=Je.bookings,Ge[Le-1]=Je.covers)}const Q={};for(let Le=0;Le<7;Le++)Q[Le]={bookings:[],covers:[]};T.forEach(Le=>{const $e=new Date(Le.date).getDay(),{bookings:ce,covers:Je}=Te(Le);Q[$e].bookings.push(ce),Q[$e].covers.push(Je)});const X={};for(let Le=0;Le<7;Le++){const rt=Q[Le].bookings,$e=Q[Le].covers;X[Le]={bookings:rt.length>0?rt.reduce((ce,Je)=>ce+Je,0)/rt.length:0,covers:$e.length>0?$e.reduce((ce,Je)=>ce+Je,0)/$e.length:0}}const pe=new Array(ee).fill(0);for(let Le=1;Le<=ee;Le++){const $e=new Date(i,a-1,Le).getDay();pe[Le-1]=X[$e].covers}const we=Math.max(...Be,...He,...he,...Ge,...pe,10),Ne=300,st="100%",Ve=50,Re=1200;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{width:st,height:Ne,viewBox:`0 0 ${Re} ${Ne}`,preserveAspectRatio:"xMidYMid meet",style:ht.chart,children:[[0,.25,.5,.75,1].map(Le=>s.jsx("line",{x1:Ve,y1:Ve+(Ne-2*Ve)*Le,x2:Re-Ve,y2:Ve+(Ne-2*Ve)*Le,stroke:"#e0e0e0",strokeWidth:"1"},Le)),Array.from({length:ee},(Le,rt)=>{const $e=rt+1;if(new Date(i,a-1,$e).getDay()===0){const jt=Ve+(Re-2*Ve)/(ee-1)*rt;return s.jsx("line",{x1:jt,y1:Ve,x2:jt,y2:Ne-Ve,stroke:"#999",strokeWidth:"1",strokeDasharray:"3,3"},`sunday-${$e}`)}return null}),s.jsx("polyline",{points:Be.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-He[rt]/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#93c5fd",strokeWidth:"2",strokeDasharray:"5,5"}),s.jsx("polyline",{points:Be.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#3b82f6",strokeWidth:"3"}),Be.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return s.jsx("circle",{cx:$e,cy:ce,r:"3",fill:"#3b82f6",stroke:"white",strokeWidth:"1"},`booking-point-${rt}`)}),s.jsx("polyline",{points:he.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Ge[rt]/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#86efac",strokeWidth:"2",strokeDasharray:"5,5"}),s.jsx("polyline",{points:he.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#10b981",strokeWidth:"3"}),he.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return s.jsx("circle",{cx:$e,cy:ce,r:"3",fill:"#10b981",stroke:"white",strokeWidth:"1"},`cover-point-${rt}`)}),s.jsx("polyline",{points:pe.map((Le,rt)=>{const $e=Ve+(Re-2*Ve)/(ee-1)*rt,ce=Ve+(Ne-2*Ve)*(1-Le/we);return`${$e},${ce}`}).join(" "),fill:"none",stroke:"#f97316",strokeWidth:"2",strokeDasharray:"3,3"}),s.jsx("text",{x:Ve-10,y:Ve,textAnchor:"end",fontSize:"12",fill:"#666",children:we}),s.jsx("text",{x:Ve-10,y:Ve+(Ne-2*Ve)*.5,textAnchor:"end",fontSize:"12",fill:"#666",children:Math.round(we/2)}),s.jsx("text",{x:Ve-10,y:Ne-Ve,textAnchor:"end",fontSize:"12",fill:"#666",children:"0"}),Array.from({length:Math.ceil(ee/5)},(Le,rt)=>{const $e=rt*5+1;if($e>ee)return null;const ce=Ve+(Re-2*Ve)/(ee-1)*($e-1);return s.jsx("text",{x:ce,y:Ne-Ve+20,textAnchor:"middle",fontSize:"11",fill:"#666",children:$e},$e)})]}),s.jsxs("div",{style:ht.chartLegend,children:[s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,background:"#3b82f6"}}),"Current Bookings"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,height:"2px",borderTop:"2px dashed #93c5fd",background:"transparent"}}),"Previous Bookings"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,background:"#10b981"}}),"Current Covers"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,height:"2px",borderTop:"2px dashed #86efac",background:"transparent"}}),"Previous Covers"]}),s.jsxs("span",{style:ht.legendItem,children:[s.jsx("span",{style:{...ht.legendLine,height:"2px",borderTop:"2px dashed #f97316",background:"transparent"}}),"Avg Day-of-Week Covers"]})]})]})})()]})]}),d&&D&&s.jsx("div",{style:ht.modalOverlay,onClick:()=>c(null),children:s.jsxs("div",{style:ht.modal,onClick:ee=>ee.stopPropagation(),children:[s.jsxs("div",{style:ht.modalHeader,children:[s.jsxs("h2",{children:["Bookings for ",d]}),s.jsx("button",{onClick:()=>c(null),style:ht.closeBtn,children:"×"})]}),s.jsxs("div",{style:ht.modalContent,children:[(()=>{const ee=Ze.get(d)||[];return ee.length>0?s.jsxs("div",{style:{marginBottom:"2rem"},children:[s.jsx("h3",{style:{marginBottom:"1rem"},children:"Events & Reminders"}),ee.map(Z=>s.jsxs("div",{style:{padding:"1rem",background:Z.event_type==="reminder"?"#fff3cd":Z.event_type==="event"?"#d1ecf1":"#f8f9fa",borderLeft:`4px solid ${Z.event_type==="reminder"?"#ffc107":Z.event_type==="event"?"#0dcaf0":"#6c757d"}`,borderRadius:"4px",marginBottom:"0.5rem",display:"flex",justifyContent:"space-between",alignItems:"start"},children:[s.jsxs("div",{children:[s.jsxs("div",{style:{fontWeight:"bold",marginBottom:"0.25rem"},children:[Z.event_type.toUpperCase(),": ",Z.title]}),Z.description&&s.jsx("div",{style:{fontSize:"0.9rem",color:"#666"},children:Z.description})]}),s.jsx("button",{onClick:()=>{x(Z),S({event_date:Z.event_date,event_type:Z.event_type,title:Z.title,description:Z.description||""}),y(!0)},style:{padding:"0.5rem 1rem",background:"#667eea",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"Edit"})]},Z.id))]}):null})(),(()=>{let ee=18,Z=22;if(L)ee=L.startHour,Z=L.endHour;else if(D.length>0){const K=D.map(Q=>{const[X,pe]=Q.booking_time.split(":").map(Number);return X*60+pe}),de=Math.min(...K),Y=Math.max(...K)+120;ee=Math.floor(de/60),Z=Math.ceil(Y/60)}const ge=(Z-ee)*60,Te=[...D].sort((K,de)=>{const Y=parseInt(K.booking_time.replace(/:/g,"")),Q=parseInt(de.booking_time.replace(/:/g,""));return Y-Q}),Be=[],he=Te.map(K=>{const[de,Y]=K.booking_time.split(":").map(Number),Q=(de-ee)*60+Y,X=Q+120,pe=K.people,we=Math.max(1,Math.floor(pe/4)+1);let Ne=0,st=!1;for(;!st;){for(;Be.length=Le.end+5)){Ve=!1;break}if(!Ve)break}if(Ve){for(let Re=Ne;Re{const K=[];if(!W||W.length===0)return K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:"0%",width:"100%",height:Ge}},"full-closed")),K;const de=[...W].sort((st,Ve)=>st.open-Ve.open),Y=de[0].open,X=Math.floor(Y/100)*60+Y%100-ee*60;if(X>0){const st=X/ge*100;K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:"0%",width:`${st}%`,height:Ge}},"before-open"))}for(let st=0;st0){const jt=$e/ge*100,ct=Je/ge*100;K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:`${jt}%`,width:`${ct}%`,height:Ge}},`gap-${st}`))}}const pe=de[de.length-1].close,we=Math.floor(pe/100)*60+pe%100,Ne=Z*60-we;if(Ne>0){const st=(we-ee*60)/ge*100,Ve=Ne/ge*100;K.push(s.jsx("div",{style:{...ht.ganttClosedBlock,left:`${st}%`,width:`${Ve}%`,height:Ge}},"after-close"))}return K};return s.jsxs("div",{style:ht.ganttContainer,children:[s.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem"},children:"Timeline"}),s.jsx("div",{style:ht.ganttTimeAxis,children:Array.from({length:Z-ee},(K,de)=>ee+de).flatMap(K=>[s.jsxs("div",{style:{...ht.ganttTimeLabel,left:`${(K-ee)*60/ge*100}%`},children:[K,":00"]},`${K}-00`),s.jsxs("div",{style:{...ht.ganttTimeLabel,left:`${((K-ee)*60+30)/ge*100}%`},children:[K,":30"]},`${K}-30`)])}),s.jsxs("div",{style:{...ht.ganttBookings,height:Ge},children:[ae(),Array.from({length:Math.floor(ge/15)},(K,de)=>(de+1)*15).map(K=>s.jsx("div",{style:{...ht.ganttIntervalLine,left:`${K/ge*100}%`,height:Ge}},K)),he.map(K=>{const de=K.bookingStart/ge*100,Y=(Math.min(K.bookingEnd,ge)-K.bookingStart)/ge*100,Q=10+K.gridRow*He,X=K.rowSpan*He-4,pe=K.table_name||"",we=re(K.people),Ne=K.is_flagged?z(K.flag_reasons):we?me():"";return s.jsxs("div",{style:{...ht.ganttBookingBar,left:`${de}%`,width:`${Y}%`,top:Q,height:X},title:`${K.booking_time} - ${I(K.opening_hour_name||"")} - ${K.people} covers${K.table_name?` - Table ${K.table_name}`:""}${K.allergies?` -🦀 ${K.allergies}`:""}${K.notes?` -📝 ${K.notes}`:""}`,children:[s.jsx("span",{style:ht.ganttPartySize,children:K.people}),Ne&&s.jsx("span",{children:Ne}),pe&&s.jsx("span",{style:ht.ganttBarText,children:pe})]},K.id)})]})]})})(),s.jsxs("h3",{children:["All Bookings (",D.length,")"]}),s.jsx("div",{style:ht.tableContainer,children:(()=>{const ee=D.reduce((ge,Te)=>{const Be=I(Te.opening_hour_name||"Unknown");return ge[Be]||(ge[Be]=[]),ge[Be].push(Te),ge},{});return Object.entries(ee).map(([ge,Te])=>{var Be;return{period:ge,bookings:Te.sort((he,He)=>he.booking_time.localeCompare(He.booking_time)),firstTime:((Be=Te[0])==null?void 0:Be.booking_time)||""}}).sort((ge,Te)=>ge.firstTime.localeCompare(Te.firstTime)).map(({period:ge,bookings:Te})=>s.jsxs("div",{style:ht.serviceGroup,children:[s.jsx("h4",{style:ht.serviceGroupTitle,children:ge}),s.jsxs("table",{style:ht.bookingsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:ht.th,children:"Time"}),s.jsx("th",{style:ht.th,children:"Area"}),s.jsx("th",{style:ht.th,children:"Table"}),s.jsx("th",{style:ht.th,children:"Covers"}),s.jsx("th",{style:ht.th,children:"Hotel Guest"}),s.jsx("th",{style:ht.th,children:"DBB/Package"}),s.jsx("th",{style:ht.th,children:"Allergies"}),s.jsx("th",{style:ht.th,children:"Notes"})]})}),s.jsx("tbody",{children:Te.map(Be=>{var we;const he=Be.allergies&&((we=Be.flag_reasons)!=null&&we.includes("allergies"))?z("allergies"):"",He=Be.notes?"📝":"",Ge=G(Be.flag_reasons),ae=u.has(Be.id),K=Be.notes&&(ae||Ge),de=re(Be.people),Y=de?me():"",{hasKeywords:Q,matchedKeyword:X}=te(Be.notes),pe=Q&&X?H(`note_keyword_${X}`):"";return s.jsxs(nF.Fragment,{children:[s.jsxs("tr",{children:[s.jsx("td",{style:ht.td,children:Be.booking_time}),s.jsx("td",{style:ht.td,children:Be.seating_area||"-"}),s.jsx("td",{style:ht.td,children:Be.table_name||"-"}),s.jsxs("td",{style:de?ht.highlightCell:ht.td,children:[Be.people,Y&&s.jsx("span",{style:{marginLeft:"0.25rem"},children:Y})]}),s.jsx("td",{style:ht.td,children:Be.is_hotel_guest?"✓":"-"}),s.jsx("td",{style:ht.td,children:Be.is_dbb&&Be.is_package?"DBB + Pkg":Be.is_dbb?"DBB":Be.is_package?"Package":"-"}),s.jsxs("td",{style:Be.allergies?ht.highlightCell:ht.td,children:[he&&s.jsx("span",{style:{marginRight:"0.25rem"},children:he}),Be.allergies||"-"]}),s.jsxs("td",{style:Ge||Q?ht.highlightCell:ht.td,onClick:()=>Be.notes&&J(Be.id),children:[He&&s.jsx("span",{style:ht.clickableIcon,children:He}),pe&&s.jsx("span",{style:{...ht.clickableIcon,marginLeft:"0.25rem"},children:pe}),!Be.notes&&"-"]})]}),K&&s.jsxs("tr",{children:[s.jsx("td",{colSpan:4,style:ht.emptyIndentCell}),s.jsxs("td",{colSpan:4,style:ht.notesRow,children:[s.jsx("strong",{children:"Notes:"})," ",Be.notes]})]},`${Be.id}-notes`),Be.allergies&&s.jsxs("tr",{children:[s.jsx("td",{colSpan:4,style:ht.emptyIndentCell}),s.jsxs("td",{colSpan:4,style:ht.allergiesRow,children:[s.jsx("strong",{children:"Allergies:"})," ",Be.allergies]})]},`${Be.id}-allergies`)]},Be.id)})})]})]},ge))})()})]})]})}),m&&s.jsx("div",{style:ht.modalOverlay,onClick:()=>y(!1),children:s.jsxs("div",{style:{...ht.modal,maxWidth:"600px"},onClick:ee=>ee.stopPropagation(),children:[s.jsxs("div",{style:ht.modalHeader,children:[s.jsx("h2",{children:v?"Edit Event":"Create Event"}),s.jsx("button",{onClick:()=>y(!1),style:ht.closeBtn,children:"×"})]}),s.jsx("div",{style:ht.modalContent,children:s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Date"}),s.jsx("input",{type:"date",value:w.event_date,onChange:ee=>S({...w,event_date:ee.target.value}),style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Type"}),s.jsxs("select",{value:w.event_type,onChange:ee=>S({...w,event_type:ee.target.value}),style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd"},children:[s.jsx("option",{value:"reminder",children:"Reminder"}),s.jsx("option",{value:"event",children:"Event"}),s.jsx("option",{value:"note",children:"Note"})]})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Title"}),s.jsx("input",{type:"text",value:w.title,onChange:ee=>S({...w,title:ee.target.value}),placeholder:"Event title...",style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd"}})]}),s.jsxs("div",{children:[s.jsx("label",{style:{display:"block",marginBottom:"0.5rem",fontWeight:"bold"},children:"Description"}),s.jsx("textarea",{value:w.description,onChange:ee=>S({...w,description:ee.target.value}),placeholder:"Optional description...",rows:4,style:{width:"100%",padding:"0.5rem",borderRadius:"4px",border:"1px solid #ddd",resize:"vertical"}})]}),s.jsxs("div",{style:{display:"flex",gap:"1rem",justifyContent:"flex-end"},children:[v&&s.jsx("button",{onClick:async()=>{confirm("Delete this event?")&&(await fetch(`/api/calendar-events/${v.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}}),y(!1),A())},style:{padding:"0.75rem 1.5rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},children:"Delete"}),s.jsx("button",{onClick:()=>y(!1),style:{padding:"0.75rem 1.5rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},children:"Cancel"}),s.jsx("button",{onClick:async()=>{const ee=v?`/api/calendar-events/${v.id}`:"/api/calendar-events/";await fetch(ee,{method:v?"PUT":"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(w)}),y(!1),A()},disabled:!w.title||!w.event_date,style:{padding:"0.75rem 1.5rem",background:!w.title||!w.event_date?"#ccc":"#667eea",color:"white",border:"none",borderRadius:"6px",cursor:!w.title||!w.event_date?"not-allowed":"pointer",fontWeight:"bold"},children:v?"Update":"Create"})]})]})})]})})]})}const ht={container:{padding:"2rem",maxWidth:"1400px",margin:"0 auto"},title:{fontSize:"2rem",fontWeight:"bold",marginBottom:"0.5rem"},subtitle:{color:"#666",marginBottom:"2rem"},navBar:{display:"flex",alignItems:"center",gap:"1rem",marginBottom:"2rem",padding:"1rem",background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},navButton:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:500},todayButton:{padding:"0.5rem 1rem",background:"#0066cc",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:500},monthYearDisplay:{fontSize:"1.5rem",fontWeight:"bold",flex:1,textAlign:"center"},loading:{padding:"2rem",textAlign:"center",background:"white",borderRadius:"8px"},calendar:{background:"white",borderRadius:"8px",padding:"1rem",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},calendarHeader:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:"0.5rem",marginBottom:"0.5rem"},dayHeader:{padding:"0.5rem",textAlign:"center",fontWeight:"bold",color:"#666"},calendarGrid:{display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:"0.5rem"},emptyCell:{minHeight:"100px"},dayCell:{minHeight:"100px",padding:"0.5rem",border:"1px solid #e0e0e0",borderRadius:"4px",cursor:"default",background:"#fafafa"},dayCellWithData:{background:"white",cursor:"pointer",transition:"transform 0.2s, box-shadow 0.2s"},dayCellToday:{borderColor:"#0066cc",borderWidth:"2px"},dayCellFlagged:{borderLeftColor:"#e94560",borderLeftWidth:"4px"},dayCellForecast:{background:"#f0f8ff"},dayNumber:{fontSize:"1.1rem",fontWeight:"bold",marginBottom:"0.5rem",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.25rem"},flagIcon:{fontSize:"1rem"},dayStats:{fontSize:"0.85rem",color:"#333"},statLine:{marginBottom:"0.25rem"},serviceBreakdown:{marginTop:"0.5rem",fontSize:"0.75rem",color:"#666"},serviceLine:{marginBottom:"0.2rem"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",width:"90%",maxWidth:"1000px",maxHeight:"90vh",overflow:"hidden",display:"flex",flexDirection:"column",padding:"2rem"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",paddingBottom:"1rem",borderBottom:"2px solid #e0e0e0",flexShrink:0},closeBtn:{background:"none",border:"none",fontSize:"2rem",cursor:"pointer",color:"#666",lineHeight:1},modalContent:{marginTop:"1rem",flex:1,overflowY:"scroll",scrollbarGutter:"stable",paddingRight:"0.5rem"},tableContainer:{overflowX:"auto",marginTop:"1rem"},bookingsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",fontWeight:"bold",background:"#f8f9fa"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},serviceGroup:{marginBottom:"1.5rem"},serviceGroupTitle:{fontSize:"1.1rem",fontWeight:"bold",marginBottom:"0.5rem",padding:"0.5rem",background:"#f0f0f0",borderRadius:"4px"},highlightCell:{padding:"0.75rem",borderBottom:"1px solid #eee",background:"#fffbcc"},clickableIcon:{cursor:"pointer",userSelect:"none",fontSize:"1.2rem"},emptyIndentCell:{padding:0,borderTop:"none",borderBottom:"2px solid #ddd",background:"transparent"},notesRow:{padding:"0.75rem",background:"#f8f9fa",borderTop:"none",borderBottom:"2px solid #ddd",fontSize:"0.9rem",fontStyle:"italic",color:"#555"},allergiesRow:{padding:"0.75rem",background:"#fff3cd",borderTop:"none",borderBottom:"2px solid #ddd",fontSize:"0.9rem",color:"#856404"},ganttContainer:{marginBottom:"1.5rem",border:"1px solid #e5e7eb",borderRadius:"6px",overflow:"hidden",padding:"0.75rem",background:"#f9fafb"},ganttTimeAxis:{position:"relative",height:"30px",borderBottom:"1px solid #ddd",background:"#f9f9f9",marginBottom:"0.5rem"},ganttTimeLabel:{position:"absolute",top:"8px",transform:"translateX(-50%)",fontSize:"11px",color:"#666",whiteSpace:"nowrap"},ganttBookings:{position:"relative",background:"white"},ganttBookingBar:{position:"absolute",background:"linear-gradient(135deg, #667eea 0%, #764ba2 100%)",borderRadius:"4px",border:"2px solid #5568d3",padding:"4px 8px",color:"white",fontWeight:500,display:"flex",alignItems:"center",gap:"6px",overflow:"hidden",cursor:"pointer",transition:"transform 0.2s",zIndex:2},ganttPartySize:{background:"rgba(255,255,255,0.3)",borderRadius:"3px",padding:"2px 6px",fontSize:"11px",fontWeight:"bold",flexShrink:0},ganttBarText:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:"11px"},ganttIntervalLine:{position:"absolute",width:"1px",background:"#e5e5e5",top:0,pointerEvents:"none",zIndex:1},ganttClosedBlock:{position:"absolute",background:"rgba(100, 100, 100, 0.1)",top:0,pointerEvents:"none",zIndex:0},chartContainer:{background:"white",borderRadius:"8px",padding:"1.5rem",marginTop:"2rem",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},chartTitle:{fontSize:"1.5rem",fontWeight:"bold",marginBottom:"1rem"},chart:{border:"1px solid #e5e7eb",borderRadius:"4px"},chartLegend:{display:"flex",gap:"2rem",justifyContent:"center",marginTop:"1rem"},legendItem:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem"},legendLine:{width:"30px",height:"3px",display:"inline-block"}},lO={normal:{bg:"#e8e5f5",border:"#667eea"},groupMember:{bg:"#e8e5f5",border:"#0ea5e9"}};function OJ(){const{token:n}=gn(),[e,t]=k.useState(()=>new Date().toISOString().split("T")[0]),[r,i]=k.useState(null),[o,a]=k.useState(null),{data:l,isLoading:d}=Oe({queryKey:["residents-table-chart","v2",e],queryFn:async()=>{const p=await fetch(`/api/residents-table-chart?start_date=${e}`,{headers:{Authorization:`Bearer ${n}`}});if(!p.ok)throw new Error("Failed to fetch chart data");return p.json()},staleTime:2*60*1e3}),c=()=>{const p=new Date(e);p.setDate(p.getDate()-7),t(p.toISOString().split("T")[0])},u=()=>{const p=new Date(e);p.setDate(p.getDate()+7),t(p.toISOString().split("T")[0])},f=p=>{const g=new Date(p);return`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][g.getDay()]} ${g.getDate()}`};return d?s.jsxs("div",{style:Vn.container,children:[s.jsx("h1",{children:"Residents Table Chart"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"Loading..."})]}):!l||!l.rooms?s.jsxs("div",{style:Vn.container,children:[s.jsx("h1",{children:"Residents Table Chart"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:l?"Loading new data structure...":"No data available"})]}):s.jsxs("div",{style:Vn.container,children:[s.jsx("h1",{children:"Residents Table Chart"}),s.jsxs("div",{style:Vn.header,children:[s.jsx("button",{onClick:c,style:Vn.navButton,children:"◀ Prev Week"}),s.jsx("input",{type:"date",value:e,onChange:p=>t(p.target.value),style:Vn.dateInput}),s.jsx("button",{onClick:u,style:Vn.navButton,children:"Next Week ▶"})]}),s.jsxs("div",{style:Vn.summary,children:[s.jsx("strong",{children:l.summary.total_rooms})," Rooms",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsx("strong",{children:l.summary.total_bookings})," Bookings",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsx("strong",{children:l.summary.total_room_nights})," Room Nights",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsx("strong",{children:l.summary.nights_with_restaurant})," with Restaurant Table",s.jsx("span",{style:{margin:"0 1rem",color:"#ddd"},children:"|"}),s.jsxs("strong",{children:[l.summary.coverage_percentage,"%"]})," Coverage"]}),s.jsx("div",{style:Vn.chartContainer,children:s.jsxs("div",{style:Vn.grid,children:[s.jsx("div",{style:{...Vn.headerCell,borderLeft:"none"},children:"Room"}),l.date_range.dates.map(p=>s.jsx("div",{style:Vn.headerCell,children:f(p)},p)),l.rooms.map((p,g)=>s.jsxs("div",{style:Vn.row,children:[s.jsx("div",{style:Vn.roomCell,children:s.jsx("div",{style:Vn.roomNumber,children:p.room_number||"Unknown Room"})}),l.date_range.dates.map(m=>{const v=p.bookings.filter(T=>T.nights.includes(m))[0];if(!v)return s.jsx("div",{style:Vn.dayCell},m);const x=v.check_in===m,w=v.nights[v.nights.length-1]===m,S=v.restaurant_bookings[m],_=v.bookings_group_id&&v.bookings_group_id.trim()!=="",b=_&&o===v.bookings_group_id,C=_?lO.groupMember:lO.normal;return s.jsxs("div",{style:Vn.dayCell,children:[s.jsx("div",{style:{position:"absolute",top:"12px",height:"36px",background:C.bg,cursor:"pointer",transition:"all 0.2s ease",zIndex:b?15:10,left:x?"0.5rem":"calc(-0.5rem + 1px)",right:w?"0.5rem":"calc(-0.5rem + 1px)",borderRadius:x&&w?"8px":x?"8px 0 0 8px":w?"0 8px 8px 0":"0",borderTop:`2px solid ${C.border}`,borderBottom:`2px solid ${C.border}`,borderLeft:x?`2px solid ${C.border}`:"none",borderRight:w?`2px solid ${C.border}`:"none",boxShadow:b?x&&w?`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}, inset 3px 0 0 ${C.border}, inset -3px 0 0 ${C.border}`:x?`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}, inset 3px 0 0 ${C.border}`:w?`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}, inset -3px 0 0 ${C.border}`:`inset 0 3px 0 ${C.border}, inset 0 -3px 0 ${C.border}`:x||w?"0 1px 3px rgba(0,0,0,0.05)":"none"},onMouseEnter:()=>_&&a(v.bookings_group_id),onMouseLeave:()=>a(null),onClick:()=>i({room:p,booking:v}),title:`Room ${p.room_number} - Booking ${v.booking_id} -${v.check_in} to ${v.check_out}${_?` -Group: ${v.bookings_group_id}`:""}`}),(S==null?void 0:S.has_booking)&&s.jsx("div",{style:{position:"absolute",top:"12px",left:"50%",transform:"translateX(-50%)",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"1.3rem",cursor:"pointer",filter:"drop-shadow(0 1px 2px rgba(0,0,0,0.3))",zIndex:20,pointerEvents:"none",opacity:S.is_group_match?.5:1},title:`${S.opening_hour_name||"Dining"} - ${S.time||""} -${S.people} people${S.table_name?` -${S.table_name}`:""}${S.is_group_match?` -(Group booking - via another room)`:""}`,children:"🍽️"})]},m)})]},p.room_number||`room-${g}`))]})}),r&&s.jsx("div",{style:Vn.modalOverlay,onClick:()=>i(null),children:s.jsxs("div",{style:Vn.modal,onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{style:Vn.modalHeader,children:[s.jsxs("h2",{children:["Room ",r.room.room_number||"Unknown"]}),s.jsx("button",{onClick:()=>i(null),style:Vn.closeBtn,children:"×"})]}),s.jsxs("div",{style:Vn.modalContent,children:[s.jsxs("div",{style:Vn.modalRow,children:[s.jsx("strong",{children:"Booking ID:"})," ",r.booking.booking_id||"Not specified"]}),s.jsxs("div",{style:Vn.modalRow,children:[s.jsx("strong",{children:"Stay:"})," ",r.booking.check_in," to ",r.booking.check_out," (",r.booking.nights.length," nights)"]}),r.booking.is_dbb&&s.jsx("div",{style:Vn.modalRow,children:s.jsx("span",{style:Vn.badge,children:"Dinner, Bed & Breakfast"})}),r.booking.is_package&&s.jsx("div",{style:Vn.modalRow,children:s.jsx("span",{style:Vn.badge,children:"Package Deal"})}),s.jsx("h3",{style:{marginTop:"1.5rem",marginBottom:"0.75rem"},children:"Restaurant Bookings"}),s.jsxs("table",{style:Vn.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Vn.th,children:"Date"}),s.jsx("th",{style:Vn.th,children:"Time"}),s.jsx("th",{style:Vn.th,children:"Service"}),s.jsx("th",{style:Vn.th,children:"Covers"}),s.jsx("th",{style:Vn.th,children:"Table"})]})}),s.jsx("tbody",{children:r.booking.nights.map(p=>{const g=r.booking.restaurant_bookings[p];return s.jsxs("tr",{style:g!=null&&g.has_booking?{}:Vn.noBookingRow,children:[s.jsx("td",{style:Vn.td,children:p}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.time:"-"}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.opening_hour_name:"-"}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.people:"-"}),s.jsx("td",{style:Vn.td,children:g!=null&&g.has_booking?g.table_name:"-"})]},p)})})]})]})]})})]})}const Vn={container:{padding:"2rem",background:"#f5f5f5",minHeight:"100vh"},header:{background:"white",padding:"1.5rem",borderRadius:"12px",marginBottom:"1rem",display:"flex",gap:"1rem",alignItems:"center",justifyContent:"center"},navButton:{padding:"0.75rem 1.5rem",background:"#667eea",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"1rem",fontWeight:"500"},dateInput:{padding:"0.75rem",border:"1px solid #ddd",borderRadius:"8px",fontSize:"1rem"},summary:{background:"white",padding:"1rem 1.5rem",borderRadius:"8px",marginBottom:"1rem",fontSize:"0.95rem",color:"#666",textAlign:"center"},chartContainer:{background:"white",borderRadius:"12px",overflow:"auto",scrollbarGutter:"stable",padding:"1rem",paddingRight:"0.5rem"},grid:{display:"grid",gridTemplateColumns:"150px repeat(7, 1fr)",gap:"0",minWidth:"1000px"},headerCell:{padding:"0.75rem",borderBottom:"2px solid #333",borderLeft:"1px solid #eee",fontWeight:"bold",textAlign:"center",background:"#f8f8f8",fontSize:"0.9rem"},row:{display:"contents"},roomCell:{padding:"0.75rem",borderRight:"1px solid #ddd",borderBottom:"1px solid #eee",fontWeight:"500",background:"#fafafa",display:"flex",flexDirection:"column",gap:"0.25rem"},roomNumber:{fontSize:"1rem",fontWeight:"bold",color:"#333"},badge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#e0e7ff",color:"#4338ca",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"600",marginTop:"0.25rem"},dayCell:{position:"relative",padding:"0.5rem",borderLeft:"1px solid #eee",borderBottom:"1px solid #eee",minHeight:"70px",background:"white"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",width:"90%",maxWidth:"700px",maxHeight:"90vh",overflow:"auto",padding:"24px"},modalHeader:{display:"flex",justifyContent:"space-between",marginBottom:"1rem",paddingBottom:"1rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"2rem",cursor:"pointer",color:"#999"},modalContent:{fontSize:"0.95rem"},modalRow:{marginBottom:"0.75rem",lineHeight:"1.6"},table:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",fontWeight:"600",fontSize:"0.9rem"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},noBookingRow:{background:"#f9f9f9",color:"#999"}};/*! - * @kurkle/color v0.3.4 - * https://github.com/kurkle/color#readme - * (c) 2024 Jukka Kurkela - * Released under the MIT License - */function X_(n){return n+.5|0}const hg=(n,e,t)=>Math.max(Math.min(n,t),e);function Jw(n){return hg(X_(n*2.55),0,255)}function Tg(n){return hg(X_(n*255),0,255)}function vh(n){return hg(X_(n/2.55)/100,0,1)}function dO(n){return hg(X_(n*100),0,100)}const nd={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},uB=[..."0123456789ABCDEF"],LJ=n=>uB[n&15],NJ=n=>uB[(n&240)>>4]+uB[n&15],p2=n=>(n&240)>>4===(n&15),WJ=n=>p2(n.r)&&p2(n.g)&&p2(n.b)&&p2(n.a);function UJ(n){var e=n.length,t;return n[0]==="#"&&(e===4||e===5?t={r:255&nd[n[1]]*17,g:255&nd[n[2]]*17,b:255&nd[n[3]]*17,a:e===5?nd[n[4]]*17:255}:(e===7||e===9)&&(t={r:nd[n[1]]<<4|nd[n[2]],g:nd[n[3]]<<4|nd[n[4]],b:nd[n[5]]<<4|nd[n[6]],a:e===9?nd[n[7]]<<4|nd[n[8]]:255})),t}const HJ=(n,e)=>n<255?e(n):"";function qJ(n){var e=WJ(n)?LJ:NJ;return n?"#"+e(n.r)+e(n.g)+e(n.b)+HJ(n.a,e):void 0}const VJ=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function V9(n,e,t){const r=e*Math.min(t,1-t),i=(o,a=(o+n/30)%12)=>t-r*Math.max(Math.min(a-3,9-a,1),-1);return[i(0),i(8),i(4)]}function GJ(n,e,t){const r=(i,o=(i+n/60)%6)=>t-t*e*Math.max(Math.min(o,4-o,1),0);return[r(5),r(3),r(1)]}function KJ(n,e,t){const r=V9(n,1,.5);let i;for(e+t>1&&(i=1/(e+t),e*=i,t*=i),i=0;i<3;i++)r[i]*=1-e-t,r[i]+=e;return r}function XJ(n,e,t,r,i){return n===i?(e-t)/r+(e.5?u/(2-o-a):u/(o+a),d=XJ(t,r,i,u,o),d=d*60+.5),[d|0,c||0,l]}function C6(n,e,t,r){return(Array.isArray(e)?n(e[0],e[1],e[2]):n(e,t,r)).map(Tg)}function A6(n,e,t){return C6(V9,n,e,t)}function YJ(n,e,t){return C6(KJ,n,e,t)}function QJ(n,e,t){return C6(GJ,n,e,t)}function G9(n){return(n%360+360)%360}function $J(n){const e=VJ.exec(n);let t=255,r;if(!e)return;e[5]!==r&&(t=e[6]?Jw(+e[5]):Tg(+e[5]));const i=G9(+e[2]),o=+e[3]/100,a=+e[4]/100;return e[1]==="hwb"?r=YJ(i,o,a):e[1]==="hsv"?r=QJ(i,o,a):r=A6(i,o,a),{r:r[0],g:r[1],b:r[2],a:t}}function ZJ(n,e){var t=_6(n);t[0]=G9(t[0]+e),t=A6(t),n.r=t[0],n.g=t[1],n.b=t[2]}function JJ(n){if(!n)return;const e=_6(n),t=e[0],r=dO(e[1]),i=dO(e[2]);return n.a<255?`hsla(${t}, ${r}%, ${i}%, ${vh(n.a)})`:`hsl(${t}, ${r}%, ${i}%)`}const cO={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},uO={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};function eee(){const n={},e=Object.keys(uO),t=Object.keys(cO);let r,i,o,a,l;for(r=0;r>16&255,o>>8&255,o&255]}return n}let g2;function tee(n){g2||(g2=eee(),g2.transparent=[0,0,0,0]);const e=g2[n.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:e.length===4?e[3]:255}}const nee=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;function ree(n){const e=nee.exec(n);let t=255,r,i,o;if(e){if(e[7]!==r){const a=+e[7];t=e[8]?Jw(a):hg(a*255,0,255)}return r=+e[1],i=+e[3],o=+e[5],r=255&(e[2]?Jw(r):hg(r,0,255)),i=255&(e[4]?Jw(i):hg(i,0,255)),o=255&(e[6]?Jw(o):hg(o,0,255)),{r,g:i,b:o,a:t}}}function iee(n){return n&&(n.a<255?`rgba(${n.r}, ${n.g}, ${n.b}, ${vh(n.a)})`:`rgb(${n.r}, ${n.g}, ${n.b})`)}const oP=n=>n<=.0031308?n*12.92:Math.pow(n,1/2.4)*1.055-.055,cx=n=>n<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4);function see(n,e,t){const r=cx(vh(n.r)),i=cx(vh(n.g)),o=cx(vh(n.b));return{r:Tg(oP(r+t*(cx(vh(e.r))-r))),g:Tg(oP(i+t*(cx(vh(e.g))-i))),b:Tg(oP(o+t*(cx(vh(e.b))-o))),a:n.a+t*(e.a-n.a)}}function m2(n,e,t){if(n){let r=_6(n);r[e]=Math.max(0,Math.min(r[e]+r[e]*t,e===0?360:1)),r=A6(r),n.r=r[0],n.g=r[1],n.b=r[2]}}function K9(n,e){return n&&Object.assign(e||{},n)}function hO(n){var e={r:0,g:0,b:0,a:255};return Array.isArray(n)?n.length>=3&&(e={r:n[0],g:n[1],b:n[2],a:255},n.length>3&&(e.a=Tg(n[3]))):(e=K9(n,{r:0,g:0,b:0,a:1}),e.a=Tg(e.a)),e}function oee(n){return n.charAt(0)==="r"?ree(n):$J(n)}class Tj{constructor(e){if(e instanceof Tj)return e;const t=typeof e;let r;t==="object"?r=hO(e):t==="string"&&(r=UJ(e)||tee(e)||oee(e)),this._rgb=r,this._valid=!!r}get valid(){return this._valid}get rgb(){var e=K9(this._rgb);return e&&(e.a=vh(e.a)),e}set rgb(e){this._rgb=hO(e)}rgbString(){return this._valid?iee(this._rgb):void 0}hexString(){return this._valid?qJ(this._rgb):void 0}hslString(){return this._valid?JJ(this._rgb):void 0}mix(e,t){if(e){const r=this.rgb,i=e.rgb;let o;const a=t===o?.5:t,l=2*a-1,d=r.a-i.a,c=((l*d===-1?l:(l+d)/(1+l*d))+1)/2;o=1-c,r.r=255&c*r.r+o*i.r+.5,r.g=255&c*r.g+o*i.g+.5,r.b=255&c*r.b+o*i.b+.5,r.a=a*r.a+(1-a)*i.a,this.rgb=r}return this}interpolate(e,t){return e&&(this._rgb=see(this._rgb,e._rgb,t)),this}clone(){return new Tj(this.rgb)}alpha(e){return this._rgb.a=Tg(e),this}clearer(e){const t=this._rgb;return t.a*=1-e,this}greyscale(){const e=this._rgb,t=X_(e.r*.3+e.g*.59+e.b*.11);return e.r=e.g=e.b=t,this}opaquer(e){const t=this._rgb;return t.a*=1+e,this}negate(){const e=this._rgb;return e.r=255-e.r,e.g=255-e.g,e.b=255-e.b,this}lighten(e){return m2(this._rgb,2,e),this}darken(e){return m2(this._rgb,2,-e),this}saturate(e){return m2(this._rgb,1,e),this}desaturate(e){return m2(this._rgb,1,-e),this}rotate(e){return ZJ(this._rgb,e),this}}/*! - * Chart.js v4.5.1 - * https://www.chartjs.org - * (c) 2025 Chart.js Contributors - * Released under the MIT License - */function ih(){}const aee=(()=>{let n=0;return()=>n++})();function Ur(n){return n==null}function ki(n){if(Array.isArray&&Array.isArray(n))return!0;const e=Object.prototype.toString.call(n);return e.slice(0,7)==="[object"&&e.slice(-6)==="Array]"}function Yn(n){return n!==null&&Object.prototype.toString.call(n)==="[object Object]"}function sl(n){return(typeof n=="number"||n instanceof Number)&&isFinite(+n)}function Hc(n,e){return sl(n)?n:e}function In(n,e){return typeof n>"u"?e:n}const lee=(n,e)=>typeof n=="string"&&n.endsWith("%")?parseFloat(n)/100:+n/e,X9=(n,e)=>typeof n=="string"&&n.endsWith("%")?parseFloat(n)/100*e:+n;function li(n,e,t){if(n&&typeof n.call=="function")return n.apply(t,e)}function Yr(n,e,t,r){let i,o,a;if(ki(n))for(o=n.length,i=0;in,x:n=>n.x,y:n=>n.y};function uee(n){const e=n.split("."),t=[];let r="";for(const i of e)r+=i,r.endsWith("\\")?r=r.slice(0,-1)+".":(t.push(r),r="");return t}function hee(n){const e=uee(n);return t=>{for(const r of e){if(r==="")break;t=t&&t[r]}return t}}function g0(n,e){return(fO[e]||(fO[e]=hee(e)))(n)}function T6(n){return n.charAt(0).toUpperCase()+n.slice(1)}const ol=n=>typeof n<"u",il=n=>typeof n=="function",pO=(n,e)=>{if(n.size!==e.size)return!1;for(const t of n)if(!e.has(t))return!1;return!0};function fee(n){return n.type==="mouseup"||n.type==="click"||n.type==="contextmenu"}const Or=Math.PI,Eo=2*Or,pee=Eo+Or,VA=Number.POSITIVE_INFINITY,F6=Or/180,Po=Or/2,jd=Or/4,GA=Or*2/3,Q9=Math.log10,zu=Math.sign;function HS(n,e,t){return Math.abs(n-e)i-o).pop(),e}function mee(n){return typeof n=="symbol"||typeof n=="object"&&n!==null&&!(Symbol.toPrimitive in n||"toString"in n||"valueOf"in n)}function m0(n){return!mee(n)&&!isNaN(parseFloat(n))&&isFinite(n)}function yee(n,e){const t=Math.round(n);return t-e<=n&&t+e>=n}function xee(n,e,t){let r,i,o;for(r=0,i=n.length;rd&&c=Math.min(e,t)-r&&n<=Math.max(e,t)+r}function D6(n,e,t){t=t||(a=>n[a]1;)o=i+r>>1,t(o)?i=o:r=o;return{lo:i,hi:r}}const vm=(n,e,t,r)=>D6(n,t,r?i=>{const o=n[i][e];return on[i][e]D6(n,t,r=>n[r][e]>=t);function See(n,e,t){let r=0,i=n.length;for(;rr&&n[i-1]>t;)i--;return r>0||i{const r="_onData"+T6(t),i=n[t];Object.defineProperty(n,t,{configurable:!0,enumerable:!1,value(...o){const a=i.apply(this,o);return n._chartjs.listeners.forEach(l=>{typeof l[r]=="function"&&l[r](...o)}),a}})})}function yO(n,e){const t=n._chartjs;if(!t)return;const r=t.listeners,i=r.indexOf(e);i!==-1&&r.splice(i,1),!(r.length>0)&&(Z9.forEach(o=>{delete n[o]}),delete n._chartjs)}function J9(n){const e=new Set(n);return e.size===n.length?n:Array.from(e)}const eU=function(){return typeof window>"u"?function(n){return n()}:window.requestAnimationFrame}();function tU(n,e){let t=[],r=!1;return function(...i){t=i,r||(r=!0,eU.call(window,()=>{r=!1,n.apply(e,t)}))}}function kee(n,e){let t;return function(...r){return e?(clearTimeout(t),t=setTimeout(n,e,r)):n.apply(this,r),e}}const E6=n=>n==="start"?"left":n==="end"?"right":"center",ta=(n,e,t)=>n==="start"?e:n==="end"?t:(e+t)/2,_ee=(n,e,t,r)=>n===(r?"left":"right")?t:n==="center"?(e+t)/2:e;function Cee(n,e,t){const r=e.length;let i=0,o=r;if(n._sorted){const{iScale:a,vScale:l,_parsed:d}=n,c=n.dataset&&n.dataset.options?n.dataset.options.spanGaps:null,u=a.axis,{min:f,max:p,minDefined:g,maxDefined:m}=a.getUserBounds();if(g){if(i=Math.min(vm(d,u,f).lo,t?r:vm(e,u,a.getPixelForValue(f)).lo),c){const y=d.slice(0,i+1).reverse().findIndex(v=>!Ur(v[l.axis]));i-=Math.max(0,y)}i=Wl(i,0,r-1)}if(m){let y=Math.max(vm(d,a.axis,p,!0).hi+1,t?0:vm(e,u,a.getPixelForValue(p),!0).hi+1);if(c){const v=d.slice(y-1).findIndex(x=>!Ur(x[l.axis]));y+=Math.max(0,v)}o=Wl(y,i,r)-i}else o=r-i}return{start:i,count:o}}function Aee(n){const{xScale:e,yScale:t,_scaleRanges:r}=n,i={xmin:e.min,xmax:e.max,ymin:t.min,ymax:t.max};if(!r)return n._scaleRanges=i,!0;const o=r.xmin!==e.min||r.xmax!==e.max||r.ymin!==t.min||r.ymax!==t.max;return Object.assign(r,i),o}const y2=n=>n===0||n===1,xO=(n,e,t)=>-(Math.pow(2,10*(n-=1))*Math.sin((n-e)*Eo/t)),bO=(n,e,t)=>Math.pow(2,-10*n)*Math.sin((n-e)*Eo/t)+1,qS={linear:n=>n,easeInQuad:n=>n*n,easeOutQuad:n=>-n*(n-2),easeInOutQuad:n=>(n/=.5)<1?.5*n*n:-.5*(--n*(n-2)-1),easeInCubic:n=>n*n*n,easeOutCubic:n=>(n-=1)*n*n+1,easeInOutCubic:n=>(n/=.5)<1?.5*n*n*n:.5*((n-=2)*n*n+2),easeInQuart:n=>n*n*n*n,easeOutQuart:n=>-((n-=1)*n*n*n-1),easeInOutQuart:n=>(n/=.5)<1?.5*n*n*n*n:-.5*((n-=2)*n*n*n-2),easeInQuint:n=>n*n*n*n*n,easeOutQuint:n=>(n-=1)*n*n*n*n+1,easeInOutQuint:n=>(n/=.5)<1?.5*n*n*n*n*n:.5*((n-=2)*n*n*n*n+2),easeInSine:n=>-Math.cos(n*Po)+1,easeOutSine:n=>Math.sin(n*Po),easeInOutSine:n=>-.5*(Math.cos(Or*n)-1),easeInExpo:n=>n===0?0:Math.pow(2,10*(n-1)),easeOutExpo:n=>n===1?1:-Math.pow(2,-10*n)+1,easeInOutExpo:n=>y2(n)?n:n<.5?.5*Math.pow(2,10*(n*2-1)):.5*(-Math.pow(2,-10*(n*2-1))+2),easeInCirc:n=>n>=1?n:-(Math.sqrt(1-n*n)-1),easeOutCirc:n=>Math.sqrt(1-(n-=1)*n),easeInOutCirc:n=>(n/=.5)<1?-.5*(Math.sqrt(1-n*n)-1):.5*(Math.sqrt(1-(n-=2)*n)+1),easeInElastic:n=>y2(n)?n:xO(n,.075,.3),easeOutElastic:n=>y2(n)?n:bO(n,.075,.3),easeInOutElastic(n){return y2(n)?n:n<.5?.5*xO(n*2,.1125,.45):.5+.5*bO(n*2-1,.1125,.45)},easeInBack(n){return n*n*((1.70158+1)*n-1.70158)},easeOutBack(n){return(n-=1)*n*((1.70158+1)*n+1.70158)+1},easeInOutBack(n){let e=1.70158;return(n/=.5)<1?.5*(n*n*(((e*=1.525)+1)*n-e)):.5*((n-=2)*n*(((e*=1.525)+1)*n+e)+2)},easeInBounce:n=>1-qS.easeOutBounce(1-n),easeOutBounce(n){return n<1/2.75?7.5625*n*n:n<2/2.75?7.5625*(n-=1.5/2.75)*n+.75:n<2.5/2.75?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375},easeInOutBounce:n=>n<.5?qS.easeInBounce(n*2)*.5:qS.easeOutBounce(n*2-1)*.5+.5};function P6(n){if(n&&typeof n=="object"){const e=n.toString();return e==="[object CanvasPattern]"||e==="[object CanvasGradient]"}return!1}function vO(n){return P6(n)?n:new Tj(n)}function aP(n){return P6(n)?n:new Tj(n).saturate(.5).darken(.1).hexString()}const Tee=["x","y","borderWidth","radius","tension"],Fee=["color","borderColor","backgroundColor"];function Dee(n){n.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),n.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:e=>e!=="onProgress"&&e!=="onComplete"&&e!=="fn"}),n.set("animations",{colors:{type:"color",properties:Fee},numbers:{type:"number",properties:Tee}}),n.describe("animations",{_fallback:"animation"}),n.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:e=>e|0}}}})}function Eee(n){n.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})}const wO=new Map;function Pee(n,e){e=e||{};const t=n+JSON.stringify(e);let r=wO.get(t);return r||(r=new Intl.NumberFormat(n,e),wO.set(t,r)),r}function R6(n,e,t){return Pee(e,t).format(n)}const Ree={values(n){return ki(n)?n:""+n},numeric(n,e,t){if(n===0)return"0";const r=this.chart.options.locale;let i,o=n;if(t.length>1){const c=Math.max(Math.abs(t[0].value),Math.abs(t[t.length-1].value));(c<1e-4||c>1e15)&&(i="scientific"),o=Bee(n,t)}const a=Q9(Math.abs(o)),l=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),d={notation:i,minimumFractionDigits:l,maximumFractionDigits:l};return Object.assign(d,this.options.ticks.format),R6(n,r,d)}};function Bee(n,e){let t=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;return Math.abs(t)>=1&&n!==Math.floor(n)&&(t=n-Math.floor(n)),t}var nU={formatters:Ree};function Iee(n){n.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(e,t)=>t.lineWidth,tickColor:(e,t)=>t.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:nU.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),n.route("scale.ticks","color","","color"),n.route("scale.grid","color","","borderColor"),n.route("scale.border","color","","borderColor"),n.route("scale.title","color","","color"),n.describe("scale",{_fallback:!1,_scriptable:e=>!e.startsWith("before")&&!e.startsWith("after")&&e!=="callback"&&e!=="parser",_indexable:e=>e!=="borderDash"&&e!=="tickBorderDash"&&e!=="dash"}),n.describe("scales",{_fallback:"scale"}),n.describe("scale.ticks",{_scriptable:e=>e!=="backdropPadding"&&e!=="callback",_indexable:e=>e!=="backdropPadding"})}const y0=Object.create(null),fB=Object.create(null);function VS(n,e){if(!e)return n;const t=e.split(".");for(let r=0,i=t.length;rr.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(r,i)=>aP(i.backgroundColor),this.hoverBorderColor=(r,i)=>aP(i.borderColor),this.hoverColor=(r,i)=>aP(i.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(e),this.apply(t)}set(e,t){return lP(this,e,t)}get(e){return VS(this,e)}describe(e,t){return lP(fB,e,t)}override(e,t){return lP(y0,e,t)}route(e,t,r,i){const o=VS(this,e),a=VS(this,r),l="_"+t;Object.defineProperties(o,{[l]:{value:o[t],writable:!0},[t]:{enumerable:!0,get(){const d=this[l],c=a[i];return Yn(d)?Object.assign({},c,d):In(d,c)},set(d){this[l]=d}}})}apply(e){e.forEach(t=>t(this))}}var hs=new Mee({_scriptable:n=>!n.startsWith("on"),_indexable:n=>n!=="events",hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[Dee,Eee,Iee]);function zee(n){return!n||Ur(n.size)||Ur(n.family)?null:(n.style?n.style+" ":"")+(n.weight?n.weight+" ":"")+n.size+"px "+n.family}function SO(n,e,t,r,i){let o=e[i];return o||(o=e[i]=n.measureText(i).width,t.push(i)),o>r&&(r=o),r}function tm(n,e,t){const r=n.currentDevicePixelRatio,i=t!==0?Math.max(t/2,.5):0;return Math.round((e-i)*r)/r+i}function jO(n,e){!e&&!n||(e=e||n.getContext("2d"),e.save(),e.resetTransform(),e.clearRect(0,0,n.width,n.height),e.restore())}function pB(n,e,t,r){rU(n,e,t,r,null)}function rU(n,e,t,r,i){let o,a,l,d,c,u,f,p;const g=e.pointStyle,m=e.rotation,y=e.radius;let v=(m||0)*F6;if(g&&typeof g=="object"&&(o=g.toString(),o==="[object HTMLImageElement]"||o==="[object HTMLCanvasElement]")){n.save(),n.translate(t,r),n.rotate(v),n.drawImage(g,-g.width/2,-g.height/2,g.width,g.height),n.restore();return}if(!(isNaN(y)||y<=0)){switch(n.beginPath(),g){default:i?n.ellipse(t,r,i/2,y,0,0,Eo):n.arc(t,r,y,0,Eo),n.closePath();break;case"triangle":u=i?i/2:y,n.moveTo(t+Math.sin(v)*u,r-Math.cos(v)*y),v+=GA,n.lineTo(t+Math.sin(v)*u,r-Math.cos(v)*y),v+=GA,n.lineTo(t+Math.sin(v)*u,r-Math.cos(v)*y),n.closePath();break;case"rectRounded":c=y*.516,d=y-c,a=Math.cos(v+jd)*d,f=Math.cos(v+jd)*(i?i/2-c:d),l=Math.sin(v+jd)*d,p=Math.sin(v+jd)*(i?i/2-c:d),n.arc(t-f,r-l,c,v-Or,v-Po),n.arc(t+p,r-a,c,v-Po,v),n.arc(t+f,r+l,c,v,v+Po),n.arc(t-p,r+a,c,v+Po,v+Or),n.closePath();break;case"rect":if(!m){d=Math.SQRT1_2*y,u=i?i/2:d,n.rect(t-u,r-d,2*u,2*d);break}v+=jd;case"rectRot":f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+p,r-a),n.lineTo(t+f,r+l),n.lineTo(t-p,r+a),n.closePath();break;case"crossRot":v+=jd;case"cross":f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+f,r+l),n.moveTo(t+p,r-a),n.lineTo(t-p,r+a);break;case"star":f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+f,r+l),n.moveTo(t+p,r-a),n.lineTo(t-p,r+a),v+=jd,f=Math.cos(v)*(i?i/2:y),a=Math.cos(v)*y,l=Math.sin(v)*y,p=Math.sin(v)*(i?i/2:y),n.moveTo(t-f,r-l),n.lineTo(t+f,r+l),n.moveTo(t+p,r-a),n.lineTo(t-p,r+a);break;case"line":a=i?i/2:Math.cos(v)*y,l=Math.sin(v)*y,n.moveTo(t-a,r-l),n.lineTo(t+a,r+l);break;case"dash":n.moveTo(t,r),n.lineTo(t+Math.cos(v)*(i?i/2:y),r+Math.sin(v)*y);break;case!1:n.closePath();break}n.fill(),e.borderWidth>0&&n.stroke()}}function Dj(n,e,t){return t=t||.5,!e||n&&n.x>e.left-t&&n.xe.top-t&&n.y0&&o.strokeColor!=="";let d,c;for(n.save(),n.font=i.string,Nee(n,o),d=0;d+n||0;function iU(n,e){const t={},r=Yn(e),i=r?Object.keys(e):e,o=Yn(n)?r?a=>In(n[a],n[e[a]]):a=>n[a]:()=>n;for(const a of i)t[a]=Gee(o(a));return t}function sU(n){return iU(n,{top:"y",right:"x",bottom:"y",left:"x"})}function o0(n){return iU(n,["topLeft","topRight","bottomLeft","bottomRight"])}function sa(n){const e=sU(n);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Us(n,e){n=n||{},e=e||hs.font;let t=In(n.size,e.size);typeof t=="string"&&(t=parseInt(t,10));let r=In(n.style,e.style);r&&!(""+r).match(qee)&&(console.warn('Invalid font style specified: "'+r+'"'),r=void 0);const i={family:In(n.family,e.family),lineHeight:Vee(In(n.lineHeight,e.lineHeight),t),size:t,style:r,weight:In(n.weight,e.weight),string:""};return i.string=zee(i),i}function x2(n,e,t,r){let i,o,a;for(i=0,o=n.length;it&&l===0?0:l+d;return{min:a(r,-Math.abs(o)),max:a(i,o)}}function P0(n,e){return Object.assign(Object.create(n),e)}function B6(n,e=[""],t,r,i=()=>n[0]){const o=t||n;typeof r>"u"&&(r=dU("_fallback",n));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:n,_rootScopes:o,_fallback:r,_getTarget:i,override:l=>B6([l,...n],e,o,r)};return new Proxy(a,{deleteProperty(l,d){return delete l[d],delete l._keys,delete n[0][d],!0},get(l,d){return aU(l,d,()=>tte(d,e,n,l))},getOwnPropertyDescriptor(l,d){return Reflect.getOwnPropertyDescriptor(l._scopes[0],d)},getPrototypeOf(){return Reflect.getPrototypeOf(n[0])},has(l,d){return _O(l).includes(d)},ownKeys(l){return _O(l)},set(l,d,c){const u=l._storage||(l._storage=i());return l[d]=u[d]=c,delete l._keys,!0}})}function i1(n,e,t,r){const i={_cacheable:!1,_proxy:n,_context:e,_subProxy:t,_stack:new Set,_descriptors:oU(n,r),setContext:o=>i1(n,o,t,r),override:o=>i1(n.override(o),e,t,r)};return new Proxy(i,{deleteProperty(o,a){return delete o[a],delete n[a],!0},get(o,a,l){return aU(o,a,()=>Yee(o,a,l))},getOwnPropertyDescriptor(o,a){return o._descriptors.allKeys?Reflect.has(n,a)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(n,a)},getPrototypeOf(){return Reflect.getPrototypeOf(n)},has(o,a){return Reflect.has(n,a)},ownKeys(){return Reflect.ownKeys(n)},set(o,a,l){return n[a]=l,delete o[a],!0}})}function oU(n,e={scriptable:!0,indexable:!0}){const{_scriptable:t=e.scriptable,_indexable:r=e.indexable,_allKeys:i=e.allKeys}=n;return{allKeys:i,scriptable:t,indexable:r,isScriptable:il(t)?t:()=>t,isIndexable:il(r)?r:()=>r}}const Xee=(n,e)=>n?n+T6(e):e,I6=(n,e)=>Yn(e)&&n!=="adapters"&&(Object.getPrototypeOf(e)===null||e.constructor===Object);function aU(n,e,t){if(Object.prototype.hasOwnProperty.call(n,e)||e==="constructor")return n[e];const r=t();return n[e]=r,r}function Yee(n,e,t){const{_proxy:r,_context:i,_subProxy:o,_descriptors:a}=n;let l=r[e];return il(l)&&a.isScriptable(e)&&(l=Qee(e,l,n,t)),ki(l)&&l.length&&(l=$ee(e,l,n,a.isIndexable)),I6(e,l)&&(l=i1(l,i,o&&o[e],a)),l}function Qee(n,e,t,r){const{_proxy:i,_context:o,_subProxy:a,_stack:l}=t;if(l.has(n))throw new Error("Recursion detected: "+Array.from(l).join("->")+"->"+n);l.add(n);let d=e(o,a||r);return l.delete(n),I6(n,d)&&(d=M6(i._scopes,i,n,d)),d}function $ee(n,e,t,r){const{_proxy:i,_context:o,_subProxy:a,_descriptors:l}=t;if(typeof o.index<"u"&&r(n))return e[o.index%e.length];if(Yn(e[0])){const d=e,c=i._scopes.filter(u=>u!==d);e=[];for(const u of d){const f=M6(c,i,n,u);e.push(i1(f,o,a&&a[n],l))}}return e}function lU(n,e,t){return il(n)?n(e,t):n}const Zee=(n,e)=>n===!0?e:typeof n=="string"?g0(e,n):void 0;function Jee(n,e,t,r,i){for(const o of e){const a=Zee(t,o);if(a){n.add(a);const l=lU(a._fallback,t,i);if(typeof l<"u"&&l!==t&&l!==r)return l}else if(a===!1&&typeof r<"u"&&t!==r)return null}return!1}function M6(n,e,t,r){const i=e._rootScopes,o=lU(e._fallback,t,r),a=[...n,...i],l=new Set;l.add(r);let d=kO(l,a,t,o||t,r);return d===null||typeof o<"u"&&o!==t&&(d=kO(l,a,o,d,r),d===null)?!1:B6(Array.from(l),[""],i,o,()=>ete(e,t,r))}function kO(n,e,t,r,i){for(;t;)t=Jee(n,e,t,r,i);return t}function ete(n,e,t){const r=n._getTarget();e in r||(r[e]={});const i=r[e];return ki(i)&&Yn(t)?t:i||{}}function tte(n,e,t,r){let i;for(const o of e)if(i=dU(Xee(o,n),t),typeof i<"u")return I6(n,i)?M6(t,r,n,i):i}function dU(n,e){for(const t of e){if(!t)continue;const r=t[n];if(typeof r<"u")return r}}function _O(n){let e=n._keys;return e||(e=n._keys=nte(n._scopes)),e}function nte(n){const e=new Set;for(const t of n)for(const r of Object.keys(t).filter(i=>!i.startsWith("_")))e.add(r);return Array.from(e)}const rte=Number.EPSILON||1e-14,s1=(n,e)=>en==="x"?"y":"x";function ite(n,e,t,r){const i=n.skip?e:n,o=e,a=t.skip?e:t,l=r1(o,i),d=r1(a,o);let c=l/(l+d),u=d/(l+d);c=isNaN(c)?0:c,u=isNaN(u)?0:u;const f=r*c,p=r*u;return{previous:{x:o.x-f*(a.x-i.x),y:o.y-f*(a.y-i.y)},next:{x:o.x+p*(a.x-i.x),y:o.y+p*(a.y-i.y)}}}function ste(n,e,t){const r=n.length;let i,o,a,l,d,c=s1(n,0);for(let u=0;u!c.skip)),e.cubicInterpolationMode==="monotone")ate(n,i);else{let c=r?n[n.length-1]:n[0];for(o=0,a=n.length;on.ownerDocument.defaultView.getComputedStyle(n,null);function cte(n,e){return jF(n).getPropertyValue(e)}const ute=["top","right","bottom","left"];function a0(n,e,t){const r={};t=t?"-"+t:"";for(let i=0;i<4;i++){const o=ute[i];r[o]=parseFloat(n[e+"-"+o+t])||0}return r.width=r.left+r.right,r.height=r.top+r.bottom,r}const hte=(n,e,t)=>(n>0||e>0)&&(!t||!t.shadowRoot);function fte(n,e){const t=n.touches,r=t&&t.length?t[0]:n,{offsetX:i,offsetY:o}=r;let a=!1,l,d;if(hte(i,o,n.target))l=i,d=o;else{const c=e.getBoundingClientRect();l=r.clientX-c.left,d=r.clientY-c.top,a=!0}return{x:l,y:d,box:a}}function om(n,e){if("native"in n)return n;const{canvas:t,currentDevicePixelRatio:r}=e,i=jF(t),o=i.boxSizing==="border-box",a=a0(i,"padding"),l=a0(i,"border","width"),{x:d,y:c,box:u}=fte(n,t),f=a.left+(u&&l.left),p=a.top+(u&&l.top);let{width:g,height:m}=e;return o&&(g-=a.width+l.width,m-=a.height+l.height),{x:Math.round((d-f)/g*t.width/r),y:Math.round((c-p)/m*t.height/r)}}function pte(n,e,t){let r,i;if(e===void 0||t===void 0){const o=n&&O6(n);if(!o)e=n.clientWidth,t=n.clientHeight;else{const a=o.getBoundingClientRect(),l=jF(o),d=a0(l,"border","width"),c=a0(l,"padding");e=a.width-c.width-d.width,t=a.height-c.height-d.height,r=XA(l.maxWidth,o,"clientWidth"),i=XA(l.maxHeight,o,"clientHeight")}}return{width:e,height:t,maxWidth:r||VA,maxHeight:i||VA}}const fg=n=>Math.round(n*10)/10;function gte(n,e,t,r){const i=jF(n),o=a0(i,"margin"),a=XA(i.maxWidth,n,"clientWidth")||VA,l=XA(i.maxHeight,n,"clientHeight")||VA,d=pte(n,e,t);let{width:c,height:u}=d;if(i.boxSizing==="content-box"){const p=a0(i,"border","width"),g=a0(i,"padding");c-=g.width+p.width,u-=g.height+p.height}return c=Math.max(0,c-o.width),u=Math.max(0,r?c/r:u-o.height),c=fg(Math.min(c,a,d.maxWidth)),u=fg(Math.min(u,l,d.maxHeight)),c&&!u&&(u=fg(c/2)),(e!==void 0||t!==void 0)&&r&&d.height&&u>d.height&&(u=d.height,c=fg(Math.floor(u*r))),{width:c,height:u}}function CO(n,e,t){const r=e||1,i=fg(n.height*r),o=fg(n.width*r);n.height=fg(n.height),n.width=fg(n.width);const a=n.canvas;return a.style&&(t||!a.style.height&&!a.style.width)&&(a.style.height=`${n.height}px`,a.style.width=`${n.width}px`),n.currentDevicePixelRatio!==r||a.height!==i||a.width!==o?(n.currentDevicePixelRatio=r,a.height=i,a.width=o,n.ctx.setTransform(r,0,0,r,0,0),!0):!1}const mte=function(){let n=!1;try{const e={get passive(){return n=!0,!1}};z6()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch{}return n}();function AO(n,e){const t=cte(n,e),r=t&&t.match(/^(\d+)(\.\d+)?px$/);return r?+r[1]:void 0}function am(n,e,t,r){return{x:n.x+t*(e.x-n.x),y:n.y+t*(e.y-n.y)}}function yte(n,e,t,r){return{x:n.x+t*(e.x-n.x),y:r==="middle"?t<.5?n.y:e.y:r==="after"?t<1?n.y:e.y:t>0?e.y:n.y}}function xte(n,e,t,r){const i={x:n.cp2x,y:n.cp2y},o={x:e.cp1x,y:e.cp1y},a=am(n,i,t),l=am(i,o,t),d=am(o,e,t),c=am(a,l,t),u=am(l,d,t);return am(c,u,t)}const bte=function(n,e){return{x(t){return n+n+e-t},setWidth(t){e=t},textAlign(t){return t==="center"?t:t==="right"?"left":"right"},xPlus(t,r){return t-r},leftForLtr(t,r){return t-r}}},vte=function(){return{x(n){return n},setWidth(n){},textAlign(n){return n},xPlus(n,e){return n+e},leftForLtr(n,e){return n}}};function ib(n,e,t){return n?bte(e,t):vte()}function uU(n,e){let t,r;(e==="ltr"||e==="rtl")&&(t=n.canvas.style,r=[t.getPropertyValue("direction"),t.getPropertyPriority("direction")],t.setProperty("direction",e,"important"),n.prevTextDirection=r)}function hU(n,e){e!==void 0&&(delete n.prevTextDirection,n.canvas.style.setProperty("direction",e[0],e[1]))}function fU(n){return n==="angle"?{between:KA,compare:bee,normalize:Yf}:{between:bm,compare:(e,t)=>e-t,normalize:e=>e}}function TO({start:n,end:e,count:t,loop:r,style:i}){return{start:n%t,end:e%t,loop:r&&(e-n+1)%t===0,style:i}}function wte(n,e,t){const{property:r,start:i,end:o}=t,{between:a,normalize:l}=fU(r),d=e.length;let{start:c,end:u,loop:f}=n,p,g;if(f){for(c+=d,u+=d,p=0,g=d;pd(i,S,x)&&l(i,S)!==0,b=()=>l(o,x)===0||d(o,S,x),C=()=>y||_(),T=()=>!y||b();for(let F=u,A=u;F<=f;++F)w=e[F%a],!w.skip&&(x=c(w[r]),x!==S&&(y=d(x,i,o),v===null&&C()&&(v=l(x,i)===0?F:A),v!==null&&T()&&(m.push(TO({start:v,end:F,loop:p,count:a,style:g})),v=null),A=F,S=x));return v!==null&&m.push(TO({start:v,end:f,loop:p,count:a,style:g})),m}function jte(n,e){const t=[],r=n.segments;for(let i=0;ii&&n[o%e].skip;)o--;return o%=e,{start:i,end:o}}function _te(n,e,t,r){const i=n.length,o=[];let a=e,l=n[e],d;for(d=e+1;d<=t;++d){const c=n[d%i];c.skip||c.stop?l.skip||(r=!1,o.push({start:e%i,end:(d-1)%i,loop:r}),e=a=c.stop?d:null):(a=d,l.skip&&(e=d)),l=c}return a!==null&&o.push({start:e%i,end:a%i,loop:r}),o}function Cte(n,e){const t=n.points,r=n.options.spanGaps,i=t.length;if(!i)return[];const o=!!n._loop,{start:a,end:l}=kte(t,i,o,r);if(r===!0)return FO(n,[{start:a,end:l,loop:o}],t,e);const d=ll({chart:e,initial:t.initial,numSteps:a,currentStep:Math.min(r-t.start,a)}))}_refresh(){this._request||(this._running=!0,this._request=eU.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(e=Date.now()){let t=0;this._charts.forEach((r,i)=>{if(!r.running||!r.items.length)return;const o=r.items;let a=o.length-1,l=!1,d;for(;a>=0;--a)d=o[a],d._active?(d._total>r.duration&&(r.duration=d._total),d.tick(e),l=!0):(o[a]=o[o.length-1],o.pop());l&&(i.draw(),this._notify(i,r,e,"progress")),o.length||(r.running=!1,this._notify(i,r,e,"complete"),r.initial=!1),t+=o.length}),this._lastDate=e,t===0&&(this._running=!1)}_getAnims(e){const t=this._charts;let r=t.get(e);return r||(r={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},t.set(e,r)),r}listen(e,t,r){this._getAnims(e).listeners[t].push(r)}add(e,t){!t||!t.length||this._getAnims(e).items.push(...t)}has(e){return this._getAnims(e).items.length>0}start(e){const t=this._charts.get(e);t&&(t.running=!0,t.start=Date.now(),t.duration=t.items.reduce((r,i)=>Math.max(r,i._duration),0),this._refresh())}running(e){if(!this._running)return!1;const t=this._charts.get(e);return!(!t||!t.running||!t.items.length)}stop(e){const t=this._charts.get(e);if(!t||!t.items.length)return;const r=t.items;let i=r.length-1;for(;i>=0;--i)r[i].cancel();t.items=[],this._notify(e,t,Date.now(),"complete")}remove(e){return this._charts.delete(e)}}var ch=new Ete;const EO="transparent",Pte={boolean(n,e,t){return t>.5?e:n},color(n,e,t){const r=vO(n||EO),i=r.valid&&vO(e||EO);return i&&i.valid?i.mix(r,t).hexString():e},number(n,e,t){return n+(e-n)*t}};class Rte{constructor(e,t,r,i){const o=t[r];i=x2([e.to,i,o,e.from]);const a=x2([e.from,o,i]);this._active=!0,this._fn=e.fn||Pte[e.type||typeof a],this._easing=qS[e.easing]||qS.linear,this._start=Math.floor(Date.now()+(e.delay||0)),this._duration=this._total=Math.floor(e.duration),this._loop=!!e.loop,this._target=t,this._prop=r,this._from=a,this._to=i,this._promises=void 0}active(){return this._active}update(e,t,r){if(this._active){this._notify(!1);const i=this._target[this._prop],o=r-this._start,a=this._duration-o;this._start=r,this._duration=Math.floor(Math.max(a,e.duration)),this._total+=o,this._loop=!!e.loop,this._to=x2([e.to,t,i,e.from]),this._from=x2([e.from,i,t])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(e){const t=e-this._start,r=this._duration,i=this._prop,o=this._from,a=this._loop,l=this._to;let d;if(this._active=o!==l&&(a||t1?2-d:d,d=this._easing(Math.min(1,Math.max(0,d))),this._target[i]=this._fn(o,l,d)}wait(){const e=this._promises||(this._promises=[]);return new Promise((t,r)=>{e.push({res:t,rej:r})})}_notify(e){const t=e?"res":"rej",r=this._promises||[];for(let i=0;i{const o=e[i];if(!Yn(o))return;const a={};for(const l of t)a[l]=o[l];(ki(o.properties)&&o.properties||[i]).forEach(l=>{(l===i||!r.has(l))&&r.set(l,a)})})}_animateOptions(e,t){const r=t.options,i=Ite(e,r);if(!i)return[];const o=this._createAnimations(i,r);return r.$shared&&Bte(e.options.$animations,r).then(()=>{e.options=r},()=>{}),o}_createAnimations(e,t){const r=this._properties,i=[],o=e.$animations||(e.$animations={}),a=Object.keys(t),l=Date.now();let d;for(d=a.length-1;d>=0;--d){const c=a[d];if(c.charAt(0)==="$")continue;if(c==="options"){i.push(...this._animateOptions(e,t));continue}const u=t[c];let f=o[c];const p=r.get(c);if(f)if(p&&f.active()){f.update(p,u,l);continue}else f.cancel();if(!p||!p.duration){e[c]=u;continue}o[c]=f=new Rte(p,e,c,u),i.push(f)}return i}update(e,t){if(this._properties.size===0){Object.assign(e,t);return}const r=this._createAnimations(e,t);if(r.length)return ch.add(this._chart,r),!0}}function Bte(n,e){const t=[],r=Object.keys(e);for(let i=0;i0||!t&&o<0)return i.index}return null}function IO(n,e){const{chart:t,_cachedMeta:r}=n,i=t._stacks||(t._stacks={}),{iScale:o,vScale:a,index:l}=r,d=o.axis,c=a.axis,u=Lte(o,a,r),f=e.length;let p;for(let g=0;gt[r].axis===e).shift()}function Ute(n,e){return P0(n,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}function Hte(n,e,t){return P0(n,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:t,index:e,mode:"default",type:"data"})}function Tw(n,e){const t=n.controller.index,r=n.vScale&&n.vScale.axis;if(r){e=e||n._parsed;for(const i of e){const o=i._stacks;if(!o||o[r]===void 0||o[r][t]===void 0)return;delete o[r][t],o[r]._visualValues!==void 0&&o[r]._visualValues[t]!==void 0&&delete o[r]._visualValues[t]}}}const uP=n=>n==="reset"||n==="none",MO=(n,e)=>e?n:Object.assign({},n),qte=(n,e,t)=>n&&!e.hidden&&e._stacked&&{keys:pU(t,!0),values:null};class l0{constructor(e,t){this.chart=e,this._ctx=e.ctx,this.index=t,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const e=this._cachedMeta;this.configure(),this.linkScales(),e._stacked=dP(e.vScale,e),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(e){this.index!==e&&Tw(this._cachedMeta),this.index=e}linkScales(){const e=this.chart,t=this._cachedMeta,r=this.getDataset(),i=(f,p,g,m)=>f==="x"?p:f==="r"?m:g,o=t.xAxisID=In(r.xAxisID,cP(e,"x")),a=t.yAxisID=In(r.yAxisID,cP(e,"y")),l=t.rAxisID=In(r.rAxisID,cP(e,"r")),d=t.indexAxis,c=t.iAxisID=i(d,o,a,l),u=t.vAxisID=i(d,a,o,l);t.xScale=this.getScaleForId(o),t.yScale=this.getScaleForId(a),t.rScale=this.getScaleForId(l),t.iScale=this.getScaleForId(c),t.vScale=this.getScaleForId(u)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(e){return this.chart.scales[e]}_getOtherScale(e){const t=this._cachedMeta;return e===t.iScale?t.vScale:t.iScale}reset(){this._update("reset")}_destroy(){const e=this._cachedMeta;this._data&&yO(this._data,this),e._stacked&&Tw(e)}_dataCheck(){const e=this.getDataset(),t=e.data||(e.data=[]),r=this._data;if(Yn(t)){const i=this._cachedMeta;this._data=Ote(t,i)}else if(r!==t){if(r){yO(r,this);const i=this._cachedMeta;Tw(i),i._parsed=[]}t&&Object.isExtensible(t)&&jee(t,this),this._syncList=[],this._data=t}}addElements(){const e=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(e.dataset=new this.datasetElementType)}buildOrUpdateElements(e){const t=this._cachedMeta,r=this.getDataset();let i=!1;this._dataCheck();const o=t._stacked;t._stacked=dP(t.vScale,t),t.stack!==r.stack&&(i=!0,Tw(t),t.stack=r.stack),this._resyncElements(e),(i||o!==t._stacked)&&(IO(this,t._parsed),t._stacked=dP(t.vScale,t))}configure(){const e=this.chart.config,t=e.datasetScopeKeys(this._type),r=e.getOptionScopes(this.getDataset(),t,!0);this.options=e.createResolver(r,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(e,t){const{_cachedMeta:r,_data:i}=this,{iScale:o,_stacked:a}=r,l=o.axis;let d=e===0&&t===i.length?!0:r._sorted,c=e>0&&r._parsed[e-1],u,f,p;if(this._parsing===!1)r._parsed=i,r._sorted=!0,p=i;else{ki(i[e])?p=this.parseArrayData(r,i,e,t):Yn(i[e])?p=this.parseObjectData(r,i,e,t):p=this.parsePrimitiveData(r,i,e,t);const g=()=>f[l]===null||c&&f[l]y||f=0;--p)if(!m()){this.updateRangeFromParsed(c,e,g,d);break}}return c}getAllParsedValues(e){const t=this._cachedMeta._parsed,r=[];let i,o,a;for(i=0,o=t.length;i=0&&ethis.getContext(r,i,t),y=c.resolveNamedOptions(p,g,m,f);return y.$shared&&(y.$shared=d,o[a]=Object.freeze(MO(y,d))),y}_resolveAnimations(e,t,r){const i=this.chart,o=this._cachedDataOpts,a=`animation-${t}`,l=o[a];if(l)return l;let d;if(i.options.animation!==!1){const u=this.chart.config,f=u.datasetAnimationScopeKeys(this._type,t),p=u.getOptionScopes(this.getDataset(),f);d=u.createResolver(p,this.getContext(e,r,t))}const c=new L6(i,d&&d.animations);return d&&d._cacheable&&(o[a]=Object.freeze(c)),c}getSharedOptions(e){if(e.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},e))}includeOptions(e,t){return!t||uP(e)||this.chart._animationsDisabled}_getSharedOptions(e,t){const r=this.resolveDataElementOptions(e,t),i=this._sharedOptions,o=this.getSharedOptions(r),a=this.includeOptions(t,o)||o!==i;return this.updateSharedOptions(o,t,r),{sharedOptions:o,includeOptions:a}}updateElement(e,t,r,i){uP(i)?Object.assign(e,r):this._resolveAnimations(t,i).update(e,r)}updateSharedOptions(e,t,r){e&&!uP(t)&&this._resolveAnimations(void 0,t).update(e,r)}_setStyle(e,t,r,i){e.active=i;const o=this.getStyle(t,i);this._resolveAnimations(t,r,i).update(e,{options:!i&&this.getSharedOptions(o)||o})}removeHoverStyle(e,t,r){this._setStyle(e,r,"active",!1)}setHoverStyle(e,t,r){this._setStyle(e,r,"active",!0)}_removeDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!1)}_setDatasetHoverStyle(){const e=this._cachedMeta.dataset;e&&this._setStyle(e,void 0,"active",!0)}_resyncElements(e){const t=this._data,r=this._cachedMeta.data;for(const[l,d,c]of this._syncList)this[l](d,c);this._syncList=[];const i=r.length,o=t.length,a=Math.min(o,i);a&&this.parse(0,a),o>i?this._insertElements(i,o-i,e):o{for(c.length+=t,l=c.length-1;l>=a;l--)c[l]=c[l-t]};for(d(o),l=e;li-o))}return n._cache.$bar}function Gte(n){const e=n.iScale,t=Vte(e,n.type);let r=e._length,i,o,a,l;const d=()=>{a===32767||a===-32768||(ol(l)&&(r=Math.min(r,Math.abs(a-l)||r)),l=a)};for(i=0,o=t.length;i0?i[n-1]:null,l=nMath.abs(l)&&(d=l,c=a),e[t.axis]=c,e._custom={barStart:d,barEnd:c,start:i,end:o,min:a,max:l}}function gU(n,e,t,r){return ki(n)?Yte(n,e,t,r):e[t.axis]=t.parse(n,r),e}function zO(n,e,t,r){const i=n.iScale,o=n.vScale,a=i.getLabels(),l=i===o,d=[];let c,u,f,p;for(c=t,u=t+r;c=t?1:-1)}function $te(n){let e,t,r,i,o;return n.horizontal?(e=n.base>n.x,t="left",r="right"):(e=n.baseu.controller.options.grouped),o=r.options.stacked,a=[],l=this._cachedMeta.controller.getParsed(t),d=l&&l[r.axis],c=u=>{const f=u._parsed.find(g=>g[r.axis]===d),p=f&&f[u.vScale.axis];if(Ur(p)||isNaN(p))return!0};for(const u of i)if(!(t!==void 0&&c(u))&&((o===!1||a.indexOf(u.stack)===-1||o===void 0&&u.stack===void 0)&&a.push(u.stack),u.index===e))break;return a.length||a.push(void 0),a}_getStackCount(e){return this._getStacks(void 0,e).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const e=this.chart.scales,t=this.chart.options.indexAxis;return Object.keys(e).filter(r=>e[r].axis===t).shift()}_getAxis(){const e={},t=this.getFirstScaleIdForIndexAxis();for(const r of this.chart.data.datasets)e[In(this.chart.options.indexAxis==="x"?r.xAxisID:r.yAxisID,t)]=!0;return Object.keys(e)}_getStackIndex(e,t,r){const i=this._getStacks(e,r),o=t!==void 0?i.indexOf(t):-1;return o===-1?i.length-1:o}_getRuler(){const e=this.options,t=this._cachedMeta,r=t.iScale,i=[];let o,a;for(o=0,a=t.data.length;oKA(S,l,d,!0)?1:Math.max(_,_*t,b,b*t),m=(S,_,b)=>KA(S,l,d,!0)?-1:Math.min(_,_*t,b,b*t),y=g(0,c,f),v=g(Po,u,p),x=m(Or,c,f),w=m(Or+Po,u,p);r=(y-x)/2,i=(v-w)/2,o=-(y+x)/2,a=-(v+w)/2}return{ratioX:r,ratioY:i,offsetX:o,offsetY:a}}class eS extends l0{constructor(e,t){super(e,t),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(e,t){const r=this.getDataset().data,i=this._cachedMeta;if(this._parsing===!1)i._parsed=r;else{let o=d=>+r[d];if(Yn(r[e])){const{key:d="value"}=this._parsing;o=c=>+g0(r[c],d)}let a,l;for(a=e,l=e+t;a0&&!isNaN(e)?Eo*(Math.abs(e)/t):0}getLabelAndValue(e){const t=this._cachedMeta,r=this.chart,i=r.data.labels||[],o=R6(t._parsed[e],r.options.locale);return{label:i[e]||"",value:o}}getMaxBorderWidth(e){let t=0;const r=this.chart;let i,o,a,l,d;if(!e){for(i=0,o=r.data.datasets.length;ie!=="spacing",_indexable:e=>e!=="spacing"&&!e.startsWith("borderDash")&&!e.startsWith("hoverBorderDash")}),ve(eS,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(e){const t=e.data,{labels:{pointStyle:r,textAlign:i,color:o,useBorderRadius:a,borderRadius:l}}=e.legend.options;return t.labels.length&&t.datasets.length?t.labels.map((d,c)=>{const f=e.getDatasetMeta(0).controller.getStyle(c);return{text:d,fillStyle:f.backgroundColor,fontColor:o,hidden:!e.getDataVisibility(c),lineDash:f.borderDash,lineDashOffset:f.borderDashOffset,lineJoin:f.borderJoinStyle,lineWidth:f.borderWidth,strokeStyle:f.borderColor,textAlign:i,pointStyle:r,borderRadius:a&&(l||f.borderRadius),index:c}}):[]}},onClick(e,t,r){r.chart.toggleDataVisibility(t.index),r.chart.update()}}}});class p5 extends l0{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(e){const t=this._cachedMeta,{dataset:r,data:i=[],_dataset:o}=t,a=this.chart._animationsDisabled;let{start:l,count:d}=Cee(t,i,a);this._drawStart=l,this._drawCount=d,Aee(t)&&(l=0,d=i.length),r._chart=this.chart,r._datasetIndex=this.index,r._decimated=!!o._decimated,r.points=i;const c=this.resolveDatasetElementOptions(e);this.options.showLine||(c.borderWidth=0),c.segment=this.options.segment,this.updateElement(r,void 0,{animated:!a,options:c},e),this.updateElements(i,l,d,e)}updateElements(e,t,r,i){const o=i==="reset",{iScale:a,vScale:l,_stacked:d,_dataset:c}=this._cachedMeta,{sharedOptions:u,includeOptions:f}=this._getSharedOptions(t,i),p=a.axis,g=l.axis,{spanGaps:m,segment:y}=this.options,v=m0(m)?m:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||i==="none",w=t+r,S=e.length;let _=t>0&&this.getParsed(t-1);for(let b=0;b=w){T.skip=!0;continue}const F=this.getParsed(b),A=Ur(F[g]),D=T[p]=a.getPixelForValue(F[p],b),P=T[g]=o||A?l.getBasePixel():l.getPixelForValue(d?this.applyStack(l,F,d):F[g],b);T.skip=isNaN(D)||isNaN(P)||A,T.stop=b>0&&Math.abs(F[p]-_[p])>v,y&&(T.parsed=F,T.raw=c.data[b]),f&&(T.options=u||this.resolveDataElementOptions(b,C.active?"active":i)),x||this.updateElement(C,b,T,i),_=F}}getMaxOverflow(){const e=this._cachedMeta,t=e.dataset,r=t.options&&t.options.borderWidth||0,i=e.data||[];if(!i.length)return r;const o=i[0].size(this.resolveDataElementOptions(0)),a=i[i.length-1].size(this.resolveDataElementOptions(i.length-1));return Math.max(r,o,a)/2}draw(){const e=this._cachedMeta;e.dataset.updateControlPoints(this.chart.chartArea,e.iScale.axis),super.draw()}}ve(p5,"id","line"),ve(p5,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),ve(p5,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});function nm(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class N6{constructor(e){ve(this,"options");this.options=e||{}}static override(e){Object.assign(N6.prototype,e)}init(){}formats(){return nm()}parse(){return nm()}format(){return nm()}add(){return nm()}diff(){return nm()}startOf(){return nm()}endOf(){return nm()}}var nne={_date:N6};function rne(n,e,t,r){const{controller:i,data:o,_sorted:a}=n,l=i._cachedMeta.iScale,d=n.dataset&&n.dataset.options?n.dataset.options.spanGaps:null;if(l&&e===l.axis&&e!=="r"&&a&&o.length){const c=l._reversePixels?wee:vm;if(r){if(i._sharedOptions){const u=o[0],f=typeof u.getRange=="function"&&u.getRange(e);if(f){const p=c(o,e,t-f),g=c(o,e,t+f);return{lo:p.lo,hi:g.hi}}}}else{const u=c(o,e,t);if(d){const{vScale:f}=i._cachedMeta,{_parsed:p}=n,g=p.slice(0,u.lo+1).reverse().findIndex(y=>!Ur(y[f.axis]));u.lo-=Math.max(0,g);const m=p.slice(u.hi).findIndex(y=>!Ur(y[f.axis]));u.hi+=Math.max(0,m)}return u}}return{lo:0,hi:o.length-1}}function kF(n,e,t,r,i){const o=n.getSortedVisibleDatasetMetas(),a=t[e];for(let l=0,d=o.length;l{d[a]&&d[a](e[t],i)&&(o.push({element:d,datasetIndex:c,index:u}),l=l||d.inRange(e.x,e.y,i))}),r&&!l?[]:o}var ane={modes:{index(n,e,t,r){const i=om(e,n),o=t.axis||"x",a=t.includeInvisible||!1,l=t.intersect?fP(n,i,o,r,a):pP(n,i,o,!1,r,a),d=[];return l.length?(n.getSortedVisibleDatasetMetas().forEach(c=>{const u=l[0].index,f=c.data[u];f&&!f.skip&&d.push({element:f,datasetIndex:c.index,index:u})}),d):[]},dataset(n,e,t,r){const i=om(e,n),o=t.axis||"xy",a=t.includeInvisible||!1;let l=t.intersect?fP(n,i,o,r,a):pP(n,i,o,!1,r,a);if(l.length>0){const d=l[0].datasetIndex,c=n.getDatasetMeta(d).data;l=[];for(let u=0;ut.pos===e)}function WO(n,e){return n.filter(t=>mU.indexOf(t.pos)===-1&&t.box.axis===e)}function Dw(n,e){return n.sort((t,r)=>{const i=e?r:t,o=e?t:r;return i.weight===o.weight?i.index-o.index:i.weight-o.weight})}function lne(n){const e=[];let t,r,i,o,a,l;for(t=0,r=(n||[]).length;tc.box.fullSize),!0),r=Dw(Fw(e,"left"),!0),i=Dw(Fw(e,"right")),o=Dw(Fw(e,"top"),!0),a=Dw(Fw(e,"bottom")),l=WO(e,"x"),d=WO(e,"y");return{fullSize:t,leftAndTop:r.concat(o),rightAndBottom:i.concat(d).concat(a).concat(l),chartArea:Fw(e,"chartArea"),vertical:r.concat(i).concat(d),horizontal:o.concat(a).concat(l)}}function UO(n,e,t,r){return Math.max(n[t],e[t])+Math.max(n[r],e[r])}function yU(n,e){n.top=Math.max(n.top,e.top),n.left=Math.max(n.left,e.left),n.bottom=Math.max(n.bottom,e.bottom),n.right=Math.max(n.right,e.right)}function hne(n,e,t,r){const{pos:i,box:o}=t,a=n.maxPadding;if(!Yn(i)){t.size&&(n[i]-=t.size);const f=r[t.stack]||{size:0,count:1};f.size=Math.max(f.size,t.horizontal?o.height:o.width),t.size=f.size/f.count,n[i]+=t.size}o.getPadding&&yU(a,o.getPadding());const l=Math.max(0,e.outerWidth-UO(a,n,"left","right")),d=Math.max(0,e.outerHeight-UO(a,n,"top","bottom")),c=l!==n.w,u=d!==n.h;return n.w=l,n.h=d,t.horizontal?{same:c,other:u}:{same:u,other:c}}function fne(n){const e=n.maxPadding;function t(r){const i=Math.max(e[r]-n[r],0);return n[r]+=i,i}n.y+=t("top"),n.x+=t("left"),t("right"),t("bottom")}function pne(n,e){const t=e.maxPadding;function r(i){const o={left:0,top:0,right:0,bottom:0};return i.forEach(a=>{o[a]=Math.max(e[a],t[a])}),o}return r(n?["left","right"]:["top","bottom"])}function tS(n,e,t,r){const i=[];let o,a,l,d,c,u;for(o=0,a=n.length,c=0;o{typeof y.beforeLayout=="function"&&y.beforeLayout()});const u=d.reduce((y,v)=>v.box.options&&v.box.options.display===!1?y:y+1,0)||1,f=Object.freeze({outerWidth:e,outerHeight:t,padding:i,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/u,hBoxMaxHeight:a/2}),p=Object.assign({},i);yU(p,sa(r));const g=Object.assign({maxPadding:p,w:o,h:a,x:i.left,y:i.top},i),m=cne(d.concat(c),f);tS(l.fullSize,g,f,m),tS(d,g,f,m),tS(c,g,f,m)&&tS(d,g,f,m),fne(g),HO(l.leftAndTop,g,f,m),g.x+=g.w,g.y+=g.h,HO(l.rightAndBottom,g,f,m),n.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},Yr(l.chartArea,y=>{const v=y.box;Object.assign(v,n.chartArea),v.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})})}};class xU{acquireContext(e,t){}releaseContext(e){return!1}addEventListener(e,t,r){}removeEventListener(e,t,r){}getDevicePixelRatio(){return 1}getMaximumSize(e,t,r,i){return t=Math.max(0,t||e.width),r=r||e.height,{width:t,height:Math.max(0,i?Math.floor(t/i):r)}}isAttached(e){return!0}updateConfig(e){}}class gne extends xU{acquireContext(e){return e&&e.getContext&&e.getContext("2d")||null}updateConfig(e){e.options.animation=!1}}const g5="$chartjs",mne={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},qO=n=>n===null||n==="";function yne(n,e){const t=n.style,r=n.getAttribute("height"),i=n.getAttribute("width");if(n[g5]={initial:{height:r,width:i,style:{display:t.display,height:t.height,width:t.width}}},t.display=t.display||"block",t.boxSizing=t.boxSizing||"border-box",qO(i)){const o=AO(n,"width");o!==void 0&&(n.width=o)}if(qO(r))if(n.style.height==="")n.height=n.width/(e||2);else{const o=AO(n,"height");o!==void 0&&(n.height=o)}return n}const bU=mte?{passive:!0}:!1;function xne(n,e,t){n&&n.addEventListener(e,t,bU)}function bne(n,e,t){n&&n.canvas&&n.canvas.removeEventListener(e,t,bU)}function vne(n,e){const t=mne[n.type]||n.type,{x:r,y:i}=om(n,e);return{type:t,chart:e,native:n,x:r!==void 0?r:null,y:i!==void 0?i:null}}function YA(n,e){for(const t of n)if(t===e||t.contains(e))return!0}function wne(n,e,t){const r=n.canvas,i=new MutationObserver(o=>{let a=!1;for(const l of o)a=a||YA(l.addedNodes,r),a=a&&!YA(l.removedNodes,r);a&&t()});return i.observe(document,{childList:!0,subtree:!0}),i}function Sne(n,e,t){const r=n.canvas,i=new MutationObserver(o=>{let a=!1;for(const l of o)a=a||YA(l.removedNodes,r),a=a&&!YA(l.addedNodes,r);a&&t()});return i.observe(document,{childList:!0,subtree:!0}),i}const Rj=new Map;let VO=0;function vU(){const n=window.devicePixelRatio;n!==VO&&(VO=n,Rj.forEach((e,t)=>{t.currentDevicePixelRatio!==n&&e()}))}function jne(n,e){Rj.size||window.addEventListener("resize",vU),Rj.set(n,e)}function kne(n){Rj.delete(n),Rj.size||window.removeEventListener("resize",vU)}function _ne(n,e,t){const r=n.canvas,i=r&&O6(r);if(!i)return;const o=tU((l,d)=>{const c=i.clientWidth;t(l,d),c{const d=l[0],c=d.contentRect.width,u=d.contentRect.height;c===0&&u===0||o(c,u)});return a.observe(i),jne(n,o),a}function gP(n,e,t){t&&t.disconnect(),e==="resize"&&kne(n)}function Cne(n,e,t){const r=n.canvas,i=tU(o=>{n.ctx!==null&&t(vne(o,n))},n);return xne(r,e,i),i}class Ane extends xU{acquireContext(e,t){const r=e&&e.getContext&&e.getContext("2d");return r&&r.canvas===e?(yne(e,t),r):null}releaseContext(e){const t=e.canvas;if(!t[g5])return!1;const r=t[g5].initial;["height","width"].forEach(o=>{const a=r[o];Ur(a)?t.removeAttribute(o):t.setAttribute(o,a)});const i=r.style||{};return Object.keys(i).forEach(o=>{t.style[o]=i[o]}),t.width=t.width,delete t[g5],!0}addEventListener(e,t,r){this.removeEventListener(e,t);const i=e.$proxies||(e.$proxies={}),a={attach:wne,detach:Sne,resize:_ne}[t]||Cne;i[t]=a(e,t,r)}removeEventListener(e,t){const r=e.$proxies||(e.$proxies={}),i=r[t];if(!i)return;({attach:gP,detach:gP,resize:gP}[t]||bne)(e,t,i),r[t]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(e,t,r,i){return gte(e,t,r,i)}isAttached(e){const t=e&&O6(e);return!!(t&&t.isConnected)}}function Tne(n){return!z6()||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas?gne:Ane}class Oo{constructor(){ve(this,"x");ve(this,"y");ve(this,"active",!1);ve(this,"options");ve(this,"$animations")}tooltipPosition(e){const{x:t,y:r}=this.getProps(["x","y"],e);return{x:t,y:r}}hasValue(){return m0(this.x)&&m0(this.y)}getProps(e,t){const r=this.$animations;if(!t||!r)return this;const i={};return e.forEach(o=>{i[o]=r[o]&&r[o].active()?r[o]._to:this[o]}),i}}ve(Oo,"defaults",{}),ve(Oo,"defaultRoutes");function Fne(n,e){const t=n.options.ticks,r=Dne(n),i=Math.min(t.maxTicksLimit||r,r),o=t.major.enabled?Pne(e):[],a=o.length,l=o[0],d=o[a-1],c=[];if(a>i)return Rne(e,c,o,a/i),c;const u=Ene(o,e,i);if(a>0){let f,p;const g=a>1?Math.round((d-l)/(a-1)):null;for(S2(e,c,u,Ur(g)?0:l-g,l),f=0,p=a-1;fi)return d}return Math.max(i,1)}function Pne(n){const e=[];let t,r;for(t=0,r=n.length;tn==="left"?"right":n==="right"?"left":n,GO=(n,e,t)=>e==="top"||e==="left"?n[e]+t:n[e]-t,KO=(n,e)=>Math.min(e||n,n);function XO(n,e){const t=[],r=n.length/e,i=n.length;let o=0;for(;oa+l)))return d}function zne(n,e){Yr(n,t=>{const r=t.gc,i=r.length/2;let o;if(i>e){for(o=0;or?r:t,r=i&&t>r?t:r,{min:Hc(t,Hc(r,t)),max:Hc(r,Hc(t,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const e=this.chart.data;return this.options.labels||(this.isHorizontal()?e.xLabels:e.yLabels)||e.labels||[]}getLabelItems(e=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(e))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){li(this.options.beforeUpdate,[this])}update(e,t,r){const{beginAtZero:i,grace:o,ticks:a}=this.options,l=a.sampleSize;this.beforeUpdate(),this.maxWidth=e,this.maxHeight=t,this._margins=r=Object.assign({left:0,right:0,top:0,bottom:0},r),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+r.left+r.right:this.height+r.top+r.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Kee(this,o,i),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const d=l=o||r<=1||!this.isHorizontal()){this.labelRotation=i;return}const u=this._getLabelSizes(),f=u.widest.width,p=u.highest.height,g=Wl(this.chart.width-f,0,this.maxWidth);l=e.offset?this.maxWidth/r:g/(r-1),f+6>l&&(l=g/(r-(e.offset?.5:1)),d=this.maxHeight-Ew(e.grid)-t.padding-YO(e.title,this.chart.options.font),c=Math.sqrt(f*f+p*p),a=$9(Math.min(Math.asin(Wl((u.highest.height+6)/l,-1,1)),Math.asin(Wl(d/c,-1,1))-Math.asin(Wl(p/c,-1,1)))),a=Math.max(i,Math.min(o,a))),this.labelRotation=a}afterCalculateLabelRotation(){li(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){li(this.options.beforeFit,[this])}fit(){const e={width:0,height:0},{chart:t,options:{ticks:r,title:i,grid:o}}=this,a=this._isVisible(),l=this.isHorizontal();if(a){const d=YO(i,t.options.font);if(l?(e.width=this.maxWidth,e.height=Ew(o)+d):(e.height=this.maxHeight,e.width=Ew(o)+d),r.display&&this.ticks.length){const{first:c,last:u,widest:f,highest:p}=this._getLabelSizes(),g=r.padding*2,m=fo(this.labelRotation),y=Math.cos(m),v=Math.sin(m);if(l){const x=r.mirror?0:v*f.width+y*p.height;e.height=Math.min(this.maxHeight,e.height+x+g)}else{const x=r.mirror?0:y*f.width+v*p.height;e.width=Math.min(this.maxWidth,e.width+x+g)}this._calculatePadding(c,u,v,y)}}this._handleMargins(),l?(this.width=this._length=t.width-this._margins.left-this._margins.right,this.height=e.height):(this.width=e.width,this.height=this._length=t.height-this._margins.top-this._margins.bottom)}_calculatePadding(e,t,r,i){const{ticks:{align:o,padding:a},position:l}=this.options,d=this.labelRotation!==0,c=l!=="top"&&this.axis==="x";if(this.isHorizontal()){const u=this.getPixelForTick(0)-this.left,f=this.right-this.getPixelForTick(this.ticks.length-1);let p=0,g=0;d?c?(p=i*e.width,g=r*t.height):(p=r*e.height,g=i*t.width):o==="start"?g=t.width:o==="end"?p=e.width:o!=="inner"&&(p=e.width/2,g=t.width/2),this.paddingLeft=Math.max((p-u+a)*this.width/(this.width-u),0),this.paddingRight=Math.max((g-f+a)*this.width/(this.width-f),0)}else{let u=t.height/2,f=e.height/2;o==="start"?(u=0,f=e.height):o==="end"&&(u=t.height,f=0),this.paddingTop=u+a,this.paddingBottom=f+a}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){li(this.options.afterFit,[this])}isHorizontal(){const{axis:e,position:t}=this.options;return t==="top"||t==="bottom"||e==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(e){this.beforeTickToLabelConversion(),this.generateTickLabels(e);let t,r;for(t=0,r=e.length;t({width:a[A]||0,height:l[A]||0});return{first:F(0),last:F(t-1),widest:F(C),highest:F(T),widths:a,heights:l}}getLabelForValue(e){return e}getPixelForValue(e,t){return NaN}getValueForPixel(e){}getPixelForTick(e){const t=this.ticks;return e<0||e>t.length-1?null:this.getPixelForValue(t[e].value)}getPixelForDecimal(e){this._reversePixels&&(e=1-e);const t=this._startPixel+e*this._length;return vee(this._alignToPixels?tm(this.chart,t,0):t)}getDecimalForPixel(e){const t=(e-this._startPixel)/this._length;return this._reversePixels?1-t:t}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:e,max:t}=this;return e<0&&t<0?t:e>0&&t>0?e:0}getContext(e){const t=this.ticks||[];if(e>=0&&el*i?l/r:d/i:d*i0}_computeGridLineItems(e){const t=this.axis,r=this.chart,i=this.options,{grid:o,position:a,border:l}=i,d=o.offset,c=this.isHorizontal(),f=this.ticks.length+(d?1:0),p=Ew(o),g=[],m=l.setContext(this.getContext()),y=m.display?m.width:0,v=y/2,x=function(M){return tm(r,M,y)};let w,S,_,b,C,T,F,A,D,P,L,W;if(a==="top")w=x(this.bottom),T=this.bottom-p,A=w-v,P=x(e.top)+v,W=e.bottom;else if(a==="bottom")w=x(this.top),P=e.top,W=x(e.bottom)-v,T=w+v,A=this.top+p;else if(a==="left")w=x(this.right),C=this.right-p,F=w-v,D=x(e.left)+v,L=e.right;else if(a==="right")w=x(this.left),D=e.left,L=x(e.right)-v,C=w+v,F=this.left+p;else if(t==="x"){if(a==="center")w=x((e.top+e.bottom)/2+.5);else if(Yn(a)){const M=Object.keys(a)[0],I=a[M];w=x(this.chart.scales[M].getPixelForValue(I))}P=e.top,W=e.bottom,T=w+v,A=T+p}else if(t==="y"){if(a==="center")w=x((e.left+e.right)/2);else if(Yn(a)){const M=Object.keys(a)[0],I=a[M];w=x(this.chart.scales[M].getPixelForValue(I))}C=w-v,F=C-p,D=e.left,L=e.right}const O=In(i.ticks.maxTicksLimit,f),U=Math.max(1,Math.ceil(f/O));for(S=0;S0&&(ye-=J/2);break}te={left:ye,top:ne,width:J+re.width,height:me+re.height,color:U.backdropColor}}v.push({label:_,font:A,textOffset:L,options:{rotation:y,color:I,strokeColor:H,strokeWidth:z,textAlign:G,textBaseline:W,translation:[b,C],backdrop:te}})}return v}_getXAxisLabelAlignment(){const{position:e,ticks:t}=this.options;if(-fo(this.labelRotation))return e==="top"?"left":"right";let i="center";return t.align==="start"?i="left":t.align==="end"?i="right":t.align==="inner"&&(i="inner"),i}_getYAxisLabelAlignment(e){const{position:t,ticks:{crossAlign:r,mirror:i,padding:o}}=this.options,a=this._getLabelSizes(),l=e+o,d=a.widest.width;let c,u;return t==="left"?i?(u=this.right+o,r==="near"?c="left":r==="center"?(c="center",u+=d/2):(c="right",u+=d)):(u=this.right-l,r==="near"?c="right":r==="center"?(c="center",u-=d/2):(c="left",u=this.left)):t==="right"?i?(u=this.left+o,r==="near"?c="right":r==="center"?(c="center",u-=d/2):(c="left",u-=d)):(u=this.left+l,r==="near"?c="left":r==="center"?(c="center",u+=d/2):(c="right",u=this.right)):c="right",{textAlign:c,x:u}}_computeLabelArea(){if(this.options.ticks.mirror)return;const e=this.chart,t=this.options.position;if(t==="left"||t==="right")return{top:0,left:this.left,bottom:e.height,right:this.right};if(t==="top"||t==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:e.width}}drawBackground(){const{ctx:e,options:{backgroundColor:t},left:r,top:i,width:o,height:a}=this;t&&(e.save(),e.fillStyle=t,e.fillRect(r,i,o,a),e.restore())}getLineWidthForValue(e){const t=this.options.grid;if(!this._isVisible()||!t.display)return 0;const i=this.ticks.findIndex(o=>o.value===e);return i>=0?t.setContext(this.getContext(i)).lineWidth:0}drawGrid(e){const t=this.options.grid,r=this.ctx,i=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(e));let o,a;const l=(d,c,u)=>{!u.width||!u.color||(r.save(),r.lineWidth=u.width,r.strokeStyle=u.color,r.setLineDash(u.borderDash||[]),r.lineDashOffset=u.borderDashOffset,r.beginPath(),r.moveTo(d.x,d.y),r.lineTo(c.x,c.y),r.stroke(),r.restore())};if(t.display)for(o=0,a=i.length;o{this.draw(o)}}]:[{z:r,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:i,draw:()=>{this.drawBorder()}},{z:t,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(e){const t=this.chart.getSortedVisibleDatasetMetas(),r=this.axis+"AxisID",i=[];let o,a;for(o=0,a=t.length;o{const r=t.split("."),i=r.pop(),o=[n].concat(r).join("."),a=e[t].split("."),l=a.pop(),d=a.join(".");hs.route(o,i,d,l)})}function qne(n){return"id"in n&&"defaults"in n}class Vne{constructor(){this.controllers=new j2(l0,"datasets",!0),this.elements=new j2(Oo,"elements"),this.plugins=new j2(Object,"plugins"),this.scales=new j2(m1,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...e){this._each("register",e)}remove(...e){this._each("unregister",e)}addControllers(...e){this._each("register",e,this.controllers)}addElements(...e){this._each("register",e,this.elements)}addPlugins(...e){this._each("register",e,this.plugins)}addScales(...e){this._each("register",e,this.scales)}getController(e){return this._get(e,this.controllers,"controller")}getElement(e){return this._get(e,this.elements,"element")}getPlugin(e){return this._get(e,this.plugins,"plugin")}getScale(e){return this._get(e,this.scales,"scale")}removeControllers(...e){this._each("unregister",e,this.controllers)}removeElements(...e){this._each("unregister",e,this.elements)}removePlugins(...e){this._each("unregister",e,this.plugins)}removeScales(...e){this._each("unregister",e,this.scales)}_each(e,t,r){[...t].forEach(i=>{const o=r||this._getRegistryForType(i);r||o.isForType(i)||o===this.plugins&&i.id?this._exec(e,o,i):Yr(i,a=>{const l=r||this._getRegistryForType(a);this._exec(e,l,a)})})}_exec(e,t,r){const i=T6(e);li(r["before"+i],[],r),t[e](r),li(r["after"+i],[],r)}_getRegistryForType(e){for(let t=0;to.filter(l=>!a.some(d=>l.plugin.id===d.plugin.id));this._notify(i(t,r),e,"stop"),this._notify(i(r,t),e,"start")}}function Kne(n){const e={},t=[],r=Object.keys(Jc.plugins.items);for(let o=0;o1&&QO(n[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${n}' axis. Please provide 'axis' or 'position' option.`)}function $O(n,e,t){if(t[e+"AxisID"]===n)return{axis:e}}function ere(n,e){if(e.data&&e.data.datasets){const t=e.data.datasets.filter(r=>r.xAxisID===n||r.yAxisID===n);if(t.length)return $O(n,"x",t[0])||$O(n,"y",t[0])}return{}}function tre(n,e){const t=y0[n.type]||{scales:{}},r=e.scales||{},i=gB(n.type,e),o=Object.create(null);return Object.keys(r).forEach(a=>{const l=r[a];if(!Yn(l))return console.error(`Invalid scale configuration for scale: ${a}`);if(l._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${a}`);const d=mB(a,l,ere(a,n),hs.scales[l.type]),c=Zne(d,i),u=t.scales||{};o[a]=US(Object.create(null),[{axis:d},l,u[d],u[c]])}),n.data.datasets.forEach(a=>{const l=a.type||n.type,d=a.indexAxis||gB(l,e),u=(y0[l]||{}).scales||{};Object.keys(u).forEach(f=>{const p=$ne(f,d),g=a[p+"AxisID"]||p;o[g]=o[g]||Object.create(null),US(o[g],[{axis:p},r[g],u[f]])})}),Object.keys(o).forEach(a=>{const l=o[a];US(l,[hs.scales[l.type],hs.scale])}),o}function wU(n){const e=n.options||(n.options={});e.plugins=In(e.plugins,{}),e.scales=tre(n,e)}function SU(n){return n=n||{},n.datasets=n.datasets||[],n.labels=n.labels||[],n}function nre(n){return n=n||{},n.data=SU(n.data),wU(n),n}const ZO=new Map,jU=new Set;function k2(n,e){let t=ZO.get(n);return t||(t=e(),ZO.set(n,t),jU.add(t)),t}const Pw=(n,e,t)=>{const r=g0(e,t);r!==void 0&&n.add(r)};let rre=class{constructor(e){this._config=nre(e),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(e){this._config.type=e}get data(){return this._config.data}set data(e){this._config.data=SU(e)}get options(){return this._config.options}set options(e){this._config.options=e}get plugins(){return this._config.plugins}update(){const e=this._config;this.clearCache(),wU(e)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(e){return k2(e,()=>[[`datasets.${e}`,""]])}datasetAnimationScopeKeys(e,t){return k2(`${e}.transition.${t}`,()=>[[`datasets.${e}.transitions.${t}`,`transitions.${t}`],[`datasets.${e}`,""]])}datasetElementScopeKeys(e,t){return k2(`${e}-${t}`,()=>[[`datasets.${e}.elements.${t}`,`datasets.${e}`,`elements.${t}`,""]])}pluginScopeKeys(e){const t=e.id,r=this.type;return k2(`${r}-plugin-${t}`,()=>[[`plugins.${t}`,...e.additionalOptionScopes||[]]])}_cachedScopes(e,t){const r=this._scopeCache;let i=r.get(e);return(!i||t)&&(i=new Map,r.set(e,i)),i}getOptionScopes(e,t,r){const{options:i,type:o}=this,a=this._cachedScopes(e,r),l=a.get(t);if(l)return l;const d=new Set;t.forEach(u=>{e&&(d.add(e),u.forEach(f=>Pw(d,e,f))),u.forEach(f=>Pw(d,i,f)),u.forEach(f=>Pw(d,y0[o]||{},f)),u.forEach(f=>Pw(d,hs,f)),u.forEach(f=>Pw(d,fB,f))});const c=Array.from(d);return c.length===0&&c.push(Object.create(null)),jU.has(t)&&a.set(t,c),c}chartOptionScopes(){const{options:e,type:t}=this;return[e,y0[t]||{},hs.datasets[t]||{},{type:t},hs,fB]}resolveNamedOptions(e,t,r,i=[""]){const o={$shared:!0},{resolver:a,subPrefixes:l}=JO(this._resolverCache,e,i);let d=a;if(sre(a,t)){o.$shared=!1,r=il(r)?r():r;const c=this.createResolver(e,r,l);d=i1(a,r,c)}for(const c of t)o[c]=d[c];return o}createResolver(e,t,r=[""],i){const{resolver:o}=JO(this._resolverCache,e,r);return Yn(t)?i1(o,t,void 0,i):o}};function JO(n,e,t){let r=n.get(e);r||(r=new Map,n.set(e,r));const i=t.join();let o=r.get(i);return o||(o={resolver:B6(e,t),subPrefixes:t.filter(l=>!l.toLowerCase().includes("hover"))},r.set(i,o)),o}const ire=n=>Yn(n)&&Object.getOwnPropertyNames(n).some(e=>il(n[e]));function sre(n,e){const{isScriptable:t,isIndexable:r}=oU(n);for(const i of e){const o=t(i),a=r(i),l=(a||o)&&n[i];if(o&&(il(l)||ire(l))||a&&ki(l))return!0}return!1}var ore="4.5.1";const are=["top","bottom","left","right","chartArea"];function eL(n,e){return n==="top"||n==="bottom"||are.indexOf(n)===-1&&e==="x"}function tL(n,e){return function(t,r){return t[n]===r[n]?t[e]-r[e]:t[n]-r[n]}}function nL(n){const e=n.chart,t=e.options.animation;e.notifyPlugins("afterRender"),li(t&&t.onComplete,[n],e)}function lre(n){const e=n.chart,t=e.options.animation;li(t&&t.onProgress,[n],e)}function kU(n){return z6()&&typeof n=="string"?n=document.getElementById(n):n&&n.length&&(n=n[0]),n&&n.canvas&&(n=n.canvas),n}const m5={},rL=n=>{const e=kU(n);return Object.values(m5).filter(t=>t.canvas===e).pop()};function dre(n,e,t){const r=Object.keys(n);for(const i of r){const o=+i;if(o>=e){const a=n[i];delete n[i],(t>0||o>e)&&(n[o+t]=a)}}}function cre(n,e,t,r){return!t||n.type==="mouseout"?null:r?e:n}var Kf;let pf=(Kf=class{static register(...e){Jc.add(...e),iL()}static unregister(...e){Jc.remove(...e),iL()}constructor(e,t){const r=this.config=new rre(t),i=kU(e),o=rL(i);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=r.createResolver(r.chartOptionScopes(),this.getContext());this.platform=new(r.platform||Tne(i)),this.platform.updateConfig(r);const l=this.platform.acquireContext(i,a.aspectRatio),d=l&&l.canvas,c=d&&d.height,u=d&&d.width;if(this.id=aee(),this.ctx=l,this.canvas=d,this.width=u,this.height=c,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new Gne,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=kee(f=>this.update(f),a.resizeDelay||0),this._dataChanges=[],m5[this.id]=this,!l||!d){console.error("Failed to create chart: can't acquire context from the given item");return}ch.listen(this,"complete",nL),ch.listen(this,"progress",lre),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:e,maintainAspectRatio:t},width:r,height:i,_aspectRatio:o}=this;return Ur(e)?t&&o?o:i?r/i:null:e}get data(){return this.config.data}set data(e){this.config.data=e}get options(){return this._options}set options(e){this.config.options=e}get registry(){return Jc}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():CO(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return jO(this.canvas,this.ctx),this}stop(){return ch.stop(this),this}resize(e,t){ch.running(this)?this._resizeBeforeDraw={width:e,height:t}:this._resize(e,t)}_resize(e,t){const r=this.options,i=this.canvas,o=r.maintainAspectRatio&&this.aspectRatio,a=this.platform.getMaximumSize(i,e,t,o),l=r.devicePixelRatio||this.platform.getDevicePixelRatio(),d=this.width?"resize":"attach";this.width=a.width,this.height=a.height,this._aspectRatio=this.aspectRatio,CO(this,l,!0)&&(this.notifyPlugins("resize",{size:a}),li(r.onResize,[this,a],this),this.attached&&this._doResize(d)&&this.render())}ensureScalesHaveIDs(){const t=this.options.scales||{};Yr(t,(r,i)=>{r.id=i})}buildOrUpdateScales(){const e=this.options,t=e.scales,r=this.scales,i=Object.keys(r).reduce((a,l)=>(a[l]=!1,a),{});let o=[];t&&(o=o.concat(Object.keys(t).map(a=>{const l=t[a],d=mB(a,l),c=d==="r",u=d==="x";return{options:l,dposition:c?"chartArea":u?"bottom":"left",dtype:c?"radialLinear":u?"category":"linear"}}))),Yr(o,a=>{const l=a.options,d=l.id,c=mB(d,l),u=In(l.type,a.dtype);(l.position===void 0||eL(l.position,c)!==eL(a.dposition))&&(l.position=a.dposition),i[d]=!0;let f=null;if(d in r&&r[d].type===u)f=r[d];else{const p=Jc.getScale(u);f=new p({id:d,type:u,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(l,e)}),Yr(i,(a,l)=>{a||delete r[l]}),Yr(r,a=>{Ed.configure(this,a,a.options),Ed.addBox(this,a)})}_updateMetasets(){const e=this._metasets,t=this.data.datasets.length,r=e.length;if(e.sort((i,o)=>i.index-o.index),r>t){for(let i=t;it.length&&delete this._stacks,e.forEach((r,i)=>{t.filter(o=>o===r._dataset).length===0&&this._destroyDatasetMeta(i)})}buildOrUpdateControllers(){const e=[],t=this.data.datasets;let r,i;for(this._removeUnreferencedMetasets(),r=0,i=t.length;r{this.getDatasetMeta(t).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(e){const t=this.config;t.update();const r=this._options=t.createResolver(t.chartOptionScopes(),this.getContext()),i=this._animationsDisabled=!r.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:e,cancelable:!0})===!1)return;const o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let a=0;for(let c=0,u=this.data.datasets.length;c{c.reset()}),this._updateDatasets(e),this.notifyPlugins("afterUpdate",{mode:e}),this._layers.sort(tL("z","_idx"));const{_active:l,_lastEvent:d}=this;d?this._eventHandler(d,!0):l.length&&this._updateHoverStyles(l,l,!0),this.render()}_updateScales(){Yr(this.scales,e=>{Ed.removeBox(this,e)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const e=this.options,t=new Set(Object.keys(this._listeners)),r=new Set(e.events);(!pO(t,r)||!!this._responsiveListeners!==e.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:e}=this,t=this._getUniformDataChanges()||[];for(const{method:r,start:i,count:o}of t){const a=r==="_removeElements"?-o:o;dre(e,i,a)}}_getUniformDataChanges(){const e=this._dataChanges;if(!e||!e.length)return;this._dataChanges=[];const t=this.data.datasets.length,r=o=>new Set(e.filter(a=>a[0]===o).map((a,l)=>l+","+a.splice(1).join(","))),i=r(0);for(let o=1;oo.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(e){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;Ed.update(this,this.width,this.height,e);const t=this.chartArea,r=t.width<=0||t.height<=0;this._layers=[],Yr(this.boxes,i=>{r&&i.position==="chartArea"||(i.configure&&i.configure(),this._layers.push(...i._layers()))},this),this._layers.forEach((i,o)=>{i._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(e){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:e,cancelable:!0})!==!1){for(let t=0,r=this.data.datasets.length;t=0;--t)this._drawDataset(e[t]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(e){const t=this.ctx,r={meta:e,index:e.index,cancelable:!0},i=Dte(this,e);this.notifyPlugins("beforeDatasetDraw",r)!==!1&&(i&&wF(t,i),e.controller.draw(),i&&SF(t),r.cancelable=!1,this.notifyPlugins("afterDatasetDraw",r))}isPointInArea(e){return Dj(e,this.chartArea,this._minPadding)}getElementsAtEventForMode(e,t,r,i){const o=ane.modes[t];return typeof o=="function"?o(this,e,r,i):[]}getDatasetMeta(e){const t=this.data.datasets[e],r=this._metasets;let i=r.filter(o=>o&&o._dataset===t).pop();return i||(i={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:t&&t.order||0,index:e,_dataset:t,_parsed:[],_sorted:!1},r.push(i)),i}getContext(){return this.$context||(this.$context=P0(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(e){const t=this.data.datasets[e];if(!t)return!1;const r=this.getDatasetMeta(e);return typeof r.hidden=="boolean"?!r.hidden:!t.hidden}setDatasetVisibility(e,t){const r=this.getDatasetMeta(e);r.hidden=!t}toggleDataVisibility(e){this._hiddenIndices[e]=!this._hiddenIndices[e]}getDataVisibility(e){return!this._hiddenIndices[e]}_updateVisibility(e,t,r){const i=r?"show":"hide",o=this.getDatasetMeta(e),a=o.controller._resolveAnimations(void 0,i);ol(t)?(o.data[t].hidden=!r,this.update()):(this.setDatasetVisibility(e,r),a.update(o,{visible:r}),this.update(l=>l.datasetIndex===e?i:void 0))}hide(e,t){this._updateVisibility(e,t,!1)}show(e,t){this._updateVisibility(e,t,!0)}_destroyDatasetMeta(e){const t=this._metasets[e];t&&t.controller&&t.controller._destroy(),delete this._metasets[e]}_stop(){let e,t;for(this.stop(),ch.remove(this),e=0,t=this.data.datasets.length;e{t.addEventListener(this,o,a),e[o]=a},i=(o,a,l)=>{o.offsetX=a,o.offsetY=l,this._eventHandler(o)};Yr(this.options.events,o=>r(o,i))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const e=this._responsiveListeners,t=this.platform,r=(d,c)=>{t.addEventListener(this,d,c),e[d]=c},i=(d,c)=>{e[d]&&(t.removeEventListener(this,d,c),delete e[d])},o=(d,c)=>{this.canvas&&this.resize(d,c)};let a;const l=()=>{i("attach",l),this.attached=!0,this.resize(),r("resize",o),r("detach",a)};a=()=>{this.attached=!1,i("resize",o),this._stop(),this._resize(0,0),r("attach",l)},t.isAttached(this.canvas)?l():a()}unbindEvents(){Yr(this._listeners,(e,t)=>{this.platform.removeEventListener(this,t,e)}),this._listeners={},Yr(this._responsiveListeners,(e,t)=>{this.platform.removeEventListener(this,t,e)}),this._responsiveListeners=void 0}updateHoverStyle(e,t,r){const i=r?"set":"remove";let o,a,l,d;for(t==="dataset"&&(o=this.getDatasetMeta(e[0].datasetIndex),o.controller["_"+i+"DatasetHoverStyle"]()),l=0,d=e.length;l{const l=this.getDatasetMeta(o);if(!l)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:l.data[a],index:a}});!HA(r,t)&&(this._active=r,this._lastEvent=null,this._updateHoverStyles(r,t))}notifyPlugins(e,t,r){return this._plugins.notify(this,e,t,r)}isPluginEnabled(e){return this._plugins._cache.filter(t=>t.plugin.id===e).length===1}_updateHoverStyles(e,t,r){const i=this.options.hover,o=(d,c)=>d.filter(u=>!c.some(f=>u.datasetIndex===f.datasetIndex&&u.index===f.index)),a=o(t,e),l=r?e:o(e,t);a.length&&this.updateHoverStyle(a,i.mode,!1),l.length&&i.mode&&this.updateHoverStyle(l,i.mode,!0)}_eventHandler(e,t){const r={event:e,replay:t,cancelable:!0,inChartArea:this.isPointInArea(e)},i=a=>(a.options.events||this.options.events).includes(e.native.type);if(this.notifyPlugins("beforeEvent",r,i)===!1)return;const o=this._handleEvent(e,t,r.inChartArea);return r.cancelable=!1,this.notifyPlugins("afterEvent",r,i),(o||r.changed)&&this.render(),this}_handleEvent(e,t,r){const{_active:i=[],options:o}=this,a=t,l=this._getActiveElements(e,i,r,a),d=fee(e),c=cre(e,this._lastEvent,r,d);r&&(this._lastEvent=null,li(o.onHover,[e,l,this],this),d&&li(o.onClick,[e,l,this],this));const u=!HA(l,i);return(u||t)&&(this._active=l,this._updateHoverStyles(l,i,t)),this._lastEvent=c,u}_getActiveElements(e,t,r,i){if(e.type==="mouseout")return[];if(!r)return t;const o=this.options.hover;return this.getElementsAtEventForMode(e,o.mode,o,i)}},ve(Kf,"defaults",hs),ve(Kf,"instances",m5),ve(Kf,"overrides",y0),ve(Kf,"registry",Jc),ve(Kf,"version",ore),ve(Kf,"getChart",rL),Kf);function iL(){return Yr(pf.instances,n=>n._plugins.invalidate())}function _U(n,e,t=e){n.lineCap=In(t.borderCapStyle,e.borderCapStyle),n.setLineDash(In(t.borderDash,e.borderDash)),n.lineDashOffset=In(t.borderDashOffset,e.borderDashOffset),n.lineJoin=In(t.borderJoinStyle,e.borderJoinStyle),n.lineWidth=In(t.borderWidth,e.borderWidth),n.strokeStyle=In(t.borderColor,e.borderColor)}function ure(n,e,t){n.lineTo(t.x,t.y)}function hre(n){return n.stepped?Oee:n.tension||n.cubicInterpolationMode==="monotone"?Lee:ure}function CU(n,e,t={}){const r=n.length,{start:i=0,end:o=r-1}=t,{start:a,end:l}=e,d=Math.max(i,a),c=Math.min(o,l),u=il&&o>l;return{count:r,start:d,loop:e.loop,ilen:c(a+(c?l-_:_))%o,S=()=>{y!==v&&(n.lineTo(u,v),n.lineTo(u,y),n.lineTo(u,x))};for(d&&(g=i[w(0)],n.moveTo(g.x,g.y)),p=0;p<=l;++p){if(g=i[w(p)],g.skip)continue;const _=g.x,b=g.y,C=_|0;C===m?(bv&&(v=b),u=(f*u+_)/++f):(S(),n.lineTo(_,b),m=C,f=0,y=v=b),x=b}S()}function yB(n){const e=n.options,t=e.borderDash&&e.borderDash.length;return!n._decimated&&!n._loop&&!e.tension&&e.cubicInterpolationMode!=="monotone"&&!e.stepped&&!t?pre:fre}function gre(n){return n.stepped?yte:n.tension||n.cubicInterpolationMode==="monotone"?xte:am}function mre(n,e,t,r){let i=e._path;i||(i=e._path=new Path2D,e.path(i,t,r)&&i.closePath()),_U(n,e.options),n.stroke(i)}function yre(n,e,t,r){const{segments:i,options:o}=e,a=yB(e);for(const l of i)_U(n,o,l.style),n.beginPath(),a(n,e,l,{start:t,end:t+r-1})&&n.closePath(),n.stroke()}const xre=typeof Path2D=="function";function bre(n,e,t,r){xre&&!e.options.segment?mre(n,e,t,r):yre(n,e,t,r)}class qx extends Oo{constructor(e){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,e&&Object.assign(this,e)}updateControlPoints(e,t){const r=this.options;if((r.tension||r.cubicInterpolationMode==="monotone")&&!r.stepped&&!this._pointsUpdated){const i=r.spanGaps?this._loop:this._fullLoop;dte(this._points,r,e,i,t),this._pointsUpdated=!0}}set points(e){this._points=e,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=Cte(this,this.options.segment))}first(){const e=this.segments,t=this.points;return e.length&&t[e[0].start]}last(){const e=this.segments,t=this.points,r=e.length;return r&&t[e[r-1].end]}interpolate(e,t){const r=this.options,i=e[t],o=this.points,a=jte(this,{property:t,start:i,end:i});if(!a.length)return;const l=[],d=gre(r);let c,u;for(c=0,u=a.length;ce!=="borderDash"&&e!=="fill"});function sL(n,e,t,r){const i=n.options,{[t]:o}=n.getProps([t],r);return Math.abs(e-o){let{boxHeight:t=e,boxWidth:r=e}=n;return n.usePointStyle&&(t=Math.min(t,e),r=n.pointStyleWidth||Math.min(r,e)),{boxWidth:r,boxHeight:t,itemHeight:Math.max(e,t)}},_re=(n,e)=>n!==null&&e!==null&&n.datasetIndex===e.datasetIndex&&n.index===e.index;class aL extends Oo{constructor(e){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,t,r){this.maxWidth=e,this.maxHeight=t,this._margins=r,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const e=this.options.labels||{};let t=li(e.generateLabels,[this.chart],this)||[];e.filter&&(t=t.filter(r=>e.filter(r,this.chart.data))),e.sort&&(t=t.sort((r,i)=>e.sort(r,i,this.chart.data))),this.options.reverse&&t.reverse(),this.legendItems=t}fit(){const{options:e,ctx:t}=this;if(!e.display){this.width=this.height=0;return}const r=e.labels,i=Us(r.font),o=i.size,a=this._computeTitleHeight(),{boxWidth:l,itemHeight:d}=oL(r,o);let c,u;t.font=i.string,this.isHorizontal()?(c=this.maxWidth,u=this._fitRows(a,o,l,d)+10):(u=this.maxHeight,c=this._fitCols(a,i,l,d)+10),this.width=Math.min(c,e.maxWidth||this.maxWidth),this.height=Math.min(u,e.maxHeight||this.maxHeight)}_fitRows(e,t,r,i){const{ctx:o,maxWidth:a,options:{labels:{padding:l}}}=this,d=this.legendHitBoxes=[],c=this.lineWidths=[0],u=i+l;let f=e;o.textAlign="left",o.textBaseline="middle";let p=-1,g=-u;return this.legendItems.forEach((m,y)=>{const v=r+t/2+o.measureText(m.text).width;(y===0||c[c.length-1]+v+2*l>a)&&(f+=u,c[c.length-(y>0?0:1)]=0,g+=u,p++),d[y]={left:0,top:g,row:p,width:v,height:i},c[c.length-1]+=v+l}),f}_fitCols(e,t,r,i){const{ctx:o,maxHeight:a,options:{labels:{padding:l}}}=this,d=this.legendHitBoxes=[],c=this.columnSizes=[],u=a-e;let f=l,p=0,g=0,m=0,y=0;return this.legendItems.forEach((v,x)=>{const{itemWidth:w,itemHeight:S}=Cre(r,t,o,v,i);x>0&&g+S+2*l>u&&(f+=p+l,c.push({width:p,height:g}),m+=p+l,y++,p=g=0),d[x]={left:m,top:g,col:y,width:w,height:S},p=Math.max(p,w),g+=S+l}),f+=p,c.push({width:p,height:g}),f}adjustHitBoxes(){if(!this.options.display)return;const e=this._computeTitleHeight(),{legendHitBoxes:t,options:{align:r,labels:{padding:i},rtl:o}}=this,a=ib(o,this.left,this.width);if(this.isHorizontal()){let l=0,d=ta(r,this.left+i,this.right-this.lineWidths[l]);for(const c of t)l!==c.row&&(l=c.row,d=ta(r,this.left+i,this.right-this.lineWidths[l])),c.top+=this.top+e+i,c.left=a.leftForLtr(a.x(d),c.width),d+=c.width+i}else{let l=0,d=ta(r,this.top+e+i,this.bottom-this.columnSizes[l].height);for(const c of t)c.col!==l&&(l=c.col,d=ta(r,this.top+e+i,this.bottom-this.columnSizes[l].height)),c.top=d,c.left+=this.left+i,c.left=a.leftForLtr(a.x(c.left),c.width),d+=c.height+i}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){const e=this.ctx;wF(e,this),this._draw(),SF(e)}}_draw(){const{options:e,columnSizes:t,lineWidths:r,ctx:i}=this,{align:o,labels:a}=e,l=hs.color,d=ib(e.rtl,this.left,this.width),c=Us(a.font),{padding:u}=a,f=c.size,p=f/2;let g;this.drawTitle(),i.textAlign=d.textAlign("left"),i.textBaseline="middle",i.lineWidth=.5,i.font=c.string;const{boxWidth:m,boxHeight:y,itemHeight:v}=oL(a,f),x=function(C,T,F){if(isNaN(m)||m<=0||isNaN(y)||y<0)return;i.save();const A=In(F.lineWidth,1);if(i.fillStyle=In(F.fillStyle,l),i.lineCap=In(F.lineCap,"butt"),i.lineDashOffset=In(F.lineDashOffset,0),i.lineJoin=In(F.lineJoin,"miter"),i.lineWidth=A,i.strokeStyle=In(F.strokeStyle,l),i.setLineDash(In(F.lineDash,[])),a.usePointStyle){const D={radius:y*Math.SQRT2/2,pointStyle:F.pointStyle,rotation:F.rotation,borderWidth:A},P=d.xPlus(C,m/2),L=T+p;rU(i,D,P,L,a.pointStyleWidth&&m)}else{const D=T+Math.max((f-y)/2,0),P=d.leftForLtr(C,m),L=o0(F.borderRadius);i.beginPath(),Object.values(L).some(W=>W!==0)?Pj(i,{x:P,y:D,w:m,h:y,radius:L}):i.rect(P,D,m,y),i.fill(),A!==0&&i.stroke()}i.restore()},w=function(C,T,F){Ej(i,F.text,C,T+v/2,c,{strikethrough:F.hidden,textAlign:d.textAlign(F.textAlign)})},S=this.isHorizontal(),_=this._computeTitleHeight();S?g={x:ta(o,this.left+u,this.right-r[0]),y:this.top+u+_,line:0}:g={x:this.left+u,y:ta(o,this.top+_+u,this.bottom-t[0].height),line:0},uU(this.ctx,e.textDirection);const b=v+u;this.legendItems.forEach((C,T)=>{i.strokeStyle=C.fontColor,i.fillStyle=C.fontColor;const F=i.measureText(C.text).width,A=d.textAlign(C.textAlign||(C.textAlign=a.textAlign)),D=m+p+F;let P=g.x,L=g.y;d.setWidth(this.width),S?T>0&&P+D+u>this.right&&(L=g.y+=b,g.line++,P=g.x=ta(o,this.left+u,this.right-r[g.line])):T>0&&L+b>this.bottom&&(P=g.x=P+t[g.line].width+u,g.line++,L=g.y=ta(o,this.top+_+u,this.bottom-t[g.line].height));const W=d.x(P);if(x(W,L,C),P=_ee(A,P+m+p,S?P+D:this.right,e.rtl),w(d.x(P),L,C),S)g.x+=D+u;else if(typeof C.text!="string"){const O=c.lineHeight;g.y+=TU(C,O)+u}else g.y+=b}),hU(this.ctx,e.textDirection)}drawTitle(){const e=this.options,t=e.title,r=Us(t.font),i=sa(t.padding);if(!t.display)return;const o=ib(e.rtl,this.left,this.width),a=this.ctx,l=t.position,d=r.size/2,c=i.top+d;let u,f=this.left,p=this.width;if(this.isHorizontal())p=Math.max(...this.lineWidths),u=this.top+c,f=ta(e.align,f,this.right-p);else{const m=this.columnSizes.reduce((y,v)=>Math.max(y,v.height),0);u=c+ta(e.align,this.top,this.bottom-m-e.labels.padding-this._computeTitleHeight())}const g=ta(l,f,f+p);a.textAlign=o.textAlign(E6(l)),a.textBaseline="middle",a.strokeStyle=t.color,a.fillStyle=t.color,a.font=r.string,Ej(a,t.text,g,u,r)}_computeTitleHeight(){const e=this.options.title,t=Us(e.font),r=sa(e.padding);return e.display?t.lineHeight+r.height:0}_getLegendItemAt(e,t){let r,i,o;if(bm(e,this.left,this.right)&&bm(t,this.top,this.bottom)){for(o=this.legendHitBoxes,r=0;ro.length>a.length?o:a)),e+t.size/2+r.measureText(i).width}function Tre(n,e,t){let r=n;return typeof e.text!="string"&&(r=TU(e,t)),r}function TU(n,e){const t=n.text?n.text.length:0;return e*t}function Fre(n,e){return!!((n==="mousemove"||n==="mouseout")&&(e.onHover||e.onLeave)||e.onClick&&(n==="click"||n==="mouseup"))}var W6={id:"legend",_element:aL,start(n,e,t){const r=n.legend=new aL({ctx:n.ctx,options:t,chart:n});Ed.configure(n,r,t),Ed.addBox(n,r)},stop(n){Ed.removeBox(n,n.legend),delete n.legend},beforeUpdate(n,e,t){const r=n.legend;Ed.configure(n,r,t),r.options=t},afterUpdate(n){const e=n.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(n,e){e.replay||n.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(n,e,t){const r=e.datasetIndex,i=t.chart;i.isDatasetVisible(r)?(i.hide(r),e.hidden=!0):(i.show(r),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:n=>n.chart.options.color,boxWidth:40,padding:10,generateLabels(n){const e=n.data.datasets,{labels:{usePointStyle:t,pointStyle:r,textAlign:i,color:o,useBorderRadius:a,borderRadius:l}}=n.legend.options;return n._getSortedDatasetMetas().map(d=>{const c=d.controller.getStyle(t?0:void 0),u=sa(c.borderWidth);return{text:e[d.index].label,fillStyle:c.backgroundColor,fontColor:o,hidden:!d.visible,lineCap:c.borderCapStyle,lineDash:c.borderDash,lineDashOffset:c.borderDashOffset,lineJoin:c.borderJoinStyle,lineWidth:(u.width+u.height)/4,strokeStyle:c.borderColor,pointStyle:r||c.pointStyle,rotation:c.rotation,textAlign:i||c.textAlign,borderRadius:a&&(l||c.borderRadius),datasetIndex:d.index}},this)}},title:{color:n=>n.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:n=>!n.startsWith("on"),labels:{_scriptable:n=>!["generateLabels","filter","sort"].includes(n)}}};class FU extends Oo{constructor(e){super(),this.chart=e.chart,this.options=e.options,this.ctx=e.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(e,t){const r=this.options;if(this.left=0,this.top=0,!r.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=e,this.height=this.bottom=t;const i=ki(r.text)?r.text.length:1;this._padding=sa(r.padding);const o=i*Us(r.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const e=this.options.position;return e==="top"||e==="bottom"}_drawArgs(e){const{top:t,left:r,bottom:i,right:o,options:a}=this,l=a.align;let d=0,c,u,f;return this.isHorizontal()?(u=ta(l,r,o),f=t+e,c=o-r):(a.position==="left"?(u=r+e,f=ta(l,i,t),d=Or*-.5):(u=o-e,f=ta(l,t,i),d=Or*.5),c=i-t),{titleX:u,titleY:f,maxWidth:c,rotation:d}}draw(){const e=this.ctx,t=this.options;if(!t.display)return;const r=Us(t.font),o=r.lineHeight/2+this._padding.top,{titleX:a,titleY:l,maxWidth:d,rotation:c}=this._drawArgs(o);Ej(e,t.text,0,0,r,{color:t.color,maxWidth:d,rotation:c,textAlign:E6(t.align),textBaseline:"middle",translation:[a,l]})}}function Dre(n,e){const t=new FU({ctx:n.ctx,options:e,chart:n});Ed.configure(n,t,e),Ed.addBox(n,t),n.titleBlock=t}var U6={id:"title",_element:FU,start(n,e,t){Dre(n,t)},stop(n){const e=n.titleBlock;Ed.removeBox(n,e),delete n.titleBlock},beforeUpdate(n,e,t){const r=n.titleBlock;Ed.configure(n,r,t),r.options=t},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const nS={average(n){if(!n.length)return!1;let e,t,r=new Set,i=0,o=0;for(e=0,t=n.length;el+d)/r.size,y:i/o}},nearest(n,e){if(!n.length)return!1;let t=e.x,r=e.y,i=Number.POSITIVE_INFINITY,o,a,l;for(o=0,a=n.length;o-1?n.split(` -`):n}function Ere(n,e){const{element:t,datasetIndex:r,index:i}=e,o=n.getDatasetMeta(r).controller,{label:a,value:l}=o.getLabelAndValue(i);return{chart:n,label:a,parsed:o.getParsed(i),raw:n.data.datasets[r].data[i],formattedValue:l,dataset:o.getDataset(),dataIndex:i,datasetIndex:r,element:t}}function lL(n,e){const t=n.chart.ctx,{body:r,footer:i,title:o}=n,{boxWidth:a,boxHeight:l}=e,d=Us(e.bodyFont),c=Us(e.titleFont),u=Us(e.footerFont),f=o.length,p=i.length,g=r.length,m=sa(e.padding);let y=m.height,v=0,x=r.reduce((_,b)=>_+b.before.length+b.lines.length+b.after.length,0);if(x+=n.beforeBody.length+n.afterBody.length,f&&(y+=f*c.lineHeight+(f-1)*e.titleSpacing+e.titleMarginBottom),x){const _=e.displayColors?Math.max(l,d.lineHeight):d.lineHeight;y+=g*_+(x-g)*d.lineHeight+(x-1)*e.bodySpacing}p&&(y+=e.footerMarginTop+p*u.lineHeight+(p-1)*e.footerSpacing);let w=0;const S=function(_){v=Math.max(v,t.measureText(_).width+w)};return t.save(),t.font=c.string,Yr(n.title,S),t.font=d.string,Yr(n.beforeBody.concat(n.afterBody),S),w=e.displayColors?a+2+e.boxPadding:0,Yr(r,_=>{Yr(_.before,S),Yr(_.lines,S),Yr(_.after,S)}),w=0,t.font=u.string,Yr(n.footer,S),t.restore(),v+=m.width,{width:v,height:y}}function Pre(n,e){const{y:t,height:r}=e;return tn.height-r/2?"bottom":"center"}function Rre(n,e,t,r){const{x:i,width:o}=r,a=t.caretSize+t.caretPadding;if(n==="left"&&i+o+a>e.width||n==="right"&&i-o-a<0)return!0}function Bre(n,e,t,r){const{x:i,width:o}=t,{width:a,chartArea:{left:l,right:d}}=n;let c="center";return r==="center"?c=i<=(l+d)/2?"left":"right":i<=o/2?c="left":i>=a-o/2&&(c="right"),Rre(c,n,e,t)&&(c="center"),c}function dL(n,e,t){const r=t.yAlign||e.yAlign||Pre(n,t);return{xAlign:t.xAlign||e.xAlign||Bre(n,e,t,r),yAlign:r}}function Ire(n,e){let{x:t,width:r}=n;return e==="right"?t-=r:e==="center"&&(t-=r/2),t}function Mre(n,e,t){let{y:r,height:i}=n;return e==="top"?r+=t:e==="bottom"?r-=i+t:r-=i/2,r}function cL(n,e,t,r){const{caretSize:i,caretPadding:o,cornerRadius:a}=n,{xAlign:l,yAlign:d}=t,c=i+o,{topLeft:u,topRight:f,bottomLeft:p,bottomRight:g}=o0(a);let m=Ire(e,l);const y=Mre(e,d,c);return d==="center"?l==="left"?m+=c:l==="right"&&(m-=c):l==="left"?m-=Math.max(u,p)+i:l==="right"&&(m+=Math.max(f,g)+i),{x:Wl(m,0,r.width-e.width),y:Wl(y,0,r.height-e.height)}}function _2(n,e,t){const r=sa(t.padding);return e==="center"?n.x+n.width/2:e==="right"?n.x+n.width-r.right:n.x+r.left}function uL(n){return Qc([],uh(n))}function zre(n,e,t){return P0(n,{tooltip:e,tooltipItems:t,type:"tooltip"})}function hL(n,e){const t=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return t?n.override(t):n}const DU={beforeTitle:ih,title(n){if(n.length>0){const e=n[0],t=e.chart.data.labels,r=t?t.length:0;if(this&&this.options&&this.options.mode==="dataset")return e.dataset.label||"";if(e.label)return e.label;if(r>0&&e.dataIndex"u"?DU[e].call(t,r):i}class xB extends Oo{constructor(e){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=e.chart,this.options=e.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(e){this.options=e,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const e=this._cachedAnimations;if(e)return e;const t=this.chart,r=this.options.setContext(this.getContext()),i=r.enabled&&t.options.animation&&r.animations,o=new L6(this.chart,i);return i._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=zre(this.chart.getContext(),this,this._tooltipItems))}getTitle(e,t){const{callbacks:r}=t,i=za(r,"beforeTitle",this,e),o=za(r,"title",this,e),a=za(r,"afterTitle",this,e);let l=[];return l=Qc(l,uh(i)),l=Qc(l,uh(o)),l=Qc(l,uh(a)),l}getBeforeBody(e,t){return uL(za(t.callbacks,"beforeBody",this,e))}getBody(e,t){const{callbacks:r}=t,i=[];return Yr(e,o=>{const a={before:[],lines:[],after:[]},l=hL(r,o);Qc(a.before,uh(za(l,"beforeLabel",this,o))),Qc(a.lines,za(l,"label",this,o)),Qc(a.after,uh(za(l,"afterLabel",this,o))),i.push(a)}),i}getAfterBody(e,t){return uL(za(t.callbacks,"afterBody",this,e))}getFooter(e,t){const{callbacks:r}=t,i=za(r,"beforeFooter",this,e),o=za(r,"footer",this,e),a=za(r,"afterFooter",this,e);let l=[];return l=Qc(l,uh(i)),l=Qc(l,uh(o)),l=Qc(l,uh(a)),l}_createItems(e){const t=this._active,r=this.chart.data,i=[],o=[],a=[];let l=[],d,c;for(d=0,c=t.length;de.filter(u,f,p,r))),e.itemSort&&(l=l.sort((u,f)=>e.itemSort(u,f,r))),Yr(l,u=>{const f=hL(e.callbacks,u);i.push(za(f,"labelColor",this,u)),o.push(za(f,"labelPointStyle",this,u)),a.push(za(f,"labelTextColor",this,u))}),this.labelColors=i,this.labelPointStyles=o,this.labelTextColors=a,this.dataPoints=l,l}update(e,t){const r=this.options.setContext(this.getContext()),i=this._active;let o,a=[];if(!i.length)this.opacity!==0&&(o={opacity:0});else{const l=nS[r.position].call(this,i,this._eventPosition);a=this._createItems(r),this.title=this.getTitle(a,r),this.beforeBody=this.getBeforeBody(a,r),this.body=this.getBody(a,r),this.afterBody=this.getAfterBody(a,r),this.footer=this.getFooter(a,r);const d=this._size=lL(this,r),c=Object.assign({},l,d),u=dL(this.chart,r,c),f=cL(r,c,u,this.chart);this.xAlign=u.xAlign,this.yAlign=u.yAlign,o={opacity:1,x:f.x,y:f.y,width:d.width,height:d.height,caretX:l.x,caretY:l.y}}this._tooltipItems=a,this.$context=void 0,o&&this._resolveAnimations().update(this,o),e&&r.external&&r.external.call(this,{chart:this.chart,tooltip:this,replay:t})}drawCaret(e,t,r,i){const o=this.getCaretPosition(e,r,i);t.lineTo(o.x1,o.y1),t.lineTo(o.x2,o.y2),t.lineTo(o.x3,o.y3)}getCaretPosition(e,t,r){const{xAlign:i,yAlign:o}=this,{caretSize:a,cornerRadius:l}=r,{topLeft:d,topRight:c,bottomLeft:u,bottomRight:f}=o0(l),{x:p,y:g}=e,{width:m,height:y}=t;let v,x,w,S,_,b;return o==="center"?(_=g+y/2,i==="left"?(v=p,x=v-a,S=_+a,b=_-a):(v=p+m,x=v+a,S=_-a,b=_+a),w=v):(i==="left"?x=p+Math.max(d,u)+a:i==="right"?x=p+m-Math.max(c,f)-a:x=this.caretX,o==="top"?(S=g,_=S-a,v=x-a,w=x+a):(S=g+y,_=S+a,v=x+a,w=x-a),b=S),{x1:v,x2:x,x3:w,y1:S,y2:_,y3:b}}drawTitle(e,t,r){const i=this.title,o=i.length;let a,l,d;if(o){const c=ib(r.rtl,this.x,this.width);for(e.x=_2(this,r.titleAlign,r),t.textAlign=c.textAlign(r.titleAlign),t.textBaseline="middle",a=Us(r.titleFont),l=r.titleSpacing,t.fillStyle=r.titleColor,t.font=a.string,d=0;dw!==0)?(e.beginPath(),e.fillStyle=o.multiKeyBackground,Pj(e,{x:y,y:m,w:c,h:d,radius:x}),e.fill(),e.stroke(),e.fillStyle=a.backgroundColor,e.beginPath(),Pj(e,{x:v,y:m+1,w:c-2,h:d-2,radius:x}),e.fill()):(e.fillStyle=o.multiKeyBackground,e.fillRect(y,m,c,d),e.strokeRect(y,m,c,d),e.fillStyle=a.backgroundColor,e.fillRect(v,m+1,c-2,d-2))}e.fillStyle=this.labelTextColors[r]}drawBody(e,t,r){const{body:i}=this,{bodySpacing:o,bodyAlign:a,displayColors:l,boxHeight:d,boxWidth:c,boxPadding:u}=r,f=Us(r.bodyFont);let p=f.lineHeight,g=0;const m=ib(r.rtl,this.x,this.width),y=function(F){t.fillText(F,m.x(e.x+g),e.y+p/2),e.y+=p+o},v=m.textAlign(a);let x,w,S,_,b,C,T;for(t.textAlign=a,t.textBaseline="middle",t.font=f.string,e.x=_2(this,v,r),t.fillStyle=r.bodyColor,Yr(this.beforeBody,y),g=l&&v!=="right"?a==="center"?c/2+u:c+2+u:0,_=0,C=i.length;_0&&t.stroke()}_updateAnimationTarget(e){const t=this.chart,r=this.$animations,i=r&&r.x,o=r&&r.y;if(i||o){const a=nS[e.position].call(this,this._active,this._eventPosition);if(!a)return;const l=this._size=lL(this,e),d=Object.assign({},a,this._size),c=dL(t,e,d),u=cL(e,d,c,t);(i._to!==u.x||o._to!==u.y)&&(this.xAlign=c.xAlign,this.yAlign=c.yAlign,this.width=l.width,this.height=l.height,this.caretX=a.x,this.caretY=a.y,this._resolveAnimations().update(this,u))}}_willRender(){return!!this.opacity}draw(e){const t=this.options.setContext(this.getContext());let r=this.opacity;if(!r)return;this._updateAnimationTarget(t);const i={width:this.width,height:this.height},o={x:this.x,y:this.y};r=Math.abs(r)<.001?0:r;const a=sa(t.padding),l=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;t.enabled&&l&&(e.save(),e.globalAlpha=r,this.drawBackground(o,e,i,t),uU(e,t.textDirection),o.y+=a.top,this.drawTitle(o,e,t),this.drawBody(o,e,t),this.drawFooter(o,e,t),hU(e,t.textDirection),e.restore())}getActiveElements(){return this._active||[]}setActiveElements(e,t){const r=this._active,i=e.map(({datasetIndex:l,index:d})=>{const c=this.chart.getDatasetMeta(l);if(!c)throw new Error("Cannot find a dataset at index "+l);return{datasetIndex:l,element:c.data[d],index:d}}),o=!HA(r,i),a=this._positionChanged(i,t);(o||a)&&(this._active=i,this._eventPosition=t,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(e,t,r=!0){if(t&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const i=this.options,o=this._active||[],a=this._getActiveElements(e,o,t,r),l=this._positionChanged(a,e),d=t||!HA(a,o)||l;return d&&(this._active=a,(i.enabled||i.external)&&(this._eventPosition={x:e.x,y:e.y},this.update(!0,t))),d}_getActiveElements(e,t,r,i){const o=this.options;if(e.type==="mouseout")return[];if(!i)return t.filter(l=>this.chart.data.datasets[l.datasetIndex]&&this.chart.getDatasetMeta(l.datasetIndex).controller.getParsed(l.index)!==void 0);const a=this.chart.getElementsAtEventForMode(e,o.mode,o,r);return o.reverse&&a.reverse(),a}_positionChanged(e,t){const{caretX:r,caretY:i,options:o}=this,a=nS[o.position].call(this,e,t);return a!==!1&&(r!==a.x||i!==a.y)}}ve(xB,"positioners",nS);var H6={id:"tooltip",_element:xB,positioners:nS,afterInit(n,e,t){t&&(n.tooltip=new xB({chart:n,options:t}))},beforeUpdate(n,e,t){n.tooltip&&n.tooltip.initialize(t)},reset(n,e,t){n.tooltip&&n.tooltip.initialize(t)},afterDraw(n){const e=n.tooltip;if(e&&e._willRender()){const t={tooltip:e};if(n.notifyPlugins("beforeTooltipDraw",{...t,cancelable:!0})===!1)return;e.draw(n.ctx),n.notifyPlugins("afterTooltipDraw",t)}},afterEvent(n,e){if(n.tooltip){const t=e.replay;n.tooltip.handleEvent(e.event,t,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(n,e)=>e.bodyFont.size,boxWidth:(n,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:DU},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:n=>n!=="filter"&&n!=="itemSort"&&n!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};const Ore=(n,e,t,r)=>(typeof e=="string"?(t=n.push(e)-1,r.unshift({index:t,label:e})):isNaN(e)&&(t=null),t);function Lre(n,e,t,r){const i=n.indexOf(e);if(i===-1)return Ore(n,e,t,r);const o=n.lastIndexOf(e);return i!==o?t:i}const Nre=(n,e)=>n===null?null:Wl(Math.round(n),0,e);function fL(n){const e=this.getLabels();return n>=0&&nt.length-1?null:this.getPixelForValue(t[e].value)}getValueForPixel(e){return Math.round(this._startValue+this.getDecimalForPixel(e)*this._valueRange)}getBasePixel(){return this.bottom}}ve(Bj,"id","category"),ve(Bj,"defaults",{ticks:{callback:fL}});function Wre(n,e){const t=[],{bounds:i,step:o,min:a,max:l,precision:d,count:c,maxTicks:u,maxDigits:f,includeBounds:p}=n,g=o||1,m=u-1,{min:y,max:v}=e,x=!Ur(a),w=!Ur(l),S=!Ur(c),_=(v-y)/(f+1);let b=gO((v-y)/m/g)*g,C,T,F,A;if(b<1e-14&&!x&&!w)return[{value:y},{value:v}];A=Math.ceil(v/b)-Math.floor(y/b),A>m&&(b=gO(A*b/m/g)*g),Ur(d)||(C=Math.pow(10,d),b=Math.ceil(b*C)/C),i==="ticks"?(T=Math.floor(y/b)*b,F=Math.ceil(v/b)*b):(T=y,F=v),x&&w&&o&&yee((l-a)/o,b/1e3)?(A=Math.round(Math.min((l-a)/b,u)),b=(l-a)/A,T=a,F=l):S?(T=x?a:T,F=w?l:F,A=c-1,b=(F-T)/A):(A=(F-T)/b,HS(A,Math.round(A),b/1e3)?A=Math.round(A):A=Math.ceil(A));const D=Math.max(mO(b),mO(T));C=Math.pow(10,Ur(d)?D:d),T=Math.round(T*C)/C,F=Math.round(F*C)/C;let P=0;for(x&&(p&&T!==a?(t.push({value:a}),Tl)break;t.push({value:L})}return w&&p&&F!==l?t.length&&HS(t[t.length-1].value,l,pL(l,_,n))?t[t.length-1].value=l:t.push({value:l}):(!w||F===l)&&t.push({value:F}),t}function pL(n,e,{horizontal:t,minRotation:r}){const i=fo(r),o=(t?Math.sin(i):Math.cos(i))||.001,a=.75*e*(""+n).length;return Math.min(e/o,a)}class Ure extends m1{constructor(e){super(e),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(e,t){return Ur(e)||(typeof e=="number"||e instanceof Number)&&!isFinite(+e)?null:+e}handleTickRangeOptions(){const{beginAtZero:e}=this.options,{minDefined:t,maxDefined:r}=this.getUserBounds();let{min:i,max:o}=this;const a=d=>i=t?i:d,l=d=>o=r?o:d;if(e){const d=zu(i),c=zu(o);d<0&&c<0?l(0):d>0&&c>0&&a(0)}if(i===o){let d=o===0?1:Math.abs(o*.05);l(o+d),e||a(i-d)}this.min=i,this.max=o}getTickLimit(){const e=this.options.ticks;let{maxTicksLimit:t,stepSize:r}=e,i;return r?(i=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,i>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${i} ticks. Limiting to 1000.`),i=1e3)):(i=this.computeTickLimit(),t=t||11),t&&(i=Math.min(t,i)),i}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const e=this.options,t=e.ticks;let r=this.getTickLimit();r=Math.max(2,r);const i={maxTicks:r,bounds:e.bounds,min:e.min,max:e.max,precision:t.precision,step:t.stepSize,count:t.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:t.minRotation||0,includeBounds:t.includeBounds!==!1},o=this._range||this,a=Wre(i,o);return e.bounds==="ticks"&&xee(a,this,"value"),e.reverse?(a.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),a}configure(){const e=this.ticks;let t=this.min,r=this.max;if(super.configure(),this.options.offset&&e.length){const i=(r-t)/Math.max(e.length-1,1)/2;t-=i,r+=i}this._startValue=t,this._endValue=r,this._valueRange=r-t}getLabelForValue(e){return R6(e,this.chart.options.locale,this.options.ticks.format)}}class Ij extends Ure{determineDataLimits(){const{min:e,max:t}=this.getMinMax(!0);this.min=sl(e)?e:0,this.max=sl(t)?t:1,this.handleTickRangeOptions()}computeTickLimit(){const e=this.isHorizontal(),t=e?this.width:this.height,r=fo(this.options.ticks.minRotation),i=(e?Math.sin(r):Math.cos(r))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(t/Math.min(40,o.lineHeight/i))}getPixelForValue(e){return e===null?NaN:this.getPixelForDecimal((e-this._startValue)/this._valueRange)}getValueForPixel(e){return this._startValue+this.getDecimalForPixel(e)*this._valueRange}}ve(Ij,"id","linear"),ve(Ij,"defaults",{ticks:{callback:nU.formatters.numeric}});const _F={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Za=Object.keys(_F);function gL(n,e){return n-e}function mL(n,e){if(Ur(e))return null;const t=n._adapter,{parser:r,round:i,isoWeekday:o}=n._parseOpts;let a=e;return typeof r=="function"&&(a=r(a)),sl(a)||(a=typeof r=="string"?t.parse(a,r):t.parse(a)),a===null?null:(i&&(a=i==="week"&&(m0(o)||o===!0)?t.startOf(a,"isoWeek",o):t.startOf(a,i)),+a)}function yL(n,e,t,r){const i=Za.length;for(let o=Za.indexOf(n);o=Za.indexOf(t);o--){const a=Za[o];if(_F[a].common&&n._adapter.diff(i,r,a)>=e-1)return a}return Za[t?Za.indexOf(t):0]}function qre(n){for(let e=Za.indexOf(n)+1,t=Za.length;e=e?t[r]:t[i];n[o]=!0}}function Vre(n,e,t,r){const i=n._adapter,o=+i.startOf(e[0].value,r),a=e[e.length-1].value;let l,d;for(l=o;l<=a;l=+i.add(l,1,r))d=t[l],d>=0&&(e[d].major=!0);return e}function bL(n,e,t){const r=[],i={},o=e.length;let a,l;for(a=0;a+e.value))}initOffsets(e=[]){let t=0,r=0,i,o;this.options.offset&&e.length&&(i=this.getDecimalForValue(e[0]),e.length===1?t=1-i:t=(this.getDecimalForValue(e[1])-i)/2,o=this.getDecimalForValue(e[e.length-1]),e.length===1?r=o:r=(o-this.getDecimalForValue(e[e.length-2]))/2);const a=e.length<3?.5:.25;t=Wl(t,0,a),r=Wl(r,0,a),this._offsets={start:t,end:r,factor:1/(t+1+r)}}_generate(){const e=this._adapter,t=this.min,r=this.max,i=this.options,o=i.time,a=o.unit||yL(o.minUnit,t,r,this._getLabelCapacity(t)),l=In(i.ticks.stepSize,1),d=a==="week"?o.isoWeekday:!1,c=m0(d)||d===!0,u={};let f=t,p,g;if(c&&(f=+e.startOf(f,"isoWeek",d)),f=+e.startOf(f,c?"day":a),e.diff(r,t,a)>1e5*l)throw new Error(t+" and "+r+" are too far apart with stepSize of "+l+" "+a);const m=i.ticks.source==="data"&&this.getDataTimestamps();for(p=f,g=0;p+y)}getLabelForValue(e){const t=this._adapter,r=this.options.time;return r.tooltipFormat?t.format(e,r.tooltipFormat):t.format(e,r.displayFormats.datetime)}format(e,t){const i=this.options.time.displayFormats,o=this._unit,a=t||i[o];return this._adapter.format(e,a)}_tickFormatFunction(e,t,r,i){const o=this.options,a=o.ticks.callback;if(a)return li(a,[e,t,r],this);const l=o.time.displayFormats,d=this._unit,c=this._majorUnit,u=d&&l[d],f=c&&l[c],p=r[t],g=c&&f&&p&&p.major;return this._adapter.format(e,i||(g?f:u))}generateTickLabels(e){let t,r,i;for(t=0,r=e.length;t0?l:1}getDataTimestamps(){let e=this._cache.data||[],t,r;if(e.length)return e;const i=this.getMatchingVisibleMetas();if(this._normalized&&i.length)return this._cache.data=i[0].controller.getAllParsedValues(this);for(t=0,r=i.length;t=n[r].pos&&e<=n[i].pos&&({lo:r,hi:i}=vm(n,"pos",e)),{pos:o,time:l}=n[r],{pos:a,time:d}=n[i]):(e>=n[r].time&&e<=n[i].time&&({lo:r,hi:i}=vm(n,"time",e)),{time:o,pos:l}=n[r],{time:a,pos:d}=n[i]);const c=a-o;return c?l+(d-l)*(e-o)/c:l}class vL extends QA{constructor(e){super(e),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const e=this._getTimestampsForTable(),t=this._table=this.buildLookupTable(e);this._minPos=C2(t,this.min),this._tableRange=C2(t,this.max)-this._minPos,super.initOffsets(e)}buildLookupTable(e){const{min:t,max:r}=this,i=[],o=[];let a,l,d,c,u;for(a=0,l=e.length;a=t&&c<=r&&i.push(c);if(i.length<2)return[{time:t,pos:0},{time:r,pos:1}];for(a=0,l=i.length;ai-o)}_getTimestampsForTable(){let e=this._cache.all||[];if(e.length)return e;const t=this.getDataTimestamps(),r=this.getLabelTimestamps();return t.length&&r.length?e=this.normalize(t.concat(r)):e=t.length?t:r,e=this._cache.all=e,e}getDecimalForValue(e){return(C2(this._table,e)-this._minPos)/this._tableRange}getValueForPixel(e){const t=this._offsets,r=this.getDecimalForPixel(e)/t.factor-t.end;return C2(this._table,r*this._tableRange+this._minPos,!0)}}ve(vL,"id","timeseries"),ve(vL,"defaults",QA.defaults);const EU="label";function wL(n,e){typeof n=="function"?n(e):n&&(n.current=e)}function Gre(n,e){const t=n.options;t&&e&&Object.assign(t,e)}function PU(n,e){n.labels=e}function RU(n,e,t=EU){const r=[];n.datasets=e.map(i=>{const o=n.datasets.find(a=>a[t]===i[t]);return!o||!i.data||r.includes(o)?{...i}:(r.push(o),Object.assign(o,i),o)})}function Kre(n,e=EU){const t={labels:[],datasets:[]};return PU(t,n.labels),RU(t,n.datasets,e),t}function Xre(n,e){const{height:t=150,width:r=300,redraw:i=!1,datasetIdKey:o,type:a,data:l,options:d,plugins:c=[],fallbackContent:u,updateMode:f,...p}=n,g=k.useRef(null),m=k.useRef(null),y=()=>{g.current&&(m.current=new pf(g.current,{type:a,data:Kre(l,o),options:d&&{...d},plugins:c}),wL(e,m.current))},v=()=>{wL(e,null),m.current&&(m.current.destroy(),m.current=null)};return k.useEffect(()=>{!i&&m.current&&d&&Gre(m.current,d)},[i,d]),k.useEffect(()=>{!i&&m.current&&PU(m.current.config.data,l.labels)},[i,l.labels]),k.useEffect(()=>{!i&&m.current&&l.datasets&&RU(m.current.config.data,l.datasets,o)},[i,l.datasets]),k.useEffect(()=>{m.current&&(i?(v(),setTimeout(y)):m.current.update(f))},[i,d,l.labels,l.datasets,f]),k.useEffect(()=>{m.current&&(v(),setTimeout(y))},[a]),k.useEffect(()=>(y(),()=>v()),[]),s.jsx("canvas",{ref:g,role:"img",height:t,width:r,...p,children:u})}const Yre=k.forwardRef(Xre);function BU(n,e){return pf.register(e),k.forwardRef((t,r)=>s.jsx(Yre,{...t,ref:r,type:n}))}const IU=BU("line",p5),Qre=BU("bar",f5);/*! -* chartjs-plugin-annotation v3.1.0 -* https://www.chartjs.org/chartjs-plugin-annotation/index - * (c) 2024 chartjs-plugin-annotation Contributors - * Released under the MIT License - */const SL={modes:{point(n,e){return x5(n,e,{intersect:!0})},nearest(n,e,t){return Jre(n,e,t)},x(n,e,t){return x5(n,e,{intersect:t.intersect,axis:"x"})},y(n,e,t){return x5(n,e,{intersect:t.intersect,axis:"y"})}}};function q6(n,e,t){return(SL.modes[t.mode]||SL.modes.nearest)(n,e,t)}function $re(n,e,t){return t!=="x"&&t!=="y"?n.inRange(e.x,e.y,"x",!0)||n.inRange(e.x,e.y,"y",!0):n.inRange(e.x,e.y,t,!0)}function Zre(n,e,t){return t==="x"?{x:n.x,y:e.y}:t==="y"?{x:e.x,y:n.y}:e}function x5(n,e,t){return n.filter(r=>t.intersect?r.inRange(e.x,e.y):$re(r,e,t.axis))}function Jre(n,e,t){let r=Number.POSITIVE_INFINITY;return x5(n,e,t).reduce((i,o)=>{const a=o.getCenterPoint(),l=Zre(e,a,t.axis),d=r1(e,l);return di._index-o._index).slice(0,1)}function R0(n,e,t){const r=Math.cos(t),i=Math.sin(t),o=e.x,a=e.y;return{x:o+r*(n.x-o)-i*(n.y-a),y:a+i*(n.x-o)+r*(n.y-a)}}const eie=(n,e)=>e>n||n.length>e.length&&n.slice(0,e.length)===e,wm=.001,CF=(n,e,t)=>Math.min(t,Math.max(e,n)),MU=(n,e)=>n.value>=n.start-e&&n.value<=n.end+e;function tie(n,e,t){for(const r of Object.keys(n))n[r]=CF(n[r],e,t);return n}function nie(n,e,t,r){return!n||!e||t<=0?!1:Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)<=Math.pow(t+r,2)}function zU(n,{x:e,y:t,x2:r,y2:i},o,{borderWidth:a,hitTolerance:l}){const d=(a+l)/2,c=n.x>=e-d-wm&&n.x<=r+d+wm,u=n.y>=t-d-wm&&n.y<=i+d+wm;return o==="x"?c:(o==="y"||c)&&u}function OU(n,{rect:e,center:t},r,{rotation:i,borderWidth:o,hitTolerance:a}){const l=R0(n,t,fo(-i));return zU(l,e,r,{borderWidth:o,hitTolerance:a})}function B0(n,e){const{centerX:t,centerY:r}=n.getProps(["centerX","centerY"],e);return{x:t,y:r}}function rie(n,e,t,r=!0){const i=t.split(".");let o=0;for(const a of e.split(".")){const l=i[o++];if(parseInt(a,10)typeof n=="string"&&n.endsWith("%"),NU=n=>parseFloat(n)/100,WU=n=>CF(NU(n),0,1),Rw=(n,e)=>({x:n,y:e,x2:n,y2:e,width:0,height:0}),iie={box:n=>Rw(n.centerX,n.centerY),doughnutLabel:n=>Rw(n.centerX,n.centerY),ellipse:n=>({centerX:n.centerX,centerY:n.centerX,radius:0,width:0,height:0}),label:n=>Rw(n.centerX,n.centerY),line:n=>Rw(n.x,n.y),point:n=>({centerX:n.centerX,centerY:n.centerY,radius:0,width:0,height:0}),polygon:n=>Rw(n.centerX,n.centerY)};function V6(n,e){return e==="start"?0:e==="end"?n:LU(e)?WU(e)*n:n/2}function Mg(n,e,t=!0){return typeof e=="number"?e:LU(e)?(t?WU(e):NU(e))*n:n}function sie(n,e){const{x:t,width:r}=n,i=e.textAlign;return i==="center"?t+r/2:i==="end"||i==="right"?t+r:t}function UU(n,e,{borderWidth:t,position:r,xAdjust:i,yAdjust:o},a){const l=Yn(a),d=e.width+(l?a.width:0)+t,c=e.height+(l?a.height:0)+t,u=G6(r),f=jL(n.x,d,i,u.x),p=jL(n.y,c,o,u.y);return{x:f,y:p,x2:f+d,y2:p+c,width:d,height:c,centerX:f+d/2,centerY:p+c/2}}function G6(n,e="center"){return Yn(n)?{x:In(n.x,e),y:In(n.y,e)}:(n=In(n,e),{x:n,y:n})}const HU=(n,e)=>n&&n.autoFit&&e<1;function qU(n,e){const t=n.font,r=ki(t)?t:[t];return HU(n,e)?r.map(function(i){const o=Us(i);return o.size=Math.floor(i.size*e),o.lineHeight=i.lineHeight,Us(o)}):r.map(i=>Us(i))}function VU(n){return n&&(ol(n.xValue)||ol(n.yValue))}function jL(n,e,t=0,r){return n-V6(e,r)+t}function y1(n,e,t){const r=t.init;if(r){if(r===!0)return KU(e,t)}else return;return oie(n,e,t)}function GU(n,e,t){let r=!1;return e.forEach(i=>{il(n[i])?(r=!0,t[i]=n[i]):ol(t[i])&&delete t[i]}),r}function KU(n,e){const t=e.type||"line";return iie[t](n)}function oie(n,e,t){const r=li(t.init,[{chart:n,properties:e,options:t}]);if(r===!0)return KU(e,t);if(Yn(r))return r}const xP=new Map,aie=n=>isNaN(n)||n<=0,lie=n=>n.reduce(function(e,t){return e+=t.string,e},"");function AF(n){if(n&&typeof n=="object"){const e=n.toString();return e==="[object HTMLImageElement]"||e==="[object HTMLCanvasElement]"}}function TF(n,{x:e,y:t},r){r&&(n.translate(e,t),n.rotate(fo(r)),n.translate(-e,-t))}function Cf(n,e){if(e&&e.borderWidth)return n.lineCap=e.borderCapStyle||"butt",n.setLineDash(e.borderDash),n.lineDashOffset=e.borderDashOffset,n.lineJoin=e.borderJoinStyle||"miter",n.lineWidth=e.borderWidth,n.strokeStyle=e.borderColor,!0}function x1(n,e){n.shadowColor=e.backgroundShadowColor,n.shadowBlur=e.shadowBlur,n.shadowOffsetX=e.shadowOffsetX,n.shadowOffsetY=e.shadowOffsetY}function FF(n,e){const t=e.content;if(AF(t))return{width:Mg(t.width,e.width),height:Mg(t.height,e.height)};const r=qU(e),i=e.textStrokeWidth,o=ki(t)?t:[t],a=o.join()+lie(r)+i+(n._measureText?"-spriting":"");return xP.has(a)||xP.set(a,hie(n,o,r,i)),xP.get(a)}function XU(n,e,t){const{x:r,y:i,width:o,height:a}=e;n.save(),x1(n,t);const l=Cf(n,t);n.fillStyle=t.backgroundColor,n.beginPath(),Pj(n,{x:r,y:i,w:o,h:a,radius:tie(o0(t.borderRadius),0,Math.min(o,a)/2)}),n.closePath(),n.fill(),l&&(n.shadowColor=t.borderShadowColor,n.stroke()),n.restore()}function YU(n,e,t,r){const i=t.content;if(AF(i)){n.save(),n.globalAlpha=gie(t.opacity,i.style.opacity),n.drawImage(i,e.x,e.y,e.width,e.height),n.restore();return}const o=ki(i)?i:[i],a=qU(t,r),l=t.color,d=ki(l)?l:[l],c=sie(e,t),u=e.y+t.textStrokeWidth/2;n.save(),n.textBaseline="middle",n.textAlign=t.textAlign,die(n,t)&&fie(n,{x:c,y:u},o,a),pie(n,{x:c,y:u},o,{fonts:a,colors:d}),n.restore()}function die(n,e){if(e.textStrokeWidth>0)return n.lineJoin="round",n.miterLimit=2,n.lineWidth=e.textStrokeWidth,n.strokeStyle=e.textStrokeColor,!0}function cie(n,e,t,r){const{radius:i,options:o}=e,a=o.pointStyle,l=o.rotation;let d=(l||0)*F6;if(AF(a)){n.save(),n.translate(t,r),n.rotate(d),n.drawImage(a,-a.width/2,-a.height/2,a.width,a.height),n.restore();return}aie(i)||uie(n,{x:t,y:r,radius:i,rotation:l,style:a,rad:d})}function uie(n,{x:e,y:t,radius:r,rotation:i,style:o,rad:a}){let l,d,c,u;switch(n.beginPath(),o){default:n.arc(e,t,r,0,Eo),n.closePath();break;case"triangle":n.moveTo(e+Math.sin(a)*r,t-Math.cos(a)*r),a+=GA,n.lineTo(e+Math.sin(a)*r,t-Math.cos(a)*r),a+=GA,n.lineTo(e+Math.sin(a)*r,t-Math.cos(a)*r),n.closePath();break;case"rectRounded":u=r*.516,c=r-u,l=Math.cos(a+jd)*c,d=Math.sin(a+jd)*c,n.arc(e-l,t-d,u,a-Or,a-Po),n.arc(e+d,t-l,u,a-Po,a),n.arc(e+l,t+d,u,a,a+Po),n.arc(e-d,t+l,u,a+Po,a+Or),n.closePath();break;case"rect":if(!i){c=Math.SQRT1_2*r,n.rect(e-c,t-c,2*c,2*c);break}a+=jd;case"rectRot":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+d,t-l),n.lineTo(e+l,t+d),n.lineTo(e-d,t+l),n.closePath();break;case"crossRot":a+=jd;case"cross":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d),n.moveTo(e+d,t-l),n.lineTo(e-d,t+l);break;case"star":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d),n.moveTo(e+d,t-l),n.lineTo(e-d,t+l),a+=jd,l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d),n.moveTo(e+d,t-l),n.lineTo(e-d,t+l);break;case"line":l=Math.cos(a)*r,d=Math.sin(a)*r,n.moveTo(e-l,t-d),n.lineTo(e+l,t+d);break;case"dash":n.moveTo(e,t),n.lineTo(e+Math.cos(a)*r,t+Math.sin(a)*r);break}n.fill()}function hie(n,e,t,r){n.save();const i=e.length;let o=0,a=r;for(let l=0;l0||i.borderWidth===0)&&(n.moveTo(d.x,d.y),n.lineTo(c.x,c.y)),n.moveTo(u.x,u.y),n.lineTo(f.x,f.y);const p=R0({x:t,y:r},e.getCenterPoint(),fo(-e.rotation));n.lineTo(p.x,p.y),n.stroke(),n.restore()}function yie(n,e){const{x:t,y:r,x2:i,y2:o}=n,a=xie(n,e);let l,d;return e==="left"||e==="right"?(l={x:t+a,y:r},d={x:l.x,y:o}):(l={x:t,y:r+a},d={x:i,y:l.y}),{separatorStart:l,separatorEnd:d}}function xie(n,e){const{width:t,height:r,options:i}=n,o=i.callout.margin+i.borderWidth/2;return e==="right"?t+o:e==="bottom"?r+o:-o}function bie(n,e,t){const{y:r,width:i,height:o,options:a}=n,l=a.callout.start,d=vie(e,a.callout);let c,u;return e==="left"||e==="right"?(c={x:t.x,y:r+Mg(o,l)},u={x:c.x+d,y:c.y}):(c={x:t.x+Mg(i,l),y:t.y},u={x:c.x,y:c.y+d}),{sideStart:c,sideEnd:u}}function vie(n,e){const t=e.side;return n==="left"||n==="top"?-t:t}function wie(n,e){const t=e.position;return QU.includes(t)?t:Sie(n,e)}function Sie(n,e){const{x:t,y:r,x2:i,y2:o,width:a,height:l,pointX:d,pointY:c,centerX:u,centerY:f,rotation:p}=n,g={x:u,y:f},m=e.start,y=Mg(a,m),v=Mg(l,m),x=[t,t+y,t+y,i],w=[r+v,o,r,o],S=[];for(let _=0;_<4;_++){const b=R0({x:x[_],y:w[_]},g,fo(p));S.push({position:QU[_],distance:r1(b,{x:d,y:c})})}return S.sort((_,b)=>_.distance-b.distance)[0].position}function jie(n,e,t){const{pointX:r,pointY:i}=n,o=e.margin;let a=r,l=i;return t==="left"?a+=o:t==="right"?a-=o:t==="top"?l+=o:t==="bottom"&&(l-=o),n.inRange(a,l)}const kL={xScaleID:{min:"xMin",max:"xMax",start:"left",end:"right",startProp:"x",endProp:"x2"},yScaleID:{min:"yMin",max:"yMax",start:"bottom",end:"top",startProp:"y",endProp:"y2"}};function o1(n,e,t){return e=typeof e=="number"?e:n.parse(e),sl(e)?n.getPixelForValue(e):t}function x0(n,e,t){const r=e[t];if(r||t==="scaleID")return r;const i=t.charAt(0),o=Object.values(n).filter(a=>a.axis&&a.axis===i);return o.length?o[0].id:i}function $U(n,e){if(n){const t=n.options.reverse,r=o1(n,e.min,t?e.end:e.start),i=o1(n,e.max,t?e.start:e.end);return{start:r,end:i}}}function ZU(n,e){const{chartArea:t,scales:r}=n,i=r[x0(r,e,"xScaleID")],o=r[x0(r,e,"yScaleID")];let a=t.width/2,l=t.height/2;return i&&(a=o1(i,e.xValue,i.left+i.width/2)),o&&(l=o1(o,e.yValue,o.top+o.height/2)),{x:a,y:l}}function K6(n,e){const t=n.scales,r=t[x0(t,e,"xScaleID")],i=t[x0(t,e,"yScaleID")];if(!r&&!i)return{};let{left:o,right:a}=r||n.chartArea,{top:l,bottom:d}=i||n.chartArea;const c=_L(r,{min:e.xMin,max:e.xMax,start:o,end:a});o=c.start,a=c.end;const u=_L(i,{min:e.yMin,max:e.yMax,start:d,end:l});return l=u.start,d=u.end,{x:o,y:l,x2:a,y2:d,width:a-o,height:d-l,centerX:o+(a-o)/2,centerY:l+(d-l)/2}}function JU(n,e){if(!VU(e)){const t=K6(n,e);let r=e.radius;(!r||isNaN(r))&&(r=Math.min(t.width,t.height)/2,e.radius=r);const i=r*2,o=t.centerX+e.xAdjust,a=t.centerY+e.yAdjust;return{x:o-r,y:a-r,x2:o+r,y2:a+r,centerX:o,centerY:a,width:i,height:i,radius:r}}return _ie(n,e)}function kie(n,e){const{scales:t,chartArea:r}=n,i=t[e.scaleID],o={x:r.left,y:r.top,x2:r.right,y2:r.bottom};return i?Cie(i,o,e):Aie(t,o,e),o}function eH(n,e){const t=K6(n,e);return t.initProperties=y1(n,t,e),t.elements=[{type:"label",optionScope:"label",properties:Die(n,t,e),initProperties:t.initProperties}],t}function _ie(n,e){const t=ZU(n,e),r=e.radius*2;return{x:t.x-e.radius+e.xAdjust,y:t.y-e.radius+e.yAdjust,x2:t.x+e.radius+e.xAdjust,y2:t.y+e.radius+e.yAdjust,centerX:t.x+e.xAdjust,centerY:t.y+e.yAdjust,radius:e.radius,width:r,height:r}}function _L(n,e){const t=$U(n,e)||e;return{start:Math.min(t.start,t.end),end:Math.max(t.start,t.end)}}function Cie(n,e,t){const r=o1(n,t.value,NaN),i=o1(n,t.endValue,r);n.isHorizontal()?(e.x=r,e.x2=i):(e.y=r,e.y2=i)}function Aie(n,e,t){for(const r of Object.keys(kL)){const i=n[x0(n,t,r)];if(i){const{min:o,max:a,start:l,end:d,startProp:c,endProp:u}=kL[r],f=$U(i,{min:t[o],max:t[a],start:i[l],end:i[d]});e[c]=f.start,e[u]=f.end}}}function Tie({properties:n,options:e},t,r,i){const{x:o,x2:a,width:l}=n;return tH({start:o,end:a,borderWidth:e.borderWidth},{position:r.x,padding:{start:i.left,end:i.right},adjust:e.label.xAdjust,size:t.width})}function Fie({properties:n,options:e},t,r,i){const{y:o,y2:a,height:l}=n;return tH({start:o,end:a,borderWidth:e.borderWidth},{position:r.y,padding:{start:i.top,end:i.bottom},adjust:e.label.yAdjust,size:t.height})}function tH(n,e){const{start:t,end:r,borderWidth:i}=n,{position:o,padding:{start:a,end:l},adjust:d}=e,c=r-i-t-a-l-e.size;return t+i/2+d+V6(c,o)}function Die(n,e,t){const r=t.label;r.backgroundColor="transparent",r.callout.display=!1;const i=G6(r.position),o=sa(r.padding),a=FF(n.ctx,r),l=Tie({properties:e,options:t},a,i,o),d=Fie({properties:e,options:t},a,i,o),c=a.width+o.width,u=a.height+o.height;return{x:l,y:d,x2:l+c,y2:d+u,width:c,height:u,centerX:l+c/2,centerY:d+u/2,rotation:r.rotation}}const bB=["enter","leave"],X6=bB.concat("click");function Eie(n,e,t){e.listened=GU(t,X6,e.listeners),e.moveListened=!1,bB.forEach(r=>{il(t[r])&&(e.moveListened=!0)}),(!e.listened||!e.moveListened)&&e.annotations.forEach(r=>{!e.listened&&il(r.click)&&(e.listened=!0),e.moveListened||bB.forEach(i=>{il(r[i])&&(e.listened=!0,e.moveListened=!0)})})}function Pie(n,e,t){if(n.listened)switch(e.type){case"mousemove":case"mouseout":return Rie(n,e,t);case"click":return Bie(n,e,t)}}function Rie(n,e,t){if(!n.moveListened)return;let r;e.type==="mousemove"?r=q6(n.visibleElements,e,t.interaction):r=[];const i=n.hovered;n.hovered=r;const o={state:n,event:e};let a=CL(o,"leave",i,r);return CL(o,"enter",r,i)||a}function CL({state:n,event:e},t,r,i){let o;for(const a of r)i.indexOf(a)<0&&(o=nH(a.options[t]||n.listeners[t],a,e)||o);return o}function Bie(n,e,t){const r=n.listeners,i=q6(n.visibleElements,e,t.interaction);let o;for(const a of i)o=nH(a.options.click||r.click,a,e)||o;return o}function nH(n,e,t){return li(n,[e.$context,t])===!0}const $A=["afterDraw","beforeDraw"];function Iie(n,e,t){const r=e.visibleElements;e.hooked=GU(t,$A,e.hooks),e.hooked||r.forEach(i=>{e.hooked||$A.forEach(o=>{il(i.options[o])&&(e.hooked=!0)})})}function AL(n,e,t){if(n.hooked){const r=e.options[t]||n.hooks[t];return li(r,[e.$context])}}function Mie(n,e,t){const r=Wie(n.scales,e,t);let i=TL(e,r,"min","suggestedMin");i=TL(e,r,"max","suggestedMax")||i,i&&il(e.handleTickRangeOptions)&&e.handleTickRangeOptions()}function zie(n,e){for(const t of n)Lie(t,e)}function TL(n,e,t,r){if(sl(e[t])&&!Oie(n.options,t,r)){const i=n[t]!==e[t];return n[t]=e[t],i}}function Oie(n,e,t){return ol(n[e])||ol(n[t])}function Lie(n,e){for(const t of["scaleID","xScaleID","yScaleID"]){const r=x0(e,n,t);r&&!e[r]&&Nie(n,t)&&console.warn(`No scale found with id '${r}' for annotation '${n.id}'`)}}function Nie(n,e){if(e==="scaleID")return!0;const t=e.charAt(0);for(const r of["Min","Max","Value"])if(ol(n[t+r]))return!0;return!1}function Wie(n,e,t){const r=e.axis,i=e.id,o=r+"ScaleID",a={min:In(e.min,Number.NEGATIVE_INFINITY),max:In(e.max,Number.POSITIVE_INFINITY)};for(const l of t)l.scaleID===i?FL(l,e,["value","endValue"],a):x0(n,l,o)===i&&FL(l,e,[r+"Min",r+"Max",r+"Value"],a);return a}function FL(n,e,t,r){for(const i of t){const o=n[i];if(ol(o)){const a=e.parse(o);r.min=Math.min(r.min,a),r.max=Math.max(r.max,a)}}}class b1 extends Oo{inRange(e,t,r,i){const{x:o,y:a}=R0({x:e,y:t},this.getCenterPoint(i),fo(-this.options.rotation));return zU({x:o,y:a},this.getProps(["x","y","x2","y2"],i),r,this.options)}getCenterPoint(e){return B0(this,e)}draw(e){e.save(),TF(e,this.getCenterPoint(),this.options.rotation),XU(e,this,this.options),e.restore()}get label(){return this.elements&&this.elements[0]}resolveElementProperties(e,t){return eH(e,t)}}b1.id="boxAnnotation";b1.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderRadius:0,borderShadowColor:"transparent",borderWidth:1,display:!0,init:void 0,hitTolerance:0,label:{backgroundColor:"transparent",borderWidth:0,callout:{display:!1},color:"black",content:null,display:!1,drawTime:void 0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:"bold"},height:void 0,hitTolerance:void 0,opacity:void 0,padding:6,position:"center",rotation:void 0,textAlign:"start",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,yAdjust:0,z:void 0},rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,xMax:void 0,xMin:void 0,xScaleID:void 0,yMax:void 0,yMin:void 0,yScaleID:void 0,z:0};b1.defaultRoutes={borderColor:"color",backgroundColor:"color"};b1.descriptors={label:{_fallback:!0}};class DF extends Oo{inRange(e,t,r,i){return OU({x:e,y:t},{rect:this.getProps(["x","y","x2","y2"],i),center:this.getCenterPoint(i)},r,{rotation:this.rotation,borderWidth:0,hitTolerance:this.options.hitTolerance})}getCenterPoint(e){return B0(this,e)}draw(e){const t=this.options;!t.display||!t.content||(Kie(e,this),e.save(),TF(e,this.getCenterPoint(),this.rotation),YU(e,this,t,this._fitRatio),e.restore())}resolveElementProperties(e,t){const r=Uie(e,t);if(!r)return{};const{controllerMeta:i,point:o,radius:a}=qie(e,t,r);let l=FF(e.ctx,t);const d=Vie(l,a);HU(t,d)&&(l={width:l.width*d,height:l.height*d});const{position:c,xAdjust:u,yAdjust:f}=t,p=UU(o,l,{borderWidth:0,position:c,xAdjust:u,yAdjust:f});return{initProperties:y1(e,p,t),...p,...i,rotation:t.rotation,_fitRatio:d}}}DF.id="doughnutLabelAnnotation";DF.defaults={autoFit:!0,autoHide:!0,backgroundColor:"transparent",backgroundShadowColor:"transparent",borderColor:"transparent",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderShadowColor:"transparent",borderWidth:0,color:"black",content:null,display:!0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:void 0},height:void 0,hitTolerance:0,init:void 0,opacity:void 0,position:"center",rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,spacing:1,textAlign:"center",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,yAdjust:0};DF.defaultRoutes={};function Uie(n,e){return n.getSortedVisibleDatasetMetas().reduce(function(t,r){const i=r.controller;return i instanceof eS&&Hie(n,e,r.data)&&(!t||i.innerRadius=90?r:t},void 0)}function Hie(n,e,t){if(!e.autoHide)return!0;for(let r=0;rf,x=v?i+m:a-m,w=Gie(x,u,f,y);return{controllerMeta:{_centerX:u,_centerY:f,_radius:y,_counterclockwise:v,...w},point:g,radius:Math.min(l,Math.min(p.right-p.left,p.bottom-p.top)/2)}}function Vie({width:n,height:e},t){const r=Math.sqrt(Math.pow(n,2)+Math.pow(e,2));return t*2/r}function Gie(n,e,t,r){const i=Math.pow(t-n,2),o=Math.pow(r,2),a=e*-2,l=Math.pow(e,2)+i-o,d=Math.pow(a,2)-4*l;if(d<=0)return{_startAngle:0,_endAngle:Eo};const c=(-a-Math.sqrt(d))/2,u=(-a+Math.sqrt(d))/2;return{_startAngle:hB({x:e,y:t},{x:c,y:n}).angle,_endAngle:hB({x:e,y:t},{x:u,y:n}).angle}}function Kie(n,e){const{_centerX:t,_centerY:r,_radius:i,_startAngle:o,_endAngle:a,_counterclockwise:l,options:d}=e;n.save();const c=Cf(n,d);n.fillStyle=d.backgroundColor,n.beginPath(),n.arc(t,r,i,o,a,l),n.closePath(),n.fill(),c&&n.stroke(),n.restore()}class Y_ extends Oo{inRange(e,t,r,i){return OU({x:e,y:t},{rect:this.getProps(["x","y","x2","y2"],i),center:this.getCenterPoint(i)},r,{rotation:this.rotation,borderWidth:this.options.borderWidth,hitTolerance:this.options.hitTolerance})}getCenterPoint(e){return B0(this,e)}draw(e){const t=this.options,r=!ol(this._visible)||this._visible;!t.display||!t.content||!r||(e.save(),TF(e,this.getCenterPoint(),this.rotation),mie(e,this),XU(e,this,t),YU(e,Xie(this),t),e.restore())}resolveElementProperties(e,t){let r;if(VU(t))r=ZU(e,t);else{const{centerX:l,centerY:d}=K6(e,t);r={x:l,y:d}}const i=sa(t.padding),o=FF(e.ctx,t),a=UU(r,o,t,i);return{initProperties:y1(e,a,t),pointX:r.x,pointY:r.y,...a,rotation:t.rotation}}}Y_.id="labelAnnotation";Y_.defaults={adjustScaleRange:!0,backgroundColor:"transparent",backgroundShadowColor:"transparent",borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderRadius:0,borderShadowColor:"transparent",borderWidth:0,callout:{borderCapStyle:"butt",borderColor:void 0,borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:1,display:!1,margin:5,position:"auto",side:5,start:"50%"},color:"black",content:null,display:!0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:void 0},height:void 0,hitTolerance:0,init:void 0,opacity:void 0,padding:6,position:"center",rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,textAlign:"center",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,xMax:void 0,xMin:void 0,xScaleID:void 0,xValue:void 0,yAdjust:0,yMax:void 0,yMin:void 0,yScaleID:void 0,yValue:void 0,z:0};Y_.defaultRoutes={borderColor:"color"};function Xie({x:n,y:e,width:t,height:r,options:i}){const o=i.borderWidth/2,a=sa(i.padding);return{x:n+a.left+o,y:e+a.top+o,width:t-a.left-a.right-i.borderWidth,height:r-a.top-a.bottom-i.borderWidth}}const Y6=(n,e,t)=>({x:n.x+t*(e.x-n.x),y:n.y+t*(e.y-n.y)}),vB=(n,e,t)=>Y6(e,t,Math.abs((n-e.y)/(t.y-e.y))).x,DL=(n,e,t)=>Y6(e,t,Math.abs((n-e.x)/(t.x-e.x))).y,rS=n=>n*n,Yie=(n,e,{x:t,y:r,x2:i,y2:o},a)=>a==="y"?{start:Math.min(r,o),end:Math.max(r,o),value:e}:{start:Math.min(t,i),end:Math.max(t,i),value:n},EL=(n,e,t,r)=>(1-r)*(1-r)*n+2*(1-r)*r*e+r*r*t,wB=(n,e,t,r)=>({x:EL(n.x,e.x,t.x,r),y:EL(n.y,e.y,t.y,r)}),PL=(n,e,t,r)=>2*(1-r)*(e-n)+2*r*(t-e),RL=(n,e,t,r)=>-Math.atan2(PL(n.x,e.x,t.x,r),PL(n.y,e.y,t.y,r))+.5*Or;class Q_ extends Oo{inRange(e,t,r,i){const o=(this.options.borderWidth+this.options.hitTolerance)/2;if(r!=="x"&&r!=="y"){const a={mouseX:e,mouseY:t},{path:l,ctx:d}=this;if(l){Cf(d,this.options),d.lineWidth+=this.options.hitTolerance;const{chart:u}=this.$context,f=e*u.currentDevicePixelRatio,p=t*u.currentDevicePixelRatio,g=d.isPointInStroke(l,f,p)||SB(this,a,i);return d.restore(),g}const c=rS(o);return Jie(this,a,c,i)||SB(this,a,i)}return Qie(this,{mouseX:e,mouseY:t},r,{hitSize:o,useFinalPosition:i})}getCenterPoint(e){return B0(this,e)}draw(e){const{x:t,y:r,x2:i,y2:o,cp:a,options:l}=this;if(e.save(),!Cf(e,l))return e.restore();x1(e,l);const d=Math.sqrt(Math.pow(i-t,2)+Math.pow(o-r,2));if(l.curve&&a)return ase(e,this,a,d),e.restore();const{startOpts:c,endOpts:u,startAdjust:f,endAdjust:p}=rH(this),g=Math.atan2(o-r,i-t);e.translate(t,r),e.rotate(g),e.beginPath(),e.moveTo(0+f,0),e.lineTo(d-p,0),e.shadowColor=l.borderShadowColor,e.stroke(),jB(e,0,f,c),jB(e,d,-p,u),e.restore()}get label(){return this.elements&&this.elements[0]}resolveElementProperties(e,t){const r=kie(e,t),{x:i,y:o,x2:a,y2:l}=r,d=$ie(r,e.chartArea),c=d?Zie({x:i,y:o},{x:a,y:l},e.chartArea):{x:i,y:o,x2:a,y2:l,width:Math.abs(a-i),height:Math.abs(l-o)};if(c.centerX=(a+i)/2,c.centerY=(l+o)/2,c.initProperties=y1(e,c,t),t.curve){const f={x:c.x,y:c.y},p={x:c.x2,y:c.y2};c.cp=ose(c,t,r1(f,p))}const u=ese(e,c,t.label);return u._visible=d,c.elements=[{type:"label",optionScope:"label",properties:u,initProperties:c.initProperties}],c}}Q_.id="lineAnnotation";const BL={backgroundColor:void 0,backgroundShadowColor:void 0,borderColor:void 0,borderDash:void 0,borderDashOffset:void 0,borderShadowColor:void 0,borderWidth:void 0,display:void 0,fill:void 0,length:void 0,shadowBlur:void 0,shadowOffsetX:void 0,shadowOffsetY:void 0,width:void 0};Q_.defaults={adjustScaleRange:!0,arrowHeads:{display:!1,end:Object.assign({},BL),fill:!1,length:12,start:Object.assign({},BL),width:6},borderDash:[],borderDashOffset:0,borderShadowColor:"transparent",borderWidth:2,curve:!1,controlPoint:{y:"-50%"},display:!0,endValue:void 0,init:void 0,hitTolerance:0,label:{backgroundColor:"rgba(0,0,0,0.8)",backgroundShadowColor:"transparent",borderCapStyle:"butt",borderColor:"black",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderRadius:6,borderShadowColor:"transparent",borderWidth:0,callout:Object.assign({},Y_.defaults.callout),color:"#fff",content:null,display:!1,drawTime:void 0,font:{family:void 0,lineHeight:void 0,size:void 0,style:void 0,weight:"bold"},height:void 0,hitTolerance:void 0,opacity:void 0,padding:6,position:"center",rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,textAlign:"center",textStrokeColor:void 0,textStrokeWidth:0,width:void 0,xAdjust:0,yAdjust:0,z:void 0},scaleID:void 0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,value:void 0,xMax:void 0,xMin:void 0,xScaleID:void 0,yMax:void 0,yMin:void 0,yScaleID:void 0,z:0};Q_.descriptors={arrowHeads:{start:{_fallback:!0},end:{_fallback:!0},_fallback:!0}};Q_.defaultRoutes={borderColor:"color"};function Qie(n,{mouseX:e,mouseY:t},r,{hitSize:i,useFinalPosition:o}){const a=Yie(e,t,n.getProps(["x","y","x2","y2"],o),r);return MU(a,i)||SB(n,{mouseX:e,mouseY:t},o,r)}function $ie({x:n,y:e,x2:t,y2:r},{top:i,right:o,bottom:a,left:l}){return!(no&&t>o||ea&&r>a)}function IL({x:n,y:e},t,{top:r,right:i,bottom:o,left:a}){return ni&&(e=DL(i,{x:n,y:e},t),n=i),eo&&(n=vB(o,{x:n,y:e},t),e=o),{x:n,y:e}}function Zie(n,e,t){const{x:r,y:i}=IL(n,e,t),{x:o,y:a}=IL(e,n,t);return{x:r,y:i,x2:o,y2:a,width:Math.abs(o-r),height:Math.abs(a-i)}}function Jie(n,{mouseX:e,mouseY:t},r=wm,i){const{x:o,y:a,x2:l,y2:d}=n.getProps(["x","y","x2","y2"],i),c=l-o,u=d-a,f=rS(c)+rS(u),p=f===0?-1:((e-o)*c+(t-a)*u)/f;let g,m;return p<0?(g=o,m=a):p>1?(g=l,m=d):(g=o+p*c,m=a+p*u),rS(e-g)+rS(t-m)<=r}function SB(n,{mouseX:e,mouseY:t},r,i){const o=n.label;return o.options.display&&o.inRange(e,t,i,r)}function ese(n,e,t){const r=t.borderWidth,i=sa(t.padding),o=FF(n.ctx,t),a=o.width+i.width+r,l=o.height+i.height+r;return nse(e,t,{width:a,height:l,padding:i},n.chartArea)}function tse(n){const{x:e,y:t,x2:r,y2:i}=n,o=Math.atan2(i-t,r-e);return o>Or/2?o-Or:o0&&(i.w/2+o.left-r.x)/a,c=l>0&&(i.h/2+o.top-r.y)/l;return CF(Math.max(d,c),0,.25)}function sse(n,e){const{x:t,x2:r,y:i,y2:o}=n,a=Math.min(i,o)-e.top,l=Math.min(t,r)-e.left,d=e.bottom-Math.max(i,o),c=e.right-Math.max(t,r);return{x:Math.min(l,c),y:Math.min(a,d),dx:l<=c?1:-1,dy:a<=d?1:-1}}function zL(n,e){const{size:t,min:r,max:i,padding:o}=e,a=t/2;return t>i-r?(i+r)/2:(r>=n-o-a&&(n=r+o+a),i<=n+o+a&&(n=i-o-a),n)}function rH(n){const e=n.options,t=e.arrowHeads&&e.arrowHeads.start,r=e.arrowHeads&&e.arrowHeads.end;return{startOpts:t,endOpts:r,startAdjust:OL(n,t),endAdjust:OL(n,r)}}function OL(n,e){if(!e||!e.display)return 0;const{length:t,width:r}=e,i=n.options.borderWidth/2,o={x:t,y:r+i};return Math.abs(vB(0,o,{x:0,y:i}))}function jB(n,e,t,r){if(!r||!r.display)return;const{length:i,width:o,fill:a,backgroundColor:l,borderColor:d}=r,c=Math.abs(e-i)+t;n.beginPath(),x1(n,r),Cf(n,r),n.moveTo(c,-o),n.lineTo(e+t,0),n.lineTo(c,o),a===!0?(n.fillStyle=l||d,n.closePath(),n.fill(),n.shadowColor="transparent"):n.shadowColor=r.borderShadowColor,n.stroke()}function ose(n,e,t){const{x:r,y:i,x2:o,y2:a,centerX:l,centerY:d}=n,c=Math.atan2(a-i,o-r),u=G6(e.controlPoint,0),f={x:l+Mg(t,u.x,!1),y:d+Mg(t,u.y,!1)};return R0(f,{x:l,y:d},c)}function LL(n,{x:e,y:t},{angle:r,adjust:i},o){!o||!o.display||(n.save(),n.translate(e,t),n.rotate(r),jB(n,0,-i,o),n.restore())}function ase(n,e,t,r){const{x:i,y:o,x2:a,y2:l,options:d}=e,{startOpts:c,endOpts:u,startAdjust:f,endAdjust:p}=rH(e),g={x:i,y:o},m={x:a,y:l},y=RL(g,t,m,0),v=RL(g,t,m,1)-Or,x=wB(g,t,m,f/r),w=wB(g,t,m,1-p/r),S=new Path2D;n.beginPath(),S.moveTo(x.x,x.y),S.quadraticCurveTo(t.x,t.y,w.x,w.y),n.shadowColor=d.borderShadowColor,n.stroke(S),e.path=S,e.ctx=n,LL(n,x,{angle:y,adjust:f},c),LL(n,w,{angle:v,adjust:p},u)}class $_ extends Oo{inRange(e,t,r,i){const o=this.options.rotation,a=(this.options.borderWidth+this.options.hitTolerance)/2;if(r!=="x"&&r!=="y")return lse({x:e,y:t},this.getProps(["width","height","centerX","centerY"],i),o,a);const{x:l,y:d,x2:c,y2:u}=this.getProps(["x","y","x2","y2"],i),f=r==="y"?{start:d,end:u}:{start:l,end:c},p=R0({x:e,y:t},this.getCenterPoint(i),fo(-o));return p[r]>=f.start-a-wm&&p[r]<=f.end+a+wm}getCenterPoint(e){return B0(this,e)}draw(e){const{width:t,height:r,centerX:i,centerY:o,options:a}=this;e.save(),TF(e,this.getCenterPoint(),a.rotation),x1(e,this.options),e.beginPath(),e.fillStyle=a.backgroundColor;const l=Cf(e,a);e.ellipse(i,o,r/2,t/2,Or/2,0,2*Or),e.fill(),l&&(e.shadowColor=a.borderShadowColor,e.stroke()),e.restore()}get label(){return this.elements&&this.elements[0]}resolveElementProperties(e,t){return eH(e,t)}}$_.id="ellipseAnnotation";$_.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderDash:[],borderDashOffset:0,borderShadowColor:"transparent",borderWidth:1,display:!0,hitTolerance:0,init:void 0,label:Object.assign({},b1.defaults.label),rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,xMax:void 0,xMin:void 0,xScaleID:void 0,yMax:void 0,yMin:void 0,yScaleID:void 0,z:0};$_.defaultRoutes={borderColor:"color",backgroundColor:"color"};$_.descriptors={label:{_fallback:!0}};function lse(n,e,t,r){const{width:i,height:o,centerX:a,centerY:l}=e,d=i/2,c=o/2;if(d<=0||c<=0)return!1;const u=fo(t||0),f=Math.cos(u),p=Math.sin(u),g=Math.pow(f*(n.x-a)+p*(n.y-l),2),m=Math.pow(p*(n.x-a)-f*(n.y-l),2);return g/Math.pow(d+r,2)+m/Math.pow(c+r,2)<=1.0001}class EF extends Oo{inRange(e,t,r,i){const{x:o,y:a,x2:l,y2:d,width:c}=this.getProps(["x","y","x2","y2","width"],i),u=(this.options.borderWidth+this.options.hitTolerance)/2;return r!=="x"&&r!=="y"?nie({x:e,y:t},this.getCenterPoint(i),c/2,u):MU(r==="y"?{start:a,end:d,value:t}:{start:o,end:l,value:e},u)}getCenterPoint(e){return B0(this,e)}draw(e){const t=this.options,r=t.borderWidth;if(t.radius<.1)return;e.save(),e.fillStyle=t.backgroundColor,x1(e,t);const i=Cf(e,t);cie(e,this,this.centerX,this.centerY),i&&!AF(t.pointStyle)&&(e.shadowColor=t.borderShadowColor,e.stroke()),e.restore(),t.borderWidth=r}resolveElementProperties(e,t){const r=JU(e,t);return r.initProperties=y1(e,r,t),r}}EF.id="pointAnnotation";EF.defaults={adjustScaleRange:!0,backgroundShadowColor:"transparent",borderDash:[],borderDashOffset:0,borderShadowColor:"transparent",borderWidth:1,display:!0,hitTolerance:0,init:void 0,pointStyle:"circle",radius:10,rotation:0,shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,xAdjust:0,xMax:void 0,xMin:void 0,xScaleID:void 0,xValue:void 0,yAdjust:0,yMax:void 0,yMin:void 0,yScaleID:void 0,yValue:void 0,z:0};EF.defaultRoutes={borderColor:"color",backgroundColor:"color"};class PF extends Oo{inRange(e,t,r,i){if(r!=="x"&&r!=="y")return this.options.radius>=.1&&this.elements.length>1&&cse(this.elements,e,t,i);const o=R0({x:e,y:t},this.getCenterPoint(i),fo(-this.options.rotation)),a=this.elements.map(c=>r==="y"?c.bY:c.bX),l=Math.min(...a),d=Math.max(...a);return o[r]>=l&&o[r]<=d}getCenterPoint(e){return B0(this,e)}draw(e){const{elements:t,options:r}=this;e.save(),e.beginPath(),e.fillStyle=r.backgroundColor,x1(e,r);const i=Cf(e,r);let o=!0;for(const a of t)o?(e.moveTo(a.x,a.y),o=!1):e.lineTo(a.x,a.y);e.closePath(),e.fill(),i&&(e.shadowColor=r.borderShadowColor,e.stroke()),e.restore()}resolveElementProperties(e,t){const r=JU(e,t),{sides:i,rotation:o}=t,a=[],l=2*Or/i;let d=o*F6;for(let c=0;ct!=o.bY>t&&e<(o.bX-l.bX)*(t-l.bY)/(o.bY-l.bY)+l.bX&&(i=!i),o=l}return i}const Fg={box:b1,doughnutLabel:DF,ellipse:$_,label:Y_,line:Q_,point:EF,polygon:PF};Object.keys(Fg).forEach(n=>{hs.describe(`elements.${Fg[n].id}`,{_fallback:"plugins.annotation.common"})});const use={update:Object.assign},hse=X6.concat($A),NL=(n,e)=>Yn(e)?_B(n,e):n,kB=n=>n==="color"||n==="font";function Q6(n="line"){return Fg[n]?n:(console.warn(`Unknown annotation type: '${n}', defaulting to 'line'`),"line")}function fse(n,e,t,r){const i=gse(n,t.animations,r),o=e.annotations,a=xse(e.elements,o);for(let l=0;lNL(a,i)):t[r]=NL(o,i)}return t}function yse(n,e,t,r){return e.$context||(e.$context=Object.assign(Object.create(n.getContext()),{element:e,get elements(){return t.filter(i=>i&&i.options)},id:r.id,type:"annotation"}))}function xse(n,e){const t=e.length,r=n.length;if(rt&&n.splice(t,r-t);return n}var bse="3.1.0";const Qf=new Map,WL=n=>n.type!=="doughnutLabel",vse=X6.concat($A);var wse={id:"annotation",version:bse,beforeRegister(){rie("chart.js","4.0",pf.version)},afterRegister(){pf.register(Fg)},afterUnregister(){pf.unregister(Fg)},beforeInit(n){Qf.set(n,{annotations:[],elements:[],visibleElements:[],listeners:{},listened:!1,moveListened:!1,hooks:{},hooked:!1,hovered:[]})},beforeUpdate(n,e,t){const r=Qf.get(n),i=r.annotations=[];let o=t.annotations;Yn(o)?Object.keys(o).forEach(a=>{const l=o[a];Yn(l)&&(l.id=a,i.push(l))}):ki(o)&&i.push(...o),zie(i.filter(WL),n.scales)},afterDataLimits(n,e){const t=Qf.get(n);Mie(n,e.scale,t.annotations.filter(WL).filter(r=>r.display&&r.adjustScaleRange))},afterUpdate(n,e,t){const r=Qf.get(n);Eie(n,r,t),fse(n,r,t,e.mode),r.visibleElements=r.elements.filter(i=>!i.skip&&i.options.display),Iie(n,r,t)},beforeDatasetsDraw(n,e,t){Bw(n,"beforeDatasetsDraw",t.clip)},afterDatasetsDraw(n,e,t){Bw(n,"afterDatasetsDraw",t.clip)},beforeDatasetDraw(n,e,t){Bw(n,e.index,t.clip)},beforeDraw(n,e,t){Bw(n,"beforeDraw",t.clip)},afterDraw(n,e,t){Bw(n,"afterDraw",t.clip)},beforeEvent(n,e,t){const r=Qf.get(n);Pie(r,e.event,t)&&(e.changed=!0)},afterDestroy(n){Qf.delete(n)},getAnnotations(n){const e=Qf.get(n);return e?e.elements:[]},_getAnnotationElementsAtEventForMode(n,e,t){return q6(n,e,t)},defaults:{animations:{numbers:{properties:["x","y","x2","y2","width","height","centerX","centerY","pointX","pointY","radius"],type:"number"},colors:{properties:["backgroundColor","borderColor"],type:"color"}},clip:!0,interaction:{mode:void 0,axis:void 0,intersect:void 0},common:{drawTime:"afterDatasetsDraw",init:!1,label:{}}},descriptors:{_indexable:!1,_scriptable:n=>!vse.includes(n)&&n!=="init",annotations:{_allKeys:!1,_fallback:(n,e)=>`elements.${Fg[Q6(e.type)].id}`},interaction:{_fallback:!0},common:{label:{_indexable:kB,_fallback:!0},_indexable:kB}},additionalOptionScopes:[""]};function Bw(n,e,t){const{ctx:r,chartArea:i}=n,o=Qf.get(n);t&&wF(r,i);const a=Sse(o.visibleElements,e).sort((l,d)=>l.element.options.z-d.element.options.z);for(const l of a)jse(r,i,o,l);t&&SF(r)}function Sse(n,e){const t=[];for(const r of n)if(r.options.drawTime===e&&t.push({element:r,main:!0}),r.elements&&r.elements.length)for(const i of r.elements)i.options.display&&i.options.drawTime===e&&t.push({element:i});return t}function jse(n,e,t,r){const i=r.element;r.main?(AL(t,i,"beforeDraw"),i.draw(n,e),AL(t,i,"afterDraw")):i.draw(n,e)}pf.register(Bj,Ij,GS,qx,U6,H6,W6,wse);const oH="bookings-stats-from-date",aH="bookings-stats-to-date",kse=()=>{const n=sessionStorage.getItem(oH),e=sessionStorage.getItem(aH);if(n&&e)return{from:n,to:e};const t=new Date,r=new Date(t);return r.setDate(t.getDate()-30),{from:r.toISOString().split("T")[0],to:t.toISOString().split("T")[0]}};function _se(){const{token:n}=gn(),e=kse(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(e.from),[d,c]=k.useState(e.to);k.useEffect(()=>{sessionStorage.setItem(oH,a),sessionStorage.setItem(aH,d)},[a,d]);const u=t!==a||i!==d,f=()=>{l(t),c(i)},[p,g]=k.useState(!1),[m,y]=k.useState(null),{data:v,isLoading:x}=Oe({queryKey:["resos-stats",a,d],queryFn:async()=>{const P=await fetch(`/api/resos/stats?from_date=${a}&to_date=${d}`,{headers:{Authorization:`Bearer ${n}`}});if(!P.ok)throw new Error("Failed to fetch stats");return P.json()},staleTime:2*60*1e3}),w=()=>{const P=new Date(a),L=new Date(d),W=Math.floor((L.getTime()-P.getTime())/(1e3*60*60*24)),O=new Date(P);O.setDate(O.getDate()-1);const U=new Date(O);return U.setDate(U.getDate()-W),{from:U.toISOString().split("T")[0],to:O.toISOString().split("T")[0]}},{data:S}=Oe({queryKey:["resos-stats-previous",a,d],queryFn:async()=>{const P=w(),L=await fetch(`/api/resos/stats?from_date=${P.from}&to_date=${P.to}`,{headers:{Authorization:`Bearer ${n}`}});if(!L.ok)throw new Error("Failed to fetch previous stats");return L.json()},enabled:p,staleTime:2*60*1e3}),{data:_}=Oe({queryKey:["resos-bookings",m],queryFn:async()=>{const P=await fetch(`/api/resos/bookings/${m}`,{headers:{Authorization:`Bearer ${n}`}});if(!P.ok)throw new Error("Failed to fetch bookings");return P.json()},enabled:!!m}),b=()=>{const P=new Date,L=new Date;L.setDate(L.getDate()-30),r(L.toISOString().split("T")[0]),o(P.toISOString().split("T")[0])},C=()=>{const P=new Date,L=new Date;L.setDate(L.getDate()-90),r(L.toISOString().split("T")[0]),o(P.toISOString().split("T")[0])},T=P=>new Intl.NumberFormat("en-GB",{style:"currency",currency:"GBP",minimumFractionDigits:0,maximumFractionDigits:0}).format(P),F=P=>new Date(P).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),A=()=>{if(!v||!v.daily_breakdown||v.daily_breakdown.length===0)return s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"No data available"});const P=v.daily_breakdown.map(M=>F(M.date)),L=new Date().toISOString().split("T")[0],W=v.daily_breakdown.findIndex(M=>M.date===L),O=W!==-1,U=[{label:"Bookings",data:v.daily_breakdown.map(M=>M.total_bookings),borderColor:"rgb(102, 126, 234)",backgroundColor:"rgba(102, 126, 234, 0.1)",yAxisID:"y"},{label:"Covers",data:v.daily_breakdown.map(M=>M.total_covers),borderColor:"rgb(118, 75, 162)",backgroundColor:"rgba(118, 75, 162, 0.1)",yAxisID:"y"},{label:"Spend (£)",data:v.daily_breakdown.map(M=>M.total_spend),borderColor:"rgb(237, 100, 166)",backgroundColor:"rgba(237, 100, 166, 0.1)",yAxisID:"y1"}];return p&&(S!=null&&S.daily_breakdown)&&U.push({label:"Prev Bookings",data:S.daily_breakdown.map(M=>M.total_bookings),borderColor:"rgba(102, 126, 234, 0.4)",backgroundColor:"transparent",borderDash:[5,5],yAxisID:"y"},{label:"Prev Covers",data:S.daily_breakdown.map(M=>M.total_covers),borderColor:"rgba(118, 75, 162, 0.4)",backgroundColor:"transparent",borderDash:[5,5],yAxisID:"y"},{label:"Prev Spend (£)",data:S.daily_breakdown.map(M=>M.total_spend),borderColor:"rgba(237, 100, 166, 0.4)",backgroundColor:"transparent",borderDash:[5,5],yAxisID:"y1"}),s.jsx(IU,{data:{labels:P,datasets:U},options:{responsive:!0,maintainAspectRatio:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{position:"top"},tooltip:{callbacks:{label:M=>{let I=M.dataset.label||"";I&&(I+=": ");const H=M.parsed.y;return H!==null&&(I.includes("Spend")?I+=T(H):I+=H),I}}},annotation:O?{annotations:{todayLine:{type:"line",xMin:W,xMax:W,borderColor:"rgba(255, 99, 132, 0.8)",borderWidth:2,borderDash:[5,5],label:{display:!0,content:"Today",position:"start",backgroundColor:"rgba(255, 99, 132, 0.8)",color:"white",padding:4,font:{size:11,weight:"bold"}}}}}:{}},scales:{y:{type:"linear",display:!0,position:"left",title:{display:!0,text:"Bookings / Covers"}},y1:{type:"linear",display:!0,position:"right",title:{display:!0,text:"Spend (£)"},grid:{drawOnChartArea:!1}}},onClick:(M,I)=>{if(I.length>0){const H=I[0].index,z=v.daily_breakdown[H].date;y(z)}}}})},D=()=>{if(!m||!_)return null;const P=_.filter(W=>W.is_flagged),L=v==null?void 0:v.daily_breakdown.find(W=>W.date===m);return s.jsx("div",{style:lt.modalOverlay,onClick:()=>y(null),children:s.jsxs("div",{style:lt.modal,onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{style:lt.modalHeader,children:[s.jsxs("h2",{children:["Bookings for ",F(m)]}),s.jsx("button",{onClick:()=>y(null),style:lt.closeBtn,children:"×"})]}),s.jsxs("div",{style:lt.modalContent,children:[L&&s.jsxs("div",{style:lt.daySummary,children:[s.jsxs("div",{style:lt.summaryRow,children:[s.jsxs("span",{children:[s.jsx("strong",{children:L.total_bookings})," Bookings"]}),s.jsxs("span",{children:[s.jsx("strong",{children:L.total_covers})," Covers"]}),s.jsxs("span",{children:[s.jsx("strong",{children:T(L.total_spend)})," Total Spend"]})]}),s.jsxs("div",{style:lt.summaryRow,children:[s.jsxs("span",{children:["Food: ",T(L.food_spend)]}),s.jsxs("span",{children:["Beverage: ",T(L.beverage_spend)]}),s.jsxs("span",{children:[L.ticket_count," SambaPOS Tickets Matched"]})]})]}),P.length>0&&s.jsxs("div",{style:lt.flaggedSection,children:[s.jsx("h3",{children:"Notable Bookings 🦀"}),P.map(W=>s.jsxs("div",{style:lt.flaggedBooking,children:[s.jsx("div",{children:s.jsxs("strong",{children:[W.opening_hour_name," - ",W.booking_time]})}),s.jsxs("div",{children:["Party of ",W.people]}),W.allergies&&s.jsxs("div",{style:lt.allergyBadge,children:["Allergies: ",W.allergies]}),W.notes&&s.jsxs("div",{style:lt.noteText,children:["Notes: ",W.notes]}),W.flag_reasons&&s.jsxs("div",{style:lt.flagReasons,children:["Flags: ",W.flag_reasons.split(",").join(", ")]})]},W.id))]}),s.jsxs("h3",{children:["All Bookings (",_.length,")"]}),s.jsxs("table",{style:lt.bookingsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:lt.th,children:"Time"}),s.jsx("th",{style:lt.th,children:"Service"}),s.jsx("th",{style:lt.th,children:"Covers"}),s.jsx("th",{style:lt.th,children:"Status"}),s.jsx("th",{style:lt.th,children:"Hotel Guest"}),s.jsx("th",{style:lt.th,children:"Notes"})]})}),s.jsx("tbody",{children:_.map(W=>s.jsxs("tr",{style:W.is_flagged?lt.flaggedRow:{},children:[s.jsx("td",{style:lt.td,children:W.booking_time}),s.jsx("td",{style:lt.td,children:W.opening_hour_name}),s.jsx("td",{style:lt.td,children:W.people}),s.jsx("td",{style:lt.td,children:W.status}),s.jsx("td",{style:lt.td,children:W.is_hotel_guest?"Yes":"No"}),s.jsx("td",{style:lt.td,children:W.notes||"-"})]},W.id))})]})]})]})})};return x?s.jsxs("div",{style:lt.container,children:[s.jsx("h1",{children:"Bookings Stats Report"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"Loading..."})]}):v?s.jsxs("div",{style:lt.container,children:[s.jsx("h1",{children:"Bookings Stats Report"}),s.jsx("div",{style:lt.constructionBanner,children:"This page is still under construction and not completed yet."}),s.jsxs("div",{style:lt.toolbar,children:[s.jsxs("div",{style:lt.toolbarRow,children:[s.jsxs("div",{children:[s.jsx("label",{children:"From: "}),s.jsx("input",{type:"date",value:t,onChange:P=>r(P.target.value),style:lt.dateInput})]}),s.jsxs("div",{children:[s.jsx("label",{children:"To: "}),s.jsx("input",{type:"date",value:i,onChange:P=>o(P.target.value),style:lt.dateInput})]}),s.jsx("button",{onClick:b,style:lt.button,children:"Last 30 Days"}),s.jsx("button",{onClick:C,style:lt.button,children:"Last 90 Days"}),s.jsxs("button",{onClick:f,style:{...lt.generateButton,...u?lt.generateButtonActive:{}},children:["Generate Report",u?" *":""]})]}),s.jsxs("div",{style:lt.toolbarRow,children:[s.jsxs("label",{style:lt.checkbox,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:P=>g(P.target.checked)}),"Show Previous Period Comparison"]}),u&&s.jsx("span",{style:{color:"#d9534f",fontSize:"0.85rem",marginLeft:"1rem"},children:"Date range changed - click Generate Report to update"})]})]}),s.jsxs("div",{style:lt.summaryGrid,children:[s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Total Bookings"}),s.jsx("div",{style:lt.summaryValue,children:v.summary.total_bookings})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Total Covers"}),s.jsx("div",{style:lt.summaryValue,children:v.summary.total_covers})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Avg Lead Time"}),s.jsxs("div",{style:lt.summaryValue,children:[v.summary.avg_lead_time_days," days"]})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Resident %"}),s.jsxs("div",{style:lt.summaryValue,children:[v.summary.resident_pct_covers,"%"]}),s.jsx("div",{style:lt.summarySub,children:"by covers"})]}),s.jsxs("div",{style:lt.summaryCard,children:[s.jsx("div",{style:lt.summaryLabel,children:"Resident Spend"}),s.jsxs("div",{style:lt.summaryValue,children:[v.summary.resident_pct_spend,"%"]}),s.jsx("div",{style:lt.summarySub,children:"by value"})]})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Spend Analysis"}),s.jsxs("div",{style:lt.spendGrid,children:[s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Total Spend"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.total_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Food"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.food_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Beverage"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.beverage_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Resident Spend"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.resident_spend)})]}),s.jsxs("div",{style:lt.spendCard,children:[s.jsx("div",{style:lt.spendLabel,children:"Non-Resident Spend"}),s.jsx("div",{style:lt.spendValue,children:T(v.spend.non_resident_spend)})]})]}),s.jsxs("div",{style:lt.matchingInfo,children:[s.jsxs("span",{children:["✅ ",v.spend.matched_tickets," tickets matched to bookings"]}),v.spend.unmatched_tickets>0&&s.jsxs("span",{style:{marginLeft:"1rem",color:"#e94560"},children:["⚠️ ",v.spend.unmatched_tickets," tickets unmatched"]})]})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Trends"}),s.jsx("div",{style:lt.chartContainer,children:A()}),s.jsx("div",{style:lt.chartHint,children:"💡 Click any point on the graph to see detailed breakdown for that day"})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Average Spend by Service Period"}),v.service_period_breakdown&&v.service_period_breakdown.length>0?s.jsxs("table",{style:lt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:lt.th,children:"Service Period"}),s.jsx("th",{style:lt.th,children:"Total Spend"}),s.jsx("th",{style:lt.th,children:"Food"}),s.jsx("th",{style:lt.th,children:"Beverage"}),s.jsx("th",{style:lt.th,children:"Covers"}),s.jsx("th",{style:lt.th,children:"Tickets"}),s.jsx("th",{style:lt.th,children:"Avg per Cover"})]})}),s.jsx("tbody",{children:v.service_period_breakdown.map(P=>{const L=P.resos_covers>0&&P.samba_covers>0&&P.resos_covers!==P.samba_covers;return s.jsxs("tr",{children:[s.jsx("td",{style:lt.td,children:s.jsx("strong",{children:P.service_period})}),s.jsx("td",{style:lt.td,children:T(P.total_spend)}),s.jsx("td",{style:lt.td,children:T(P.food_spend)}),s.jsx("td",{style:lt.td,children:T(P.beverage_spend)}),s.jsxs("td",{style:lt.td,children:[s.jsxs("span",{style:L?{fontStyle:"italic"}:{},children:[P.covers,L?" *":""]}),L&&s.jsxs("div",{style:{color:"#d9534f",fontSize:"0.75rem",fontStyle:"italic"},children:["Resos: ",P.resos_covers," / SambaPOS: ",P.samba_covers]})]}),s.jsx("td",{style:lt.td,children:P.ticket_count}),s.jsx("td",{style:lt.td,children:s.jsx("strong",{children:T(P.avg_spend_per_cover)})})]},P.service_period)})})]}):s.jsx("div",{style:{padding:"1rem",color:"#666"},children:"No spend data available. Ensure SambaPOS integration is configured with GL codes in Settings."})]}),s.jsxs("div",{style:lt.section,children:[s.jsx("h2",{children:"Daily Breakdown by Service Period"}),v.daily_service_breakdown&&v.daily_service_breakdown.length>0?(()=>{const P=new Set;v.daily_service_breakdown.forEach(O=>{Object.keys(O.periods).forEach(U=>P.add(U))});const W=["Breakfast","Lunch","Afternoon","Dinner"].filter(O=>P.has(O));return s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:lt.table,children:[s.jsxs("thead",{children:[s.jsxs("tr",{children:[s.jsx("th",{style:lt.th,children:"Date"}),W.map(O=>s.jsx("th",{style:{...lt.th,textAlign:"center"},children:O},O))]}),s.jsxs("tr",{style:{background:"#f8f9fa"},children:[s.jsx("th",{style:{...lt.th,fontSize:"0.75rem",padding:"0.5rem"}}),W.map(O=>s.jsx("th",{style:{...lt.th,fontSize:"0.75rem",padding:"0.5rem",textAlign:"center"},children:"Covers | Food | Bev"},O))]})]}),s.jsx("tbody",{children:v.daily_service_breakdown.map(O=>s.jsxs("tr",{children:[s.jsx("td",{style:{...lt.td,fontWeight:"bold"},children:F(O.date)}),W.map(U=>{const M=O.periods[U];if(!M)return s.jsx("td",{style:{...lt.td,textAlign:"center",color:"#ccc"},children:"-"},U);const I=M.resos_covers>0&&M.samba_covers>0&&M.resos_covers!==M.samba_covers;return s.jsx("td",{style:{...lt.td,textAlign:"center",fontSize:"0.85rem"},children:M.covers>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:I?{fontStyle:"italic"}:{},children:[M.covers," covers",I?" *":""]}),I&&s.jsxs("div",{style:{color:"#d9534f",fontSize:"0.7rem",fontStyle:"italic"},children:["Resos: ",M.resos_covers," / SambaPOS: ",M.samba_covers]}),s.jsxs("div",{style:{color:"#666",fontSize:"0.75rem"},children:[T(M.food)," | ",T(M.beverage)]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{color:"#999",fontSize:"0.75rem"},children:[M.ticket_count," ticket",M.ticket_count!==1?"s":""," (unmatched)"]}),s.jsxs("div",{style:{color:"#666",fontSize:"0.75rem"},children:[T(M.food)," | ",T(M.beverage)]})]})},U)})]},O.date))})]})})})():s.jsx("div",{style:{padding:"1rem",color:"#666"},children:"No daily breakdown data available."})]}),D()]}):s.jsxs("div",{style:lt.container,children:[s.jsx("h1",{children:"Bookings Stats Report"}),s.jsx("div",{style:{padding:"2rem",textAlign:"center"},children:"No data available"})]})}const lt={container:{padding:"2rem",background:"#f5f5f5",minHeight:"100vh"},constructionBanner:{background:"#fff3cd",color:"#856404",border:"1px solid #ffc107",borderRadius:"8px",padding:"1rem",marginBottom:"1rem",textAlign:"center",fontWeight:500},toolbar:{background:"white",padding:"1.5rem",borderRadius:"12px",marginBottom:"1rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},toolbarRow:{display:"flex",gap:"1rem",marginBottom:"0.5rem",alignItems:"center"},dateInput:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem"},button:{padding:"0.5rem 1rem",background:"#667eea",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},generateButton:{padding:"0.5rem 1.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem",fontWeight:"bold",transition:"all 0.2s"},generateButtonActive:{background:"#dc3545",animation:"pulse 1.5s ease-in-out infinite"},checkbox:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.95rem",cursor:"pointer"},summaryGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:"1rem",marginBottom:"1.5rem"},summaryCard:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",textAlign:"center"},summaryLabel:{fontSize:"0.85rem",color:"#666",marginBottom:"0.5rem",textTransform:"uppercase",letterSpacing:"0.5px"},summaryValue:{fontSize:"2rem",fontWeight:"bold",color:"#333"},summarySub:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem"},section:{background:"white",padding:"1.5rem",borderRadius:"12px",marginBottom:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},spendGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1rem"},spendCard:{background:"#f8f9fa",padding:"1rem",borderRadius:"8px",textAlign:"center"},spendLabel:{fontSize:"0.85rem",color:"#666",marginBottom:"0.5rem"},spendValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#333"},matchingInfo:{fontSize:"0.9rem",color:"#666",padding:"0.5rem 0"},chartContainer:{height:"400px",position:"relative",marginTop:"1rem"},chartHint:{fontSize:"0.85rem",color:"#666",textAlign:"center",marginTop:"1rem",fontStyle:"italic"},table:{width:"100%",borderCollapse:"collapse",marginTop:"1rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",fontWeight:"600",fontSize:"0.9rem",background:"#f8f9fa"},td:{padding:"0.75rem",borderBottom:"1px solid #eee"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",width:"90%",maxWidth:"900px",maxHeight:"90vh",overflow:"auto",padding:"24px"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem",paddingBottom:"1rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"2rem",cursor:"pointer",color:"#999"},modalContent:{fontSize:"0.95rem"},daySummary:{background:"#f8f9fa",padding:"1rem",borderRadius:"8px",marginBottom:"1.5rem"},summaryRow:{display:"flex",justifyContent:"space-around",gap:"1rem",marginBottom:"0.5rem",fontSize:"0.9rem"},flaggedSection:{background:"#fffbcc",borderLeft:"4px solid #ffcc00",padding:"1rem",marginBottom:"1.5rem",borderRadius:"4px"},flaggedBooking:{marginBottom:"1rem",paddingBottom:"0.5rem",borderBottom:"1px solid #ddd"},allergyBadge:{background:"#f8d7da",color:"#721c24",padding:"0.2rem 0.5rem",borderRadius:"4px",display:"inline-block",marginTop:"0.3rem",fontSize:"0.85rem"},noteText:{fontStyle:"italic",color:"#666",marginTop:"0.3rem",fontSize:"0.85rem"},flagReasons:{fontSize:"0.75rem",color:"#666",marginTop:"0.3rem"},bookingsTable:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem"},flaggedRow:{background:"#fffbcc"}},ZA={wastage:"#e94560",transfer:"#3498db",staff_food:"#27ae60",manual_adjustment:"#f39c12"},$6={wastage:"Wastage",transfer:"Transfer",staff_food:"Staff Food",manual_adjustment:"Manual Adjustment"},Cse=[{value:"spoiled",label:"Spoiled"},{value:"damaged",label:"Damaged"},{value:"expired",label:"Expired"},{value:"overproduction",label:"Overproduction"},{value:"quality_issue",label:"Quality Issue"},{value:"other",label:"Other"}],Ase=[{value:"breakfast",label:"Breakfast"},{value:"lunch",label:"Lunch"},{value:"dinner",label:"Dinner"},{value:"snack",label:"Snack"}];function Tse(){const{token:n}=gn(),e=pi(),[t]=K_(),[r,i]=k.useState(""),[o,a]=k.useState(t.get("date_from")||""),[l,d]=k.useState(t.get("date_to")||""),[c,u]=k.useState(null),[f,p]=k.useState(!1),[g,m]=k.useState("wastage"),y=new URLSearchParams;r&&y.append("entry_type",r),o&&y.append("date_from",o),l&&y.append("date_to",l);const v=y.toString(),{data:x,isLoading:w}=Oe({queryKey:["logbook",r,o,l],queryFn:async()=>{const A=v?`/api/logbook?${v}`:"/api/logbook",D=await fetch(A,{headers:{Authorization:`Bearer ${n}`}});if(!D.ok)throw new Error("Failed to fetch logbook entries");return D.json()},enabled:!!n}),S=new URLSearchParams;o&&S.append("date_from",o),l&&S.append("date_to",l);const _=S.toString(),{data:b}=Oe({queryKey:["logbook-summary",o,l],queryFn:async()=>{const A=_?`/api/logbook/summary?${_}`:"/api/logbook/summary",D=await fetch(A,{headers:{Authorization:`Bearer ${n}`}});if(!D.ok)throw new Error("Failed to fetch summary");return D.json()},enabled:!!n}),C=Ue({mutationFn:async A=>{const D=await fetch(`/api/logbook/${A}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!D.ok)throw new Error("Failed to delete entry");return D.json()},onSuccess:()=>{e.invalidateQueries({queryKey:["logbook"]}),e.invalidateQueries({queryKey:["logbook-summary"]}),u(null)}}),T=A=>$6[A]||A,F=A=>{var D,P,L,W,O;switch(A.entry_type){case"wastage":return`Reason: ${(((D=A.type_data)==null?void 0:D.reason)||"Unknown").replace(/_/g," ")}`;case"transfer":return`Status: ${(((P=A.type_data)==null?void 0:P.status)||"pending").replace(/_/g," ")}`;case"staff_food":return`Meal: ${((L=A.type_data)==null?void 0:L.meal_type)||"Unknown"}${(W=A.type_data)!=null&&W.staff_count?` (${A.type_data.staff_count} staff)`:""}`;case"manual_adjustment":return(O=A.type_data)!=null&&O.adjustment_reason?`Reason: ${A.type_data.adjustment_reason}`:"";default:return""}};return w?s.jsx("div",{style:Me.loading,children:"Loading logbook..."}):s.jsxs("div",{children:[s.jsxs("div",{style:Me.header,children:[s.jsx("h2",{style:Me.title,children:"Kitchen Logbook"}),s.jsx("button",{onClick:()=>p(!0),style:Me.createBtn,children:"+ New Entry"})]}),b&&s.jsxs("div",{style:Me.summaryGrid,children:[s.jsxs("div",{style:Me.summaryCard,children:[s.jsx("div",{style:Me.summaryValue,children:b.total_entries}),s.jsx("div",{style:Me.summaryLabel,children:"Total Entries"})]}),s.jsxs("div",{style:Me.summaryCard,children:[s.jsxs("div",{style:Me.summaryValue,children:["£",b.total_cost.toFixed(2)]}),s.jsx("div",{style:Me.summaryLabel,children:"Total Cost"})]}),Object.entries(b.by_type).map(([A,D])=>s.jsxs("div",{style:{...Me.summaryCard,borderLeft:`4px solid ${ZA[A]||"#999"}`},children:[s.jsxs("div",{style:Me.summaryValue,children:["£",D.total_cost.toFixed(2)]}),s.jsxs("div",{style:Me.summaryLabel,children:[T(A)," (",D.count,")"]})]},A))]}),s.jsxs("div",{style:Me.filters,children:[s.jsxs("select",{value:r,onChange:A=>i(A.target.value),style:Me.filterSelect,children:[s.jsx("option",{value:"",children:"All Types"}),s.jsx("option",{value:"wastage",children:"Wastage"}),s.jsx("option",{value:"transfer",children:"Transfer"}),s.jsx("option",{value:"staff_food",children:"Staff Food"}),s.jsx("option",{value:"manual_adjustment",children:"Manual Adjustment"})]}),s.jsx("input",{type:"date",value:o,onChange:A=>a(A.target.value),style:Me.filterInput,placeholder:"From date"}),s.jsx("input",{type:"date",value:l,onChange:A=>d(A.target.value),style:Me.filterInput,placeholder:"To date"}),(r||o||l)&&s.jsx("button",{onClick:()=>{i(""),a(""),d("")},style:Me.clearBtn,children:"Clear Filters"})]}),!x||x.length===0?s.jsxs("div",{style:Me.empty,children:[s.jsx("p",{children:"No logbook entries found."}),s.jsx("button",{onClick:()=>p(!0),style:Me.link,children:"Create your first entry"})]}):s.jsx("div",{style:Me.list,children:x.map(A=>s.jsxs("div",{onClick:()=>u(A),style:Me.card,children:[s.jsx("div",{style:Me.cardLeft,children:s.jsx("div",{style:{...Me.typeBadge,background:ZA[A.entry_type]||"#999"},children:T(A.entry_type)})}),s.jsxs("div",{style:Me.cardMain,children:[s.jsxs("div",{style:Me.cardDate,children:[new Date(A.entry_date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"}),A.reference_number&&s.jsxs("span",{style:Me.refNumber,children:["Ref: ",A.reference_number]})]}),s.jsx("div",{style:Me.cardInfo,children:F(A)}),s.jsxs("div",{style:Me.cardItems,children:[A.line_items.slice(0,3).map((D,P)=>s.jsxs("span",{style:Me.itemPill,children:[D.product_name," (",D.quantity,")"]},P)),A.line_items.length>3&&s.jsxs("span",{style:Me.moreItems,children:["+",A.line_items.length-3," more"]})]}),A.notes&&s.jsx("div",{style:Me.cardNotes,children:A.notes.length>80?`${A.notes.substring(0,80)}...`:A.notes})]}),s.jsxs("div",{style:Me.cardRight,children:[s.jsxs("div",{style:Me.amount,children:["£",A.total_cost.toFixed(2)]}),s.jsxs("div",{style:Me.cardMeta,children:[A.line_items.length," item",A.line_items.length!==1?"s":""]}),A.attachments.length>0&&s.jsxs("div",{style:Me.attachmentBadge,children:[A.attachments.length," attachment",A.attachments.length!==1?"s":""]})]})]},A.id))}),c&&s.jsx(Fse,{entry:c,onClose:()=>u(null),onDelete:()=>C.mutate(c.id)}),f&&s.jsx(Dse,{entryType:g,setEntryType:m,onClose:()=>p(!1),onSuccess:()=>{p(!1),e.invalidateQueries({queryKey:["logbook"]}),e.invalidateQueries({queryKey:["logbook-summary"]})}})]})}function Fse({entry:n,onClose:e,onDelete:t}){var o,a,l,d,c;const[r,i]=k.useState(!1);return s.jsx("div",{style:Me.modalOverlay,onClick:e,children:s.jsxs("div",{style:Me.modal,onClick:u=>u.stopPropagation(),children:[s.jsxs("div",{style:Me.modalHeader,children:[s.jsxs("h3",{style:Me.modalTitle,children:[s.jsx("span",{style:{...Me.typeBadge,background:ZA[n.entry_type]||"#999",marginRight:"0.75rem"},children:$6[n.entry_type]||n.entry_type}),new Date(n.entry_date).toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long",year:"numeric"})]}),s.jsx("button",{onClick:e,style:Me.closeBtn,children:"×"})]}),s.jsxs("div",{style:Me.modalBody,children:[s.jsxs("div",{style:Me.detailGrid,children:[s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Total Cost"}),s.jsxs("span",{style:Me.detailValue,children:["£",n.total_cost.toFixed(2)]})]}),n.reference_number&&s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Reference"}),s.jsx("span",{style:Me.detailValue,children:n.reference_number})]}),s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Created By"}),s.jsx("span",{style:Me.detailValue,children:n.created_by_name||`User #${n.created_by}`})]}),s.jsxs("div",{style:Me.detailItem,children:[s.jsx("span",{style:Me.detailLabel,children:"Created At"}),s.jsx("span",{style:Me.detailValue,children:new Date(n.created_at).toLocaleString("en-GB")})]})]}),n.entry_type==="wastage"&&((o=n.type_data)==null?void 0:o.reason)!=null&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Reason:"})," ",String(n.type_data.reason).replace(/_/g," ")]}),n.entry_type==="transfer"&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Status:"})," ",String(((a=n.type_data)==null?void 0:a.status)||"pending").replace(/_/g," ")]}),n.entry_type==="staff_food"&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Meal:"})," ",String(((l=n.type_data)==null?void 0:l.meal_type)||"Unknown"),((d=n.type_data)==null?void 0:d.staff_count)!=null&&s.jsxs(s.Fragment,{children:[" | ",s.jsx("strong",{children:"Staff Count:"})," ",Number(n.type_data.staff_count)]})]}),n.entry_type==="manual_adjustment"&&((c=n.type_data)==null?void 0:c.adjustment_reason)!=null&&s.jsxs("div",{style:Me.typeInfo,children:[s.jsx("strong",{children:"Adjustment Reason:"})," ",String(n.type_data.adjustment_reason)]}),n.notes&&s.jsxs("div",{style:Me.notesSection,children:[s.jsx("strong",{children:"Notes:"}),s.jsx("p",{style:Me.notesText,children:n.notes})]}),s.jsxs("div",{style:Me.lineItemsSection,children:[s.jsxs("h4",{style:Me.sectionTitle,children:["Items (",n.line_items.length,")"]}),s.jsxs("table",{style:Me.lineItemsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Me.th,children:"Product"}),s.jsx("th",{style:Me.th,children:"Qty"}),s.jsx("th",{style:Me.th,children:"Unit Price"}),s.jsx("th",{style:Me.th,children:"Total"})]})}),s.jsx("tbody",{children:n.line_items.map(u=>s.jsxs("tr",{children:[s.jsxs("td",{style:Me.td,children:[s.jsx("div",{children:u.product_name}),u.product_code&&s.jsx("div",{style:Me.productCode,children:u.product_code}),u.supplier_name&&s.jsx("div",{style:Me.supplierName,children:u.supplier_name})]}),s.jsxs("td",{style:Me.td,children:[u.quantity," ",u.unit||""]}),s.jsx("td",{style:Me.td,children:u.unit_price!=null?`£${u.unit_price.toFixed(2)}`:"-"}),s.jsxs("td",{style:Me.td,children:["£",u.total_cost.toFixed(2)]})]},u.id))}),s.jsx("tfoot",{children:s.jsxs("tr",{children:[s.jsx("td",{colSpan:3,style:{...Me.td,fontWeight:"bold",textAlign:"right"},children:"Total:"}),s.jsxs("td",{style:{...Me.td,fontWeight:"bold"},children:["£",n.total_cost.toFixed(2)]})]})})]})]}),n.attachments.length>0&&s.jsxs("div",{style:Me.attachmentsSection,children:[s.jsxs("h4",{style:Me.sectionTitle,children:["Attachments (",n.attachments.length,")"]}),s.jsx("div",{style:Me.attachmentsList,children:n.attachments.map(u=>s.jsxs("div",{style:Me.attachmentItem,children:[s.jsx("span",{children:u.file_name}),s.jsxs("span",{style:Me.attachmentSize,children:["(",(u.file_size_bytes/1024).toFixed(1)," KB)"]})]},u.id))})]}),s.jsx("div",{style:Me.deleteSection,children:r?s.jsxs("div",{style:Me.confirmDelete,children:[s.jsx("span",{children:"Are you sure?"}),s.jsx("button",{onClick:t,style:Me.confirmYes,children:"Yes, Delete"}),s.jsx("button",{onClick:()=>i(!1),style:Me.confirmNo,children:"Cancel"})]}):s.jsx("button",{onClick:()=>i(!0),style:Me.deleteBtn,children:"Delete Entry"})})]})]})})}function Dse({entryType:n,setEntryType:e,onClose:t,onSuccess:r}){const{token:i}=gn(),[o,a]=k.useState(new Date().toISOString().split("T")[0]),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState("spoiled"),[g,m]=k.useState("lunch"),[y,v]=k.useState(""),[x,w]=k.useState(""),[S,_]=k.useState([]),[b,C]=k.useState(""),[T,F]=k.useState([]),[A,D]=k.useState(!1),[P,L]=k.useState(null),W=async z=>{if(z.length<2){F([]);return}try{const G=await fetch(`/api/logbook/products/search?query=${encodeURIComponent(z)}`,{headers:{Authorization:`Bearer ${i}`}});if(G.ok){const te=await G.json();F(te)}}catch{}},O=z=>{const G={product_id:z==null?void 0:z.id,product_name:(z==null?void 0:z.name)||"",product_code:(z==null?void 0:z.product_code)||void 0,supplier_name:(z==null?void 0:z.supplier_name)||void 0,quantity:1,unit:(z==null?void 0:z.unit)||void 0,unit_price:(z==null?void 0:z.last_price)||void 0,total_cost:(z==null?void 0:z.last_price)||0};_([...S,G]),C(""),F([])},U=(z,G,te)=>{const re=[...S];if(re[z]={...re[z],[G]:te},G==="quantity"||G==="unit_price"){const me=G==="quantity"?te:re[z].quantity,J=G==="unit_price"?te:re[z].unit_price;re[z].total_cost=(me||0)*(J||0)}_(re)},M=z=>{_(S.filter((G,te)=>te!==z))},I=()=>S.reduce((z,G)=>z+(G.total_cost||0),0),H=async()=>{if(S.length===0){L("Please add at least one item");return}D(!0),L(null);try{let z="/api/logbook/",G={entry_date:o,notes:l||void 0,line_items:S};switch(n){case"wastage":z+="wastage",G.reason=f,G.reference_number=c||void 0;break;case"transfer":z+="transfer",G.destination_kitchen_id=1,G.reference_number=c||void 0;break;case"staff_food":z+="staff-food",G.meal_type=g,G.staff_count=y||void 0;break;case"manual_adjustment":z+="manual-adjustment",G.adjustment_reason=x,G.reference_number=c||void 0;break}const te=await fetch(z,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify(G)});if(!te.ok){const re=await te.json();throw new Error(re.detail||"Failed to create entry")}r()}catch(z){L(z instanceof Error?z.message:"Failed to create entry")}finally{D(!1)}};return s.jsx("div",{style:Me.modalOverlay,onClick:t,children:s.jsxs("div",{style:{...Me.modal,maxWidth:"1000px"},onClick:z=>z.stopPropagation(),children:[s.jsxs("div",{style:Me.modalHeader,children:[s.jsx("h3",{style:Me.modalTitle,children:"New Logbook Entry"}),s.jsx("button",{onClick:t,style:Me.closeBtn,children:"×"})]}),s.jsxs("div",{style:Me.modalBody,children:[P&&s.jsx("div",{style:Me.errorMsg,children:P}),s.jsx("div",{style:Me.typeSelector,children:Object.entries($6).map(([z,G])=>s.jsx("button",{onClick:()=>e(z),style:{...Me.typeBtn,background:n===z?ZA[z]:"#f0f0f0",color:n===z?"white":"#333"},children:G},z))}),s.jsxs("div",{style:Me.topFieldsRow,children:[s.jsxs("div",{style:Me.leftFieldsColumn,children:[s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Date"}),s.jsx("input",{type:"date",value:o,onChange:z=>a(z.target.value),style:Me.input})]}),n==="wastage"&&s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Wastage Reason"}),s.jsx("select",{value:f,onChange:z=>p(z.target.value),style:Me.input,children:Cse.map(z=>s.jsx("option",{value:z.value,children:z.label},z.value))})]}),n==="transfer"&&s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Reference Number"}),s.jsx("input",{type:"text",value:c,onChange:z=>u(z.target.value),style:Me.input,placeholder:"Optional"})]}),n==="staff_food"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Meal Type"}),s.jsx("select",{value:g,onChange:z=>m(z.target.value),style:Me.input,children:Ase.map(z=>s.jsx("option",{value:z.value,children:z.label},z.value))})]}),s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Staff Count"}),s.jsx("input",{type:"number",value:y,onChange:z=>v(z.target.value?parseInt(z.target.value):""),style:Me.input,placeholder:"Optional",min:"1"})]})]}),n==="manual_adjustment"&&s.jsxs("div",{style:Me.formGroup,children:[s.jsx("label",{style:Me.label,children:"Adjustment Reason"}),s.jsx("input",{type:"text",value:x,onChange:z=>w(z.target.value),style:Me.input,placeholder:"e.g., Stock count correction"})]})]}),s.jsx("div",{style:Me.rightFieldsColumn,children:s.jsxs("div",{style:{...Me.formGroup,flex:1,display:"flex",flexDirection:"column"},children:[s.jsx("label",{style:Me.label,children:"Notes"}),s.jsx("textarea",{value:l,onChange:z=>d(z.target.value),style:{...Me.input,flex:1,minHeight:"100px",resize:"vertical"},placeholder:"Optional notes..."})]})})]}),s.jsxs("div",{style:Me.lineItemsSection,children:[s.jsxs("h4",{style:Me.sectionTitle,children:["Wastage Items (",S.length,")"]}),s.jsx("div",{style:Me.lineItemsTableContainer,children:s.jsxs("table",{style:Me.lineItemsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Me.th,children:"Product"}),s.jsx("th",{style:{...Me.th,width:"80px"},children:"Qty"}),s.jsx("th",{style:{...Me.th,width:"100px"},children:"Unit Price"}),s.jsx("th",{style:{...Me.th,width:"100px"},children:"Total"}),s.jsx("th",{style:{...Me.th,width:"40px"}})]})}),s.jsx("tbody",{children:S.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{...Me.td,textAlign:"center",color:"#999",padding:"1.5rem"},children:"No items added yet. Search below or add manually."})}):S.map((z,G)=>s.jsxs("tr",{children:[s.jsxs("td",{style:Me.td,children:[s.jsx("input",{type:"text",value:z.product_name,onChange:te=>U(G,"product_name",te.target.value),style:Me.tableInput,placeholder:"Product name"}),z.supplier_name&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#3498db",marginTop:"2px"},children:z.supplier_name})]}),s.jsx("td",{style:Me.td,children:s.jsx("input",{type:"number",value:z.quantity,onChange:te=>U(G,"quantity",parseFloat(te.target.value)||0),style:Me.tableInput,min:"0",step:"0.01"})}),s.jsx("td",{style:Me.td,children:s.jsx("input",{type:"number",value:z.unit_price||"",onChange:te=>U(G,"unit_price",te.target.value?parseFloat(te.target.value):void 0),style:Me.tableInput,min:"0",step:"0.01",placeholder:"£0.00"})}),s.jsx("td",{style:Me.td,children:s.jsx("input",{type:"number",value:z.total_cost,onChange:te=>U(G,"total_cost",parseFloat(te.target.value)||0),style:Me.tableInput,min:"0",step:"0.01"})}),s.jsx("td",{style:Me.td,children:s.jsx("button",{onClick:()=>M(G),style:Me.removeItemBtn,children:"×"})})]},G))}),S.length>0&&s.jsx("tfoot",{children:s.jsxs("tr",{children:[s.jsx("td",{colSpan:3,style:{...Me.td,fontWeight:"bold",textAlign:"right"},children:"Total:"}),s.jsxs("td",{style:{...Me.td,fontWeight:"bold"},children:["£",I().toFixed(2)]}),s.jsx("td",{})]})})]})}),s.jsx("button",{onClick:()=>O(),style:Me.manualAddBtn,children:"+ Add Manual Item"})]}),s.jsxs("div",{style:Me.productSearchSection,children:[s.jsx("h4",{style:Me.sectionTitle,children:"Search Products"}),s.jsx("input",{type:"text",value:b,onChange:z=>{C(z.target.value),W(z.target.value)},style:{...Me.input,marginBottom:"0.5rem"},placeholder:"Search by product name or code..."}),s.jsx("div",{style:Me.productSearchResultsContainer,children:b.length<2?s.jsx("div",{style:Me.searchPlaceholder,children:"Type at least 2 characters to search products..."}):T.length===0?s.jsxs("div",{style:Me.searchPlaceholder,children:['No products found matching "',b,'"']}):s.jsxs("table",{style:Me.searchResultsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Me.searchTh,children:"Supplier"}),s.jsx("th",{style:Me.searchTh,children:"Description"}),s.jsx("th",{style:{...Me.searchTh,width:"80px"},children:"Unit"}),s.jsx("th",{style:{...Me.searchTh,width:"80px"},children:"Price"}),s.jsx("th",{style:{...Me.searchTh,width:"60px"}})]})}),s.jsx("tbody",{children:T.map((z,G)=>s.jsxs("tr",{style:Me.searchResultRow,children:[s.jsx("td",{style:Me.searchTd,children:z.supplier_name||"-"}),s.jsxs("td",{style:Me.searchTd,children:[z.name,z.product_code&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#999",marginLeft:"0.5rem"},children:["(",z.product_code,")"]})]}),s.jsx("td",{style:Me.searchTd,children:z.unit||"-"}),s.jsx("td",{style:Me.searchTd,children:z.last_price!=null?`£${z.last_price.toFixed(2)}`:"-"}),s.jsx("td",{style:Me.searchTd,children:s.jsx("button",{onClick:()=>O(z),style:Me.addFromSearchBtn,children:"Add"})})]},`${G}-${z.name}-${z.product_code||""}`))})]})})]}),s.jsxs("div",{style:Me.submitRow,children:[s.jsx("button",{onClick:t,style:Me.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:H,style:Me.submitBtn,disabled:A||S.length===0,children:A?"Creating...":"Create Entry"})]})]})]})})}const Me={loading:{padding:"2rem",textAlign:"center",color:"#666"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},createBtn:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontWeight:"bold",cursor:"pointer"},summaryGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1.5rem"},summaryCard:{background:"white",padding:"1rem",borderRadius:"8px",textAlign:"center",boxShadow:"0 2px 4px rgba(0,0,0,0.05)"},summaryValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#1a1a2e"},summaryLabel:{fontSize:"0.85rem",color:"#666",marginTop:"0.25rem"},filters:{display:"flex",gap:"1rem",marginBottom:"1.5rem",flexWrap:"wrap"},filterSelect:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",minWidth:"150px"},filterInput:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem"},clearBtn:{padding:"0.5rem 1rem",borderRadius:"8px",border:"none",background:"#666",color:"white",cursor:"pointer",fontWeight:"bold"},empty:{padding:"3rem",textAlign:"center",color:"#666",background:"white",borderRadius:"12px"},link:{display:"inline-block",marginTop:"1rem",padding:"0.75rem 1.5rem",background:"transparent",color:"#e94560",border:"2px solid #e94560",borderRadius:"8px",textDecoration:"none",fontWeight:"bold",cursor:"pointer"},list:{display:"flex",flexDirection:"column",gap:"1rem"},card:{display:"flex",padding:"1rem",background:"white",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",cursor:"pointer",gap:"1rem"},cardLeft:{display:"flex",alignItems:"flex-start"},typeBadge:{padding:"0.35rem 0.75rem",borderRadius:"6px",fontSize:"0.75rem",fontWeight:"bold",color:"white",textTransform:"uppercase",whiteSpace:"nowrap"},cardMain:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},cardDate:{fontSize:"1rem",fontWeight:"bold",color:"#1a1a2e",display:"flex",alignItems:"center",gap:"0.75rem"},refNumber:{fontSize:"0.8rem",color:"#666",fontWeight:"normal"},cardInfo:{fontSize:"0.9rem",color:"#666"},cardItems:{display:"flex",gap:"0.5rem",flexWrap:"wrap",marginTop:"0.25rem"},itemPill:{padding:"0.2rem 0.5rem",background:"#f0f0f0",borderRadius:"4px",fontSize:"0.8rem",color:"#666"},moreItems:{fontSize:"0.8rem",color:"#999"},cardNotes:{fontSize:"0.85rem",color:"#888",fontStyle:"italic",marginTop:"0.25rem"},cardRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"0.25rem"},amount:{fontSize:"1.25rem",fontWeight:"bold",color:"#e94560"},cardMeta:{fontSize:"0.8rem",color:"#999"},attachmentBadge:{fontSize:"0.75rem",color:"#3498db"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",maxWidth:"700px",width:"95%",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)",display:"flex",flexDirection:"column"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},modalTitle:{margin:0,color:"#1a1a2e",display:"flex",alignItems:"center"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},modalBody:{padding:"1.5rem",overflowY:"auto",flex:1},detailGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1rem",padding:"1rem",background:"#f8f8f8",borderRadius:"8px"},detailItem:{display:"flex",flexDirection:"column"},detailLabel:{fontSize:"0.75rem",color:"#666",textTransform:"uppercase"},detailValue:{fontSize:"1rem",fontWeight:"bold",color:"#1a1a2e"},typeInfo:{padding:"0.75rem 1rem",background:"#f0f0f0",borderRadius:"8px",marginBottom:"1rem"},notesSection:{marginBottom:"1rem"},notesText:{margin:"0.5rem 0 0 0",padding:"0.75rem",background:"#fafafa",borderRadius:"8px",fontStyle:"italic",color:"#666"},lineItemsSection:{marginTop:"1.5rem"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1.1rem"},lineItemsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{padding:"0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",background:"#f8f8f8"},td:{padding:"0.75rem",borderBottom:"1px solid #eee",verticalAlign:"top"},productCode:{fontSize:"0.75rem",color:"#999"},supplierName:{fontSize:"0.75rem",color:"#3498db"},attachmentsSection:{marginTop:"1.5rem"},attachmentsList:{display:"flex",flexDirection:"column",gap:"0.5rem"},attachmentItem:{padding:"0.5rem 0.75rem",background:"#f8f8f8",borderRadius:"4px",display:"flex",justifyContent:"space-between",alignItems:"center"},attachmentSize:{fontSize:"0.8rem",color:"#999"},deleteSection:{marginTop:"2rem",paddingTop:"1rem",borderTop:"1px solid #eee"},deleteBtn:{padding:"0.75rem 1.5rem",background:"#dc3545",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold"},confirmDelete:{display:"flex",alignItems:"center",gap:"1rem"},confirmYes:{padding:"0.5rem 1rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},confirmNo:{padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},errorMsg:{padding:"1rem",background:"#fee",color:"#c00",borderRadius:"8px",marginBottom:"1rem"},typeSelector:{display:"flex",gap:"0.5rem",marginBottom:"1.5rem",flexWrap:"wrap"},typeBtn:{padding:"0.5rem 1rem",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold",transition:"all 0.2s"},formGroup:{flex:1,display:"flex",flexDirection:"column",marginBottom:"1rem"},topFieldsRow:{display:"flex",gap:"1.5rem",marginBottom:"1.5rem"},leftFieldsColumn:{flex:"0 0 50%",display:"flex",flexDirection:"column"},rightFieldsColumn:{flex:"0 0 50%",display:"flex",flexDirection:"column"},lineItemsTableContainer:{maxHeight:"250px",overflowY:"auto",border:"1px solid #ddd",borderRadius:"8px"},manualAddBtn:{marginTop:"0.75rem",padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},productSearchSection:{marginTop:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px",border:"1px solid #e9ecef"},productSearchResultsContainer:{height:"200px",overflowY:"auto",background:"white",border:"1px solid #ddd",borderRadius:"8px"},searchPlaceholder:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:"#999",fontSize:"0.9rem"},searchResultsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},searchTh:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #ddd",background:"#f8f8f8",position:"sticky",top:0,fontSize:"0.8rem"},searchTd:{padding:"0.5rem 0.75rem",borderBottom:"1px solid #eee",verticalAlign:"middle"},searchResultRow:{cursor:"pointer"},addFromSearchBtn:{padding:"0.35rem 0.75rem",background:"#27ae60",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",fontSize:"0.8rem"},label:{fontSize:"0.85rem",fontWeight:"bold",color:"#333",marginBottom:"0.5rem"},input:{padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem"},tableInput:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.9rem"},removeItemBtn:{width:"24px",height:"24px",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",fontSize:"1rem",lineHeight:1},submitRow:{display:"flex",justifyContent:"flex-end",gap:"1rem",marginTop:"1.5rem",paddingTop:"1rem",borderTop:"1px solid #eee"},cancelBtn:{padding:"0.75rem 1.5rem",background:"#6c757d",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold"},submitBtn:{padding:"0.75rem 1.5rem",background:"#27ae60",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold"}};/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var CB=function(n,e){return CB=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)r.hasOwnProperty(i)&&(t[i]=r[i])},CB(n,e)};function xt(n,e){CB(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var wn=function(){return wn=Object.assign||function(e){for(var t,r=1,i=arguments.length;r0&&o[o.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]>2],e+=Vx[(n[r]&3)<<4|n[r+1]>>4],e+=Vx[(n[r+1]&15)<<2|n[r+2]>>6],e+=Vx[n[r+2]&63];return t%3===2?e=e.substring(0,e.length-1)+"=":t%3===1&&(e=e.substring(0,e.length-2)+"=="),e},UL=function(n){var e=n.length*.75,t=n.length,r,i=0,o,a,l,d;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var c=new Uint8Array(e);for(r=0;r>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|d&63;return c},Rse=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,Bse=function(n){var e=n.trim(),t=e.substring(0,100),r=t.match(Rse);if(!r)return UL(e);var i=r[0],o=e.substring(i.length);return UL(o)},mn=function(n){return n.charCodeAt(0)},Ise=function(n){return n.codePointAt(0)},Z_=function(n,e){return _c(n.toString(16),e,"0").toUpperCase()},RF=function(n){return Z_(n,2)},gf=function(n){return String.fromCharCode(n)},Mse=function(n){return gf(parseInt(n,16))},_c=function(n,e,t){for(var r="",i=0,o=e-n.length;i=55296&&t<=56319&&n.length>i&&(r=n.charCodeAt(i),r>=56320&&r<=57343&&(o=2)),[n.slice(e,e+o),o]},Lse=function(n){for(var e=[],t=0,r=n.length;tt&&c(),a+=p,l+=g}}return c(),d},Use=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,hH=function(n){var e=n.match(Use);if(e){var t=e[1],r=e[2],i=r===void 0?"01":r,o=e[3],a=o===void 0?"01":o,l=e[4],d=l===void 0?"00":l,c=e[5],u=c===void 0?"00":c,f=e[6],p=f===void 0?"00":f,g=e[7],m=g===void 0?"Z":g,y=e[8],v=y===void 0?"00":y,x=e[9],w=x===void 0?"00":x,S=m==="Z"?"Z":""+m+v+":"+w,_=new Date(t+"-"+i+"-"+a+"T"+d+":"+u+":"+p+S);return _}},Z6=function(n,e){for(var t,r=0,i;r=0&&n<=65535},Jse=function(n){return n>=65536&&n<=1114111},pH=function(n){return Math.floor((n-65536)/1024)+55296},gH=function(n){return(n-65536)%1024+56320},Dg;(function(n){n.BigEndian="BigEndian",n.LittleEndian="LittleEndian"})(Dg||(Dg={}));var Mw="�".codePointAt(0),mH=function(n,e){if(e===void 0&&(e=!0),n.length<=1)return String.fromCodePoint(Mw);for(var t=e?toe(n):Dg.BigEndian,r=e?2:0,i=[];n.length-r>=2;){var o=qL(n[r++],n[r++],t);if(eoe(o))if(n.length-r<2)i.push(Mw);else{var a=qL(n[r++],n[r++],t);HL(a)?i.push(o,a):i.push(Mw)}else HL(o)?(r+=2,i.push(Mw)):i.push(o)}return r=55296&&n<=56319},HL=function(n){return n>=56320&&n<=57343},qL=function(n,e,t){if(t===Dg.LittleEndian)return e<<8|n;if(t===Dg.BigEndian)return n<<8|e;throw new Error("Invalid byteOrder: "+t)},toe=function(n){return yH(n)?Dg.BigEndian:xH(n)?Dg.LittleEndian:Dg.BigEndian},yH=function(n){return n[0]===254&&n[1]===255},xH=function(n){return n[0]===255&&n[1]===254},bH=function(n){return yH(n)||xH(n)},noe=function(n){var e=String(n);if(Math.abs(n)<1){var t=parseInt(n.toString().split("e-")[1]);if(t){var r=n<0;r&&(n*=-1),n*=Math.pow(10,t-1),e="0."+new Array(t).join("0")+n.toString().substring(2),r&&(e="-"+e)}}else{var t=parseInt(n.toString().split("+")[1]);t>20&&(t-=20,n/=Math.pow(10,t),e=n.toString()+new Array(t+1).join("0"))}return e},b5=function(n){return Math.ceil(n.toString(2).length/8)},hx=function(n){for(var e=new Uint8Array(b5(n)),t=1;t<=e.length;t++)e[t-1]=n>>(e.length-t)*8;return e},eC=function(n){throw new Error(n)},Rf={};(function(n){var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function t(o,a){return Object.prototype.hasOwnProperty.call(o,a)}n.assign=function(o){for(var a=Array.prototype.slice.call(arguments,1);a.length;){var l=a.shift();if(l){if(typeof l!="object")throw new TypeError(l+"must be non-object");for(var d in l)t(l,d)&&(o[d]=l[d])}}return o},n.shrinkBuf=function(o,a){return o.length===a?o:o.subarray?o.subarray(0,a):(o.length=a,o)};var r={arraySet:function(o,a,l,d,c){if(a.subarray&&o.subarray){o.set(a.subarray(l,l+d),c);return}for(var u=0;u=0;)n[e]=0}var ooe=0,vH=1,aoe=2,loe=3,doe=258,J6=29,nC=256,Mj=nC+1+J6,sb=30,e3=19,wH=2*Mj+1,Sm=15,bP=16,coe=7,t3=256,SH=16,jH=17,kH=18,TB=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],v5=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],uoe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],_H=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],hoe=512,wh=new Array((Mj+2)*2);w1(wh);var KS=new Array(sb*2);w1(KS);var zj=new Array(hoe);w1(zj);var Oj=new Array(doe-loe+1);w1(Oj);var n3=new Array(J6);w1(n3);var eT=new Array(sb);w1(eT);function vP(n,e,t,r,i){this.static_tree=n,this.extra_bits=e,this.extra_base=t,this.elems=r,this.max_length=i,this.has_stree=n&&n.length}var CH,AH,TH;function wP(n,e){this.dyn_tree=n,this.max_code=0,this.stat_desc=e}function FH(n){return n<256?zj[n]:zj[256+(n>>>7)]}function Lj(n,e){n.pending_buf[n.pending++]=e&255,n.pending_buf[n.pending++]=e>>>8&255}function el(n,e,t){n.bi_valid>bP-t?(n.bi_buf|=e<>bP-n.bi_valid,n.bi_valid+=t-bP):(n.bi_buf|=e<>>=1,t<<=1;while(--e>0);return t>>>1}function foe(n){n.bi_valid===16?(Lj(n,n.bi_buf),n.bi_buf=0,n.bi_valid=0):n.bi_valid>=8&&(n.pending_buf[n.pending++]=n.bi_buf&255,n.bi_buf>>=8,n.bi_valid-=8)}function poe(n,e){var t=e.dyn_tree,r=e.max_code,i=e.stat_desc.static_tree,o=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,l=e.stat_desc.extra_base,d=e.stat_desc.max_length,c,u,f,p,g,m,y=0;for(p=0;p<=Sm;p++)n.bl_count[p]=0;for(t[n.heap[n.heap_max]*2+1]=0,c=n.heap_max+1;cd&&(p=d,y++),t[u*2+1]=p,!(u>r)&&(n.bl_count[p]++,g=0,u>=l&&(g=a[u-l]),m=t[u*2],n.opt_len+=m*(p+g),o&&(n.static_len+=m*(i[u*2+1]+g)));if(y!==0){do{for(p=d-1;n.bl_count[p]===0;)p--;n.bl_count[p]--,n.bl_count[p+1]+=2,n.bl_count[d]--,y-=2}while(y>0);for(p=d;p!==0;p--)for(u=n.bl_count[p];u!==0;)f=n.heap[--c],!(f>r)&&(t[f*2+1]!==p&&(n.opt_len+=(p-t[f*2+1])*t[f*2],t[f*2+1]=p),u--)}}function EH(n,e,t){var r=new Array(Sm+1),i=0,o,a;for(o=1;o<=Sm;o++)r[o]=i=i+t[o-1]<<1;for(a=0;a<=e;a++){var l=n[a*2+1];l!==0&&(n[a*2]=DH(r[l]++,l))}}function goe(){var n,e,t,r,i,o=new Array(Sm+1);for(t=0,r=0;r>=7;r8?Lj(n,n.bi_buf):n.bi_valid>0&&(n.pending_buf[n.pending++]=n.bi_buf),n.bi_buf=0,n.bi_valid=0}function moe(n,e,t,r){RH(n),Lj(n,t),Lj(n,~t),roe.arraySet(n.pending_buf,n.window,e,t,n.pending),n.pending+=t}function KL(n,e,t,r){var i=e*2,o=t*2;return n[i]>1;a>=1;a--)SP(n,t,a);c=o;do a=n.heap[1],n.heap[1]=n.heap[n.heap_len--],SP(n,t,1),l=n.heap[1],n.heap[--n.heap_max]=a,n.heap[--n.heap_max]=l,t[c*2]=t[a*2]+t[l*2],n.depth[c]=(n.depth[a]>=n.depth[l]?n.depth[a]:n.depth[l])+1,t[a*2+1]=t[l*2+1]=c,n.heap[1]=c++,SP(n,t,1);while(n.heap_len>=2);n.heap[--n.heap_max]=n.heap[1],poe(n,e),EH(t,d,n.bl_count)}function YL(n,e,t){var r,i=-1,o,a=e[0*2+1],l=0,d=7,c=4;for(a===0&&(d=138,c=3),e[(t+1)*2+1]=65535,r=0;r<=t;r++)o=a,a=e[(r+1)*2+1],!(++l=3&&n.bl_tree[_H[e]*2+1]===0;e--);return n.opt_len+=3*(e+1)+5+5+4,e}function xoe(n,e,t,r){var i;for(el(n,e-257,5),el(n,t-1,5),el(n,r-4,4),i=0;i>>=1)if(e&1&&n.dyn_ltree[t*2]!==0)return VL;if(n.dyn_ltree[9*2]!==0||n.dyn_ltree[10*2]!==0||n.dyn_ltree[13*2]!==0)return GL;for(t=32;t0?(n.strm.data_type===soe&&(n.strm.data_type=boe(n)),FB(n,n.l_desc),FB(n,n.d_desc),a=yoe(n),i=n.opt_len+3+7>>>3,o=n.static_len+3+7>>>3,o<=i&&(i=o)):i=o=t+5,t+4<=i&&e!==-1?BH(n,e,t,r):n.strategy===ioe||o===i?(el(n,(vH<<1)+(r?1:0),3),XL(n,wh,KS)):(el(n,(aoe<<1)+(r?1:0),3),xoe(n,n.l_desc.max_code+1,n.d_desc.max_code+1,a+1),XL(n,n.dyn_ltree,n.dyn_dtree)),PH(n),r&&RH(n)}function joe(n,e,t){return n.pending_buf[n.d_buf+n.last_lit*2]=e>>>8&255,n.pending_buf[n.d_buf+n.last_lit*2+1]=e&255,n.pending_buf[n.l_buf+n.last_lit]=t&255,n.last_lit++,e===0?n.dyn_ltree[t*2]++:(n.matches++,e--,n.dyn_ltree[(Oj[t]+nC+1)*2]++,n.dyn_dtree[FH(e)*2]++),n.last_lit===n.lit_bufsize-1}v1._tr_init=voe;v1._tr_stored_block=BH;v1._tr_flush_block=Soe;v1._tr_tally=joe;v1._tr_align=woe;function koe(n,e,t,r){for(var i=n&65535|0,o=n>>>16&65535|0,a=0;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[r++]|0,o=o+i|0;while(--a);i%=65521,o%=65521}return i|o<<16|0}var IH=koe;function _oe(){for(var n,e=[],t=0;t<256;t++){n=t;for(var r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e}var Coe=_oe();function Aoe(n,e,t,r){var i=Coe,o=r+t;n^=-1;for(var a=r;a>>8^i[(n^e[a])&255];return n^-1}var MH=Aoe,r3={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},ja=Rf,Id=v1,zH=IH,$f=MH,Toe=r3,I0=0,Foe=1,Doe=3,Eg=4,ZL=5,Pu=0,JL=1,Md=-2,Eoe=-3,jP=-5,Poe=-1,Roe=1,T2=2,Boe=3,Ioe=4,Moe=0,zoe=2,BF=8,Ooe=9,Loe=15,Noe=8,Woe=29,Uoe=256,DB=Uoe+1+Woe,Hoe=30,qoe=19,Voe=2*DB+1,Goe=15,hr=3,gg=258,Dc=gg+hr+1,Koe=32,IF=42,EB=69,w5=73,S5=91,j5=103,jm=113,sS=666,Ns=1,rC=2,b0=3,S1=4,Xoe=3;function mg(n,e){return n.msg=Toe[e],e}function e4(n){return(n<<1)-(n>4?9:0)}function sp(n){for(var e=n.length;--e>=0;)n[e]=0}function Zf(n){var e=n.state,t=e.pending;t>n.avail_out&&(t=n.avail_out),t!==0&&(ja.arraySet(n.output,e.pending_buf,e.pending_out,t,n.next_out),n.next_out+=t,e.pending_out+=t,n.total_out+=t,n.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))}function Bo(n,e){Id._tr_flush_block(n,n.block_start>=0?n.block_start:-1,n.strstart-n.block_start,e),n.block_start=n.strstart,Zf(n.strm)}function Tr(n,e){n.pending_buf[n.pending++]=e}function zw(n,e){n.pending_buf[n.pending++]=e>>>8&255,n.pending_buf[n.pending++]=e&255}function Yoe(n,e,t,r){var i=n.avail_in;return i>r&&(i=r),i===0?0:(n.avail_in-=i,ja.arraySet(e,n.input,n.next_in,i,t),n.state.wrap===1?n.adler=zH(n.adler,e,i,t):n.state.wrap===2&&(n.adler=$f(n.adler,e,i,t)),n.next_in+=i,n.total_in+=i,i)}function OH(n,e){var t=n.max_chain_length,r=n.strstart,i,o,a=n.prev_length,l=n.nice_match,d=n.strstart>n.w_size-Dc?n.strstart-(n.w_size-Dc):0,c=n.window,u=n.w_mask,f=n.prev,p=n.strstart+gg,g=c[r+a-1],m=c[r+a];n.prev_length>=n.good_match&&(t>>=2),l>n.lookahead&&(l=n.lookahead);do if(i=e,!(c[i+a]!==m||c[i+a-1]!==g||c[i]!==c[r]||c[++i]!==c[r+1])){r+=2,i++;do;while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&ra){if(n.match_start=e,a=o,o>=l)break;g=c[r+a-1],m=c[r+a]}}while((e=f[e&u])>d&&--t!==0);return a<=n.lookahead?a:n.lookahead}function v0(n){var e=n.w_size,t,r,i,o,a;do{if(o=n.window_size-n.lookahead-n.strstart,n.strstart>=e+(e-Dc)){ja.arraySet(n.window,n.window,e,e,0),n.match_start-=e,n.strstart-=e,n.block_start-=e,r=n.hash_size,t=r;do i=n.head[--t],n.head[t]=i>=e?i-e:0;while(--r);r=e,t=r;do i=n.prev[--t],n.prev[t]=i>=e?i-e:0;while(--r);o+=e}if(n.strm.avail_in===0)break;if(r=Yoe(n.strm,n.window,n.strstart+n.lookahead,o),n.lookahead+=r,n.lookahead+n.insert>=hr)for(a=n.strstart-n.insert,n.ins_h=n.window[a],n.ins_h=(n.ins_h<n.pending_buf_size-5&&(t=n.pending_buf_size-5);;){if(n.lookahead<=1){if(v0(n),n.lookahead===0&&e===I0)return Ns;if(n.lookahead===0)break}n.strstart+=n.lookahead,n.lookahead=0;var r=n.block_start+t;if((n.strstart===0||n.strstart>=r)&&(n.lookahead=n.strstart-r,n.strstart=r,Bo(n,!1),n.strm.avail_out===0)||n.strstart-n.block_start>=n.w_size-Dc&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=0,e===Eg?(Bo(n,!0),n.strm.avail_out===0?b0:S1):(n.strstart>n.block_start&&(Bo(n,!1),n.strm.avail_out===0),Ns)}function kP(n,e){for(var t,r;;){if(n.lookahead=hr&&(n.ins_h=(n.ins_h<=hr)if(r=Id._tr_tally(n,n.strstart-n.match_start,n.match_length-hr),n.lookahead-=n.match_length,n.match_length<=n.max_lazy_match&&n.lookahead>=hr){n.match_length--;do n.strstart++,n.ins_h=(n.ins_h<=hr&&(n.ins_h=(n.ins_h<4096)&&(n.match_length=hr-1)),n.prev_length>=hr&&n.match_length<=n.prev_length){i=n.strstart+n.lookahead-hr,r=Id._tr_tally(n,n.strstart-1-n.prev_match,n.prev_length-hr),n.lookahead-=n.prev_length-1,n.prev_length-=2;do++n.strstart<=i&&(n.ins_h=(n.ins_h<=hr&&n.strstart>0&&(i=n.strstart-1,r=a[i],r===a[++i]&&r===a[++i]&&r===a[++i])){o=n.strstart+gg;do;while(r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&r===a[++i]&&in.lookahead&&(n.match_length=n.lookahead)}if(n.match_length>=hr?(t=Id._tr_tally(n,1,n.match_length-hr),n.lookahead-=n.match_length,n.strstart+=n.match_length,n.match_length=0):(t=Id._tr_tally(n,0,n.window[n.strstart]),n.lookahead--,n.strstart++),t&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=0,e===Eg?(Bo(n,!0),n.strm.avail_out===0?b0:S1):n.last_lit&&(Bo(n,!1),n.strm.avail_out===0)?Ns:rC}function Zoe(n,e){for(var t;;){if(n.lookahead===0&&(v0(n),n.lookahead===0)){if(e===I0)return Ns;break}if(n.match_length=0,t=Id._tr_tally(n,0,n.window[n.strstart]),n.lookahead--,n.strstart++,t&&(Bo(n,!1),n.strm.avail_out===0))return Ns}return n.insert=0,e===Eg?(Bo(n,!0),n.strm.avail_out===0?b0:S1):n.last_lit&&(Bo(n,!1),n.strm.avail_out===0)?Ns:rC}function qc(n,e,t,r,i){this.good_length=n,this.max_lazy=e,this.nice_length=t,this.max_chain=r,this.func=i}var Gx;Gx=[new qc(0,0,0,0,Qoe),new qc(4,4,8,4,kP),new qc(4,5,16,8,kP),new qc(4,6,32,32,kP),new qc(4,4,16,16,fx),new qc(8,16,32,32,fx),new qc(8,16,128,128,fx),new qc(8,32,128,256,fx),new qc(32,128,258,1024,fx),new qc(32,258,258,4096,fx)];function Joe(n){n.window_size=2*n.w_size,sp(n.head),n.max_lazy_match=Gx[n.level].max_lazy,n.good_match=Gx[n.level].good_length,n.nice_match=Gx[n.level].nice_length,n.max_chain_length=Gx[n.level].max_chain,n.strstart=0,n.block_start=0,n.lookahead=0,n.insert=0,n.match_length=n.prev_length=hr-1,n.match_available=0,n.ins_h=0}function eae(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=BF,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new ja.Buf16(Voe*2),this.dyn_dtree=new ja.Buf16((2*Hoe+1)*2),this.bl_tree=new ja.Buf16((2*qoe+1)*2),sp(this.dyn_ltree),sp(this.dyn_dtree),sp(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new ja.Buf16(Goe+1),this.heap=new ja.Buf16(2*DB+1),sp(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new ja.Buf16(2*DB+1),sp(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function LH(n){var e;return!n||!n.state?mg(n,Md):(n.total_in=n.total_out=0,n.data_type=zoe,e=n.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?IF:jm,n.adler=e.wrap===2?0:1,e.last_flush=I0,Id._tr_init(e),Pu)}function NH(n){var e=LH(n);return e===Pu&&Joe(n.state),e}function tae(n,e){return!n||!n.state||n.state.wrap!==2?Md:(n.state.gzhead=e,Pu)}function WH(n,e,t,r,i,o){if(!n)return Md;var a=1;if(e===Poe&&(e=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),i<1||i>Ooe||t!==BF||r<8||r>15||e<0||e>9||o<0||o>Ioe)return mg(n,Md);r===8&&(r=9);var l=new eae;return n.state=l,l.strm=n,l.wrap=a,l.gzhead=null,l.w_bits=r,l.w_size=1<ZL||e<0)return n?mg(n,Md):Md;if(r=n.state,!n.output||!n.input&&n.avail_in!==0||r.status===sS&&e!==Eg)return mg(n,n.avail_out===0?jP:Md);if(r.strm=n,t=r.last_flush,r.last_flush=e,r.status===IF)if(r.wrap===2)n.adler=0,Tr(r,31),Tr(r,139),Tr(r,8),r.gzhead?(Tr(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),Tr(r,r.gzhead.time&255),Tr(r,r.gzhead.time>>8&255),Tr(r,r.gzhead.time>>16&255),Tr(r,r.gzhead.time>>24&255),Tr(r,r.level===9?2:r.strategy>=T2||r.level<2?4:0),Tr(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Tr(r,r.gzhead.extra.length&255),Tr(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(n.adler=$f(n.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=EB):(Tr(r,0),Tr(r,0),Tr(r,0),Tr(r,0),Tr(r,0),Tr(r,r.level===9?2:r.strategy>=T2||r.level<2?4:0),Tr(r,Xoe),r.status=jm);else{var a=BF+(r.w_bits-8<<4)<<8,l=-1;r.strategy>=T2||r.level<2?l=0:r.level<6?l=1:r.level===6?l=2:l=3,a|=l<<6,r.strstart!==0&&(a|=Koe),a+=31-a%31,r.status=jm,zw(r,a),r.strstart!==0&&(zw(r,n.adler>>>16),zw(r,n.adler&65535)),n.adler=1}if(r.status===EB)if(r.gzhead.extra){for(i=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),Zf(n),i=r.pending,r.pending===r.pending_buf_size));)Tr(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=w5)}else r.status=w5;if(r.status===w5)if(r.gzhead.name){i=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),Zf(n),i=r.pending,r.pending===r.pending_buf_size)){o=1;break}r.gzindexi&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),o===0&&(r.gzindex=0,r.status=S5)}else r.status=S5;if(r.status===S5)if(r.gzhead.comment){i=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>i&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),Zf(n),i=r.pending,r.pending===r.pending_buf_size)){o=1;break}r.gzindexi&&(n.adler=$f(n.adler,r.pending_buf,r.pending-i,i)),o===0&&(r.status=j5)}else r.status=j5;if(r.status===j5&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&Zf(n),r.pending+2<=r.pending_buf_size&&(Tr(r,n.adler&255),Tr(r,n.adler>>8&255),n.adler=0,r.status=jm)):r.status=jm),r.pending!==0){if(Zf(n),n.avail_out===0)return r.last_flush=-1,Pu}else if(n.avail_in===0&&e4(e)<=e4(t)&&e!==Eg)return mg(n,jP);if(r.status===sS&&n.avail_in!==0)return mg(n,jP);if(n.avail_in!==0||r.lookahead!==0||e!==I0&&r.status!==sS){var d=r.strategy===T2?Zoe(r,e):r.strategy===Boe?$oe(r,e):Gx[r.level].func(r,e);if((d===b0||d===S1)&&(r.status=sS),d===Ns||d===b0)return n.avail_out===0&&(r.last_flush=-1),Pu;if(d===rC&&(e===Foe?Id._tr_align(r):e!==ZL&&(Id._tr_stored_block(r,0,0,!1),e===Doe&&(sp(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),Zf(n),n.avail_out===0))return r.last_flush=-1,Pu}return e!==Eg?Pu:r.wrap<=0?JL:(r.wrap===2?(Tr(r,n.adler&255),Tr(r,n.adler>>8&255),Tr(r,n.adler>>16&255),Tr(r,n.adler>>24&255),Tr(r,n.total_in&255),Tr(r,n.total_in>>8&255),Tr(r,n.total_in>>16&255),Tr(r,n.total_in>>24&255)):(zw(r,n.adler>>>16),zw(r,n.adler&65535)),Zf(n),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?Pu:JL)}function iae(n){var e;return!n||!n.state?Md:(e=n.state.status,e!==IF&&e!==EB&&e!==w5&&e!==S5&&e!==j5&&e!==jm&&e!==sS?mg(n,Md):(n.state=null,e===jm?mg(n,Eoe):Pu))}function sae(n,e){var t=e.length,r,i,o,a,l,d,c,u;if(!n||!n.state||(r=n.state,a=r.wrap,a===2||a===1&&r.status!==IF||r.lookahead))return Md;for(a===1&&(n.adler=zH(n.adler,e,t,0)),r.wrap=0,t>=r.w_size&&(a===0&&(sp(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new ja.Buf8(r.w_size),ja.arraySet(u,e,t-r.w_size,r.w_size,0),e=u,t=r.w_size),l=n.avail_in,d=n.next_in,c=n.input,n.avail_in=t,n.next_in=0,n.input=e,v0(r);r.lookahead>=hr;){i=r.strstart,o=r.lookahead-(hr-1);do r.ins_h=(r.ins_h<=252?6:qf>=248?5:qf>=240?4:qf>=224?3:qf>=192?2:1;Nj[254]=Nj[254]=1;M0.string2buf=function(n){var e,t,r,i,o,a=n.length,l=0;for(i=0;i>>6,e[o++]=128|t&63):t<65536?(e[o++]=224|t>>>12,e[o++]=128|t>>>6&63,e[o++]=128|t&63):(e[o++]=240|t>>>18,e[o++]=128|t>>>12&63,e[o++]=128|t>>>6&63,e[o++]=128|t&63);return e};function qH(n,e){if(e<65534&&(n.subarray&&HH||!n.subarray&&UH))return String.fromCharCode.apply(null,MF.shrinkBuf(n,e));for(var t="",r=0;r4){l[r++]=65533,t+=o-1;continue}for(i&=o===2?31:o===3?15:7;o>1&&t1){l[r++]=65533;continue}i<65536?l[r++]=i:(i-=65536,l[r++]=55296|i>>10&1023,l[r++]=56320|i&1023)}return qH(l,r)};M0.utf8border=function(n,e){var t;for(e=e||n.length,e>n.length&&(e=n.length),t=e-1;t>=0&&(n[t]&192)===128;)t--;return t<0||t===0?e:t+Nj[n[t]]>e?t:e};function oae(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var VH=oae,XS=Hu,YS=Rf,PB=M0,RB=r3,aae=VH,GH=Object.prototype.toString,lae=0,_P=4,ob=0,t4=1,n4=2,dae=-1,cae=0,uae=8;function w0(n){if(!(this instanceof w0))return new w0(n);this.options=YS.assign({level:dae,method:uae,chunkSize:16384,windowBits:15,memLevel:8,strategy:cae,to:""},n||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new aae,this.strm.avail_out=0;var t=XS.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==ob)throw new Error(RB[t]);if(e.header&&XS.deflateSetHeader(this.strm,e.header),e.dictionary){var r;if(typeof e.dictionary=="string"?r=PB.string2buf(e.dictionary):GH.call(e.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(e.dictionary):r=e.dictionary,t=XS.deflateSetDictionary(this.strm,r),t!==ob)throw new Error(RB[t]);this._dict_set=!0}}w0.prototype.push=function(n,e){var t=this.strm,r=this.options.chunkSize,i,o;if(this.ended)return!1;o=e===~~e?e:e===!0?_P:lae,typeof n=="string"?t.input=PB.string2buf(n):GH.call(n)==="[object ArrayBuffer]"?t.input=new Uint8Array(n):t.input=n,t.next_in=0,t.avail_in=t.input.length;do{if(t.avail_out===0&&(t.output=new YS.Buf8(r),t.next_out=0,t.avail_out=r),i=XS.deflate(t,o),i!==t4&&i!==ob)return this.onEnd(i),this.ended=!0,!1;(t.avail_out===0||t.avail_in===0&&(o===_P||o===n4))&&(this.options.to==="string"?this.onData(PB.buf2binstring(YS.shrinkBuf(t.output,t.next_out))):this.onData(YS.shrinkBuf(t.output,t.next_out)))}while((t.avail_in>0||t.avail_out===0)&&i!==t4);return o===_P?(i=XS.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===ob):(o===n4&&(this.onEnd(ob),t.avail_out=0),!0)};w0.prototype.onData=function(n){this.chunks.push(n)};w0.prototype.onEnd=function(n){n===ob&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=YS.flattenChunks(this.chunks)),this.chunks=[],this.err=n,this.msg=this.strm.msg};function i3(n,e){var t=new w0(e);if(t.push(n,!0),t.err)throw t.msg||RB[t.err];return t.result}function hae(n,e){return e=e||{},e.raw=!0,i3(n,e)}function fae(n,e){return e=e||{},e.gzip=!0,i3(n,e)}tC.Deflate=w0;tC.deflate=i3;tC.deflateRaw=hae;tC.gzip=fae;var iC={},Rc={},F2=30,pae=12,gae=function(e,t){var r,i,o,a,l,d,c,u,f,p,g,m,y,v,x,w,S,_,b,C,T,F,A,D,P;r=e.state,i=e.next_in,D=e.input,o=i+(e.avail_in-5),a=e.next_out,P=e.output,l=a-(t-e.avail_out),d=a+(e.avail_out-257),c=r.dmax,u=r.wsize,f=r.whave,p=r.wnext,g=r.window,m=r.hold,y=r.bits,v=r.lencode,x=r.distcode,w=(1<>>24,m>>>=b,y-=b,b=_>>>16&255,b===0)P[a++]=_&65535;else if(b&16){C=_&65535,b&=15,b&&(y>>=b,y-=b),y<15&&(m+=D[i++]<>>24,m>>>=b,y-=b,b=_>>>16&255,b&16){if(T=_&65535,b&=15,yc){e.msg="invalid distance too far back",r.mode=F2;break e}if(m>>>=b,y-=b,b=a-l,T>b){if(b=T-b,b>f&&r.sane){e.msg="invalid distance too far back",r.mode=F2;break e}if(F=0,A=g,p===0){if(F+=u-b,b2;)P[a++]=A[F++],P[a++]=A[F++],P[a++]=A[F++],C-=3;C&&(P[a++]=A[F++],C>1&&(P[a++]=A[F++]))}else{F=a-T;do P[a++]=P[F++],P[a++]=P[F++],P[a++]=P[F++],C-=3;while(C>2);C&&(P[a++]=P[F++],C>1&&(P[a++]=P[F++]))}}else if(b&64){e.msg="invalid distance code",r.mode=F2;break e}else{_=x[(_&65535)+(m&(1<>3,i-=C,y-=C<<3,m&=(1<=1&&L[g]===0;g--);if(m>g&&(m=g),g===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,d.bits=1,0;for(p=1;p0&&(e===o4||g!==1))return-1;for(W[1]=0,u=1;ui4||e===a4&&w>s4)return 1;for(;;){M=u-v,l[f]P?(I=O[U+l[f]],H=A[D+l[f]]):(I=96,H=0),_=1<>v)+b]=M<<24|I<<16|H|0;while(b!==0);for(_=1<>=1;if(_!==0?(S&=_-1,S+=_):S=0,f++,--L[u]===0){if(u===g)break;u=t[r+l[f]]}if(u>m&&(S&T)!==C){for(v===0&&(v=m),F+=p,y=u-v,x=1<i4||e===a4&&w>s4)return 1;C=S&T,o[C]=m<<24|y<<16|F-a|0}}return S!==0&&(o[F+S]=u-v<<24|64<<16|0),d.bits=m,0},Ul=Rf,BB=IH,Vc=MH,wae=gae,QS=vae,Sae=0,KH=1,XH=2,l4=4,jae=5,D2=6,S0=0,kae=1,_ae=2,Nd=-2,YH=-3,QH=-4,Cae=-5,d4=8,$H=1,c4=2,u4=3,h4=4,f4=5,p4=6,g4=7,m4=8,y4=9,x4=10,tT=11,sh=12,AP=13,b4=14,TP=15,v4=16,w4=17,S4=18,j4=19,E2=20,P2=21,k4=22,_4=23,C4=24,A4=25,T4=26,FP=27,F4=28,D4=29,Di=30,ZH=31,Aae=32,Tae=852,Fae=592,Dae=15,Eae=Dae;function E4(n){return(n>>>24&255)+(n>>>8&65280)+((n&65280)<<8)+((n&255)<<24)}function Pae(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Ul.Buf16(320),this.work=new Ul.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function JH(n){var e;return!n||!n.state?Nd:(e=n.state,n.total_in=n.total_out=e.total=0,n.msg="",e.wrap&&(n.adler=e.wrap&1),e.mode=$H,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Ul.Buf32(Tae),e.distcode=e.distdyn=new Ul.Buf32(Fae),e.sane=1,e.back=-1,S0)}function eq(n){var e;return!n||!n.state?Nd:(e=n.state,e.wsize=0,e.whave=0,e.wnext=0,JH(n))}function tq(n,e){var t,r;return!n||!n.state||(r=n.state,e<0?(t=0,e=-e):(t=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?Nd:(r.window!==null&&r.wbits!==e&&(r.window=null),r.wrap=t,r.wbits=e,eq(n))}function nq(n,e){var t,r;return n?(r=new Pae,n.state=r,r.window=null,t=tq(n,e),t!==S0&&(n.state=null),t):Nd}function Rae(n){return nq(n,Eae)}var P4=!0,DP,EP;function Bae(n){if(P4){var e;for(DP=new Ul.Buf32(512),EP=new Ul.Buf32(32),e=0;e<144;)n.lens[e++]=8;for(;e<256;)n.lens[e++]=9;for(;e<280;)n.lens[e++]=7;for(;e<288;)n.lens[e++]=8;for(QS(KH,n.lens,0,288,DP,0,n.work,{bits:9}),e=0;e<32;)n.lens[e++]=5;QS(XH,n.lens,0,32,EP,0,n.work,{bits:5}),P4=!1}n.lencode=DP,n.lenbits=9,n.distcode=EP,n.distbits=5}function rq(n,e,t,r){var i,o=n.state;return o.window===null&&(o.wsize=1<=o.wsize?(Ul.arraySet(o.window,e,t-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>r&&(i=r),Ul.arraySet(o.window,e,t-r,i,o.wnext),r-=i,r?(Ul.arraySet(o.window,e,t-r,r,0),o.wnext=r,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave>>8&255,t.check=Vc(t.check,A,2,0),c=0,u=0,t.mode=c4;break}if(t.flags=0,t.head&&(t.head.done=!1),!(t.wrap&1)||(((c&255)<<8)+(c>>8))%31){n.msg="incorrect header check",t.mode=Di;break}if((c&15)!==d4){n.msg="unknown compression method",t.mode=Di;break}if(c>>>=4,u-=4,T=(c&15)+8,t.wbits===0)t.wbits=T;else if(T>t.wbits){n.msg="invalid window size",t.mode=Di;break}t.dmax=1<>8&1),t.flags&512&&(A[0]=c&255,A[1]=c>>>8&255,t.check=Vc(t.check,A,2,0)),c=0,u=0,t.mode=u4;case u4:for(;u<32;){if(l===0)break e;l--,c+=r[o++]<>>8&255,A[2]=c>>>16&255,A[3]=c>>>24&255,t.check=Vc(t.check,A,4,0)),c=0,u=0,t.mode=h4;case h4:for(;u<16;){if(l===0)break e;l--,c+=r[o++]<>8),t.flags&512&&(A[0]=c&255,A[1]=c>>>8&255,t.check=Vc(t.check,A,2,0)),c=0,u=0,t.mode=f4;case f4:if(t.flags&1024){for(;u<16;){if(l===0)break e;l--,c+=r[o++]<>>8&255,t.check=Vc(t.check,A,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=p4;case p4:if(t.flags&1024&&(g=t.length,g>l&&(g=l),g&&(t.head&&(T=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Array(t.head.extra_len)),Ul.arraySet(t.head.extra,r,o,g,T)),t.flags&512&&(t.check=Vc(t.check,r,g,o)),l-=g,o+=g,t.length-=g),t.length))break e;t.length=0,t.mode=g4;case g4:if(t.flags&2048){if(l===0)break e;g=0;do T=r[o+g++],t.head&&T&&t.length<65536&&(t.head.name+=String.fromCharCode(T));while(T&&g>9&1,t.head.done=!0),n.adler=t.check=0,t.mode=sh;break;case x4:for(;u<32;){if(l===0)break e;l--,c+=r[o++]<>>=u&7,u-=u&7,t.mode=FP;break}for(;u<3;){if(l===0)break e;l--,c+=r[o++]<>>=1,u-=1,c&3){case 0:t.mode=b4;break;case 1:if(Bae(t),t.mode=E2,e===D2){c>>>=2,u-=2;break e}break;case 2:t.mode=w4;break;case 3:n.msg="invalid block type",t.mode=Di}c>>>=2,u-=2;break;case b4:for(c>>>=u&7,u-=u&7;u<32;){if(l===0)break e;l--,c+=r[o++]<>>16^65535)){n.msg="invalid stored block lengths",t.mode=Di;break}if(t.length=c&65535,c=0,u=0,t.mode=TP,e===D2)break e;case TP:t.mode=v4;case v4:if(g=t.length,g){if(g>l&&(g=l),g>d&&(g=d),g===0)break e;Ul.arraySet(i,r,o,g,a),l-=g,o+=g,d-=g,a+=g,t.length-=g;break}t.mode=sh;break;case w4:for(;u<14;){if(l===0)break e;l--,c+=r[o++]<>>=5,u-=5,t.ndist=(c&31)+1,c>>>=5,u-=5,t.ncode=(c&15)+4,c>>>=4,u-=4,t.nlen>286||t.ndist>30){n.msg="too many length or distance symbols",t.mode=Di;break}t.have=0,t.mode=S4;case S4:for(;t.have>>=3,u-=3}for(;t.have<19;)t.lens[L[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,D={bits:t.lenbits},F=QS(Sae,t.lens,0,19,t.lencode,0,t.work,D),t.lenbits=D.bits,F){n.msg="invalid code lengths set",t.mode=Di;break}t.have=0,t.mode=j4;case j4:for(;t.have>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<>>=x,u-=x,t.lens[t.have++]=S;else{if(S===16){for(P=x+2;u>>=x,u-=x,t.have===0){n.msg="invalid bit length repeat",t.mode=Di;break}T=t.lens[t.have-1],g=3+(c&3),c>>>=2,u-=2}else if(S===17){for(P=x+3;u>>=x,u-=x,T=0,g=3+(c&7),c>>>=3,u-=3}else{for(P=x+7;u>>=x,u-=x,T=0,g=11+(c&127),c>>>=7,u-=7}if(t.have+g>t.nlen+t.ndist){n.msg="invalid bit length repeat",t.mode=Di;break}for(;g--;)t.lens[t.have++]=T}}if(t.mode===Di)break;if(t.lens[256]===0){n.msg="invalid code -- missing end-of-block",t.mode=Di;break}if(t.lenbits=9,D={bits:t.lenbits},F=QS(KH,t.lens,0,t.nlen,t.lencode,0,t.work,D),t.lenbits=D.bits,F){n.msg="invalid literal/lengths set",t.mode=Di;break}if(t.distbits=6,t.distcode=t.distdyn,D={bits:t.distbits},F=QS(XH,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,D),t.distbits=D.bits,F){n.msg="invalid distances set",t.mode=Di;break}if(t.mode=E2,e===D2)break e;case E2:t.mode=P2;case P2:if(l>=6&&d>=258){n.next_out=a,n.avail_out=d,n.next_in=o,n.avail_in=l,t.hold=c,t.bits=u,wae(n,p),a=n.next_out,i=n.output,d=n.avail_out,o=n.next_in,r=n.input,l=n.avail_in,c=t.hold,u=t.bits,t.mode===sh&&(t.back=-1);break}for(t.back=0;v=t.lencode[c&(1<>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<>_)],x=v>>>24,w=v>>>16&255,S=v&65535,!(_+x<=u);){if(l===0)break e;l--,c+=r[o++]<>>=_,u-=_,t.back+=_}if(c>>>=x,u-=x,t.back+=x,t.length=S,w===0){t.mode=T4;break}if(w&32){t.back=-1,t.mode=sh;break}if(w&64){n.msg="invalid literal/length code",t.mode=Di;break}t.extra=w&15,t.mode=k4;case k4:if(t.extra){for(P=t.extra;u>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=_4;case _4:for(;v=t.distcode[c&(1<>>24,w=v>>>16&255,S=v&65535,!(x<=u);){if(l===0)break e;l--,c+=r[o++]<>_)],x=v>>>24,w=v>>>16&255,S=v&65535,!(_+x<=u);){if(l===0)break e;l--,c+=r[o++]<>>=_,u-=_,t.back+=_}if(c>>>=x,u-=x,t.back+=x,w&64){n.msg="invalid distance code",t.mode=Di;break}t.offset=S,t.extra=w&15,t.mode=C4;case C4:if(t.extra){for(P=t.extra;u>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){n.msg="invalid distance too far back",t.mode=Di;break}t.mode=A4;case A4:if(d===0)break e;if(g=p-d,t.offset>g){if(g=t.offset-g,g>t.whave&&t.sane){n.msg="invalid distance too far back",t.mode=Di;break}g>t.wnext?(g-=t.wnext,m=t.wsize-g):m=t.wnext-g,g>t.length&&(g=t.length),y=t.window}else y=i,m=a-t.offset,g=t.length;g>d&&(g=d),d-=g,t.length-=g;do i[a++]=y[m++];while(--g);t.length===0&&(t.mode=P2);break;case T4:if(d===0)break e;i[a++]=t.length,d--,t.mode=P2;break;case FP:if(t.wrap){for(;u<32;){if(l===0)break e;l--,c|=r[o++]<=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(n&&n.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Wae,this.strm.avail_out=0;var t=ab.inflateInit2(this.strm,e.windowBits);if(t!==ms.Z_OK)throw new Error(IB[t]);if(this.header=new Uae,ab.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=k5.string2buf(e.dictionary):sq.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=ab.inflateSetDictionary(this.strm,e.dictionary),t!==ms.Z_OK)))throw new Error(IB[t])}j0.prototype.push=function(n,e){var t=this.strm,r=this.options.chunkSize,i=this.options.dictionary,o,a,l,d,c,u=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?ms.Z_FINISH:ms.Z_NO_FLUSH,typeof n=="string"?t.input=k5.binstring2buf(n):sq.call(n)==="[object ArrayBuffer]"?t.input=new Uint8Array(n):t.input=n,t.next_in=0,t.avail_in=t.input.length;do{if(t.avail_out===0&&(t.output=new $S.Buf8(r),t.next_out=0,t.avail_out=r),o=ab.inflate(t,ms.Z_NO_FLUSH),o===ms.Z_NEED_DICT&&i&&(o=ab.inflateSetDictionary(this.strm,i)),o===ms.Z_BUF_ERROR&&u===!0&&(o=ms.Z_OK,u=!1),o!==ms.Z_STREAM_END&&o!==ms.Z_OK)return this.onEnd(o),this.ended=!0,!1;t.next_out&&(t.avail_out===0||o===ms.Z_STREAM_END||t.avail_in===0&&(a===ms.Z_FINISH||a===ms.Z_SYNC_FLUSH))&&(this.options.to==="string"?(l=k5.utf8border(t.output,t.next_out),d=t.next_out-l,c=k5.buf2string(t.output,l),t.next_out=d,t.avail_out=r-d,d&&$S.arraySet(t.output,t.output,l,d,0),this.onData(c)):this.onData($S.shrinkBuf(t.output,t.next_out))),t.avail_in===0&&t.avail_out===0&&(u=!0)}while((t.avail_in>0||t.avail_out===0)&&o!==ms.Z_STREAM_END);return o===ms.Z_STREAM_END&&(a=ms.Z_FINISH),a===ms.Z_FINISH?(o=ab.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===ms.Z_OK):(a===ms.Z_SYNC_FLUSH&&(this.onEnd(ms.Z_OK),t.avail_out=0),!0)};j0.prototype.onData=function(n){this.chunks.push(n)};j0.prototype.onEnd=function(n){n===ms.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=$S.flattenChunks(this.chunks)),this.chunks=[],this.err=n,this.msg=this.strm.msg};function s3(n,e){var t=new j0(e);if(t.push(n,!0),t.err)throw t.msg||IB[t.err];return t.result}function Hae(n,e){return e=e||{},e.raw=!0,s3(n,e)}iC.Inflate=j0;iC.inflate=s3;iC.inflateRaw=Hae;iC.ungzip=s3;var qae=Rf.assign,Vae=tC,Gae=iC,Kae=iq,oq={};qae(oq,Vae,Gae,Kae);var Xae=oq;const zF=a7(Xae);var R4="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oS=new Uint8Array(256);for(var R2=0;R2>4,c[i++]=(a&15)<<4|l>>2,c[i++]=(l&3)<<6|d&63;return c},Qae=function(n){for(var e="",t=0;tr)throw new Error(Ms(e)+" must be at least "+t+" and at most "+r+", but was actually "+n)},nc=function(n,e,t,r){Ie(n,e,["number","undefined"]),typeof n=="number"&&Hl(n,e,t,r)},dq=function(n,e,t){if(Ie(n,e,["number"]),n%t!==0)throw new Error(Ms(e)+" must be a multiple of "+t+", but was actually "+n)},jle=function(n,e){if(!Number.isInteger(n))throw new Error(Ms(e)+" must be an integer, but was actually "+n)},LF=function(n,e){if(![1,0].includes(Math.sign(n)))throw new Error(Ms(e)+" must be a positive number or 0, but was actually "+n)},Sn=new Uint16Array(256);for(var M2=0;M2<256;M2++)Sn[M2]=M2;Sn[22]=mn("");Sn[24]=mn("˘");Sn[25]=mn("ˇ");Sn[26]=mn("ˆ");Sn[27]=mn("˙");Sn[28]=mn("˝");Sn[29]=mn("˛");Sn[30]=mn("˚");Sn[31]=mn("˜");Sn[127]=mn("�");Sn[128]=mn("•");Sn[129]=mn("†");Sn[130]=mn("‡");Sn[131]=mn("…");Sn[132]=mn("—");Sn[133]=mn("–");Sn[134]=mn("ƒ");Sn[135]=mn("⁄");Sn[136]=mn("‹");Sn[137]=mn("›");Sn[138]=mn("−");Sn[139]=mn("‰");Sn[140]=mn("„");Sn[141]=mn("“");Sn[142]=mn("”");Sn[143]=mn("‘");Sn[144]=mn("’");Sn[145]=mn("‚");Sn[146]=mn("™");Sn[147]=mn("fi");Sn[148]=mn("fl");Sn[149]=mn("Ł");Sn[150]=mn("Œ");Sn[151]=mn("Š");Sn[152]=mn("Ÿ");Sn[153]=mn("Ž");Sn[154]=mn("ı");Sn[155]=mn("ł");Sn[156]=mn("œ");Sn[157]=mn("š");Sn[158]=mn("ž");Sn[159]=mn("�");Sn[160]=mn("€");Sn[173]=mn("�");var cq=function(n){for(var e=new Array(n.length),t=0,r=n.length;t=le.ExclamationPoint&&n<=le.Tilde&&!d3[n]},N4={},W4=new Map,se=function(n){xt(e,n);function e(t,r){var i=this;if(t!==N4)throw new o3("PDFName");i=n.call(this)||this;for(var o="/",a=0,l=r.length;a=le.Zero&&c<=le.Nine||c>=le.a&&c<=le.f||c>=le.A&&c<=le.F?(r+=d,(r.length===2||!(u>="0"&&u<="9"||u>="a"&&u<="f"||u>="A"&&u<="F"))&&(o(parseInt(r,16)),r="")):o(c):c===le.Hash?i=!0:o(c)}return new Uint8Array(t)},e.prototype.decodeText=function(){var t=this.asBytes();return String.fromCharCode.apply(String,Array.from(t))},e.prototype.asString=function(){return this.encodedName},e.prototype.value=function(){return this.encodedName},e.prototype.clone=function(){return this},e.prototype.toString=function(){return this.encodedName},e.prototype.sizeInBytes=function(){return this.encodedName.length},e.prototype.copyBytesInto=function(t,r){return r+=Ro(this.encodedName,t,r),this.encodedName.length},e.of=function(t){var r=Wle(t),i=W4.get(r);return i||(i=new e(N4,r),W4.set(r,i)),i},e.Length=e.of("Length"),e.FlateDecode=e.of("FlateDecode"),e.Resources=e.of("Resources"),e.Font=e.of("Font"),e.XObject=e.of("XObject"),e.ExtGState=e.of("ExtGState"),e.Contents=e.of("Contents"),e.Type=e.of("Type"),e.Parent=e.of("Parent"),e.MediaBox=e.of("MediaBox"),e.Page=e.of("Page"),e.Annots=e.of("Annots"),e.TrimBox=e.of("TrimBox"),e.ArtBox=e.of("ArtBox"),e.BleedBox=e.of("BleedBox"),e.CropBox=e.of("CropBox"),e.Rotate=e.of("Rotate"),e.Title=e.of("Title"),e.Author=e.of("Author"),e.Subject=e.of("Subject"),e.Creator=e.of("Creator"),e.Keywords=e.of("Keywords"),e.Producer=e.of("Producer"),e.CreationDate=e.of("CreationDate"),e.ModDate=e.of("ModDate"),e}(Ca),Hle=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.asNull=function(){return null},e.prototype.clone=function(){return this},e.prototype.toString=function(){return"null"},e.prototype.sizeInBytes=function(){return 4},e.prototype.copyBytesInto=function(t,r){return t[r++]=le.n,t[r++]=le.u,t[r++]=le.l,t[r++]=le.l,4},e}(Ca);const Ya=new Hle;var _n=function(n){xt(e,n);function e(t,r){var i=n.call(this)||this;return i.dict=t,i.context=r,i}return e.prototype.keys=function(){return Array.from(this.dict.keys())},e.prototype.values=function(){return Array.from(this.dict.values())},e.prototype.entries=function(){return Array.from(this.dict.entries())},e.prototype.set=function(t,r){this.dict.set(t,r)},e.prototype.get=function(t,r){r===void 0&&(r=!1);var i=this.dict.get(t);if(!(i===Ya&&!r))return i},e.prototype.has=function(t){var r=this.dict.get(t);return r!==void 0&&r!==Ya},e.prototype.lookupMaybe=function(t){for(var r,i=[],o=1;othis.largestObjectNumber&&(this.largestObjectNumber=e.objectNumber)},n.prototype.nextRef=function(){return this.largestObjectNumber+=1,Mr.of(this.largestObjectNumber)},n.prototype.register=function(e){var t=this.nextRef();return this.assign(t,e),t},n.prototype.delete=function(e){return this.indirectObjects.delete(e)},n.prototype.lookupMaybe=function(e){for(var t=[],r=1;r1?(this.subsections.push([e]),this.chunkIdx+=1,this.chunkLength=1):(t.push(e),this.chunkLength+=1)},n.create=function(){return new n({ref:Mr.of(0,65535),offset:0,deleted:!0})},n.createEmpty=function(){return new n},n}(),u3=function(){function n(e){this.lastXRefOffset=String(e)}return n.prototype.toString=function(){return`startxref -`+this.lastXRefOffset+` -%%EOF`},n.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},n.prototype.copyBytesInto=function(e,t){var r=t;return e[t++]=le.s,e[t++]=le.t,e[t++]=le.a,e[t++]=le.r,e[t++]=le.t,e[t++]=le.x,e[t++]=le.r,e[t++]=le.e,e[t++]=le.f,e[t++]=le.Newline,t+=Ro(this.lastXRefOffset,e,t),e[t++]=le.Newline,e[t++]=le.Percent,e[t++]=le.Percent,e[t++]=le.E,e[t++]=le.O,e[t++]=le.F,t-r},n.forLastCrossRefSectionOffset=function(e){return new n(e)},n}(),Gle=function(){function n(e){this.dict=e}return n.prototype.toString=function(){return`trailer -`+this.dict.toString()},n.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},n.prototype.copyBytesInto=function(e,t){var r=t;return e[t++]=le.t,e[t++]=le.r,e[t++]=le.a,e[t++]=le.i,e[t++]=le.l,e[t++]=le.e,e[t++]=le.r,e[t++]=le.Newline,t+=this.dict.copyBytesInto(e,t),t-r},n.of=function(e){return new n(e)},n}(),fq=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!0);var o=n.call(this,t.obj({}),i)||this;return o.objects=r,o.offsets=o.computeObjectOffsets(),o.offsetsString=o.computeOffsetsString(),o.dict.set(se.of("Type"),se.of("ObjStm")),o.dict.set(se.of("N"),fn.of(o.objects.length)),o.dict.set(se.of("First"),fn.of(o.offsetsString.length)),o}return e.prototype.getObjectsCount=function(){return this.objects.length},e.prototype.clone=function(t){return e.withContextAndObjects(t||this.dict.context,this.objects.slice(),this.encode)},e.prototype.getContentsString=function(){for(var t=this.offsetsString,r=0,i=this.objects.length;r1&&(a.push(l),a.push(u.ref.objectNumber),l=0),l+=1}return a.push(l),a},o.computeEntryTuples=function(){for(var a=new Array(o.entries.length),l=0,d=o.entries.length;ll[0]&&(l[0]=m),y>l[1]&&(l[1]=y),v>l[2]&&(l[2]=v)}return l},o.entries=r||[],o.entryTuplesCache=mf.populatedBy(o.computeEntryTuples),o.maxByteWidthsCache=mf.populatedBy(o.computeMaxEntryByteWidths),o.indexCache=mf.populatedBy(o.computeIndex),t.set(se.of("Type"),se.of("XRef")),o}return e.prototype.addDeletedEntry=function(t,r){var i=np.Deleted;this.entries.push({type:i,ref:t,nextFreeObjectNumber:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addUncompressedEntry=function(t,r){var i=np.Uncompressed;this.entries.push({type:i,ref:t,offset:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.addCompressedEntry=function(t,r,i){var o=np.Compressed;this.entries.push({type:o,ref:t,objectStreamRef:r,index:i}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},e.prototype.clone=function(t){var r=this,i=r.dict,o=r.entries,a=r.encode;return e.of(i.clone(t),o.slice(),a)},e.prototype.getContentsString=function(){for(var t=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),i="",o=0,a=t.length;o=0;m--)i+=(f[m]||0).toString(2);for(var m=r[1]-1;m>=0;m--)i+=(p[m]||0).toString(2);for(var m=r[2]-1;m>=0;m--)i+=(g[m]||0).toString(2)}return i},e.prototype.getUnencodedContents=function(){for(var t=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),i=new Uint8Array(this.getUnencodedContentsSize()),o=0,a=0,l=t.length;a=0;y--)i[o++]=p[y]||0;for(var y=r[1]-1;y>=0;y--)i[o++]=g[y]||0;for(var y=r[2]-1;y>=0;y--)i[o++]=m[y]||0}return i},e.prototype.getUnencodedContentsSize=function(){var t=this.maxByteWidthsCache.access(),r=Kse(t);return r*this.entries.length},e.prototype.updateDict=function(){n.prototype.updateDict.call(this);var t=this.maxByteWidthsCache.access(),r=this.indexCache.access(),i=this.dict.context;this.dict.set(se.of("W"),i.obj(t)),this.dict.set(se.of("Index"),i.obj(r))},e.create=function(t,r){r===void 0&&(r=!0);var i=new e(t,[],r);return i.addDeletedEntry(Mr.of(0,65535),0),i},e.of=function(t,r,i){return i===void 0&&(i=!0),new e(t,r,i)},e}(c3),Xle=function(n){xt(e,n);function e(t,r,i,o){var a=n.call(this,t,r)||this;return a.encodeStreams=i,a.objectsPerStream=o,a}return e.prototype.computeBufferSize=function(){return Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c,m,y,u,x,f,p,v,g,m,y,v,x,w,S,_,b;return Rn(this,function(C){switch(C.label){case 0:t=this.context.largestObjectNumber+1,r=NF.forVersion(1,7),i=r.sizeInBytes()+2,o=Kle.create(this.createTrailerDict(),this.encodeStreams),a=[],l=[],d=[],c=this.context.enumerateIndirectObjects(),m=0,y=c.length,C.label=1;case 1:return m"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(t,r){return t[r++]=le.LessThan,r+=Ro(this.value,t,r),t[r++]=le.GreaterThan,this.value.length+2},e.of=function(t){return new e(t)},e.fromText=function(t){for(var r=$se(t),i="",o=0,a=r.length;o> def -/CMapName /Adobe-Identity-UCS def -/CMapType 2 def -1 begincodespacerange -<0000> -endcodespacerange -`+n.length+` beginbfchar -`+n.map(function(e){var t=e[0],r=e[1];return t+" "+r}).join(` -`)+` -endbfchar -endcmap -CMapName currentdict /CMap defineresource pop -end -end`},V4=function(){for(var n=[],e=0;e"},_5=function(n){return Z_(n,4)},$le=function(n){if(Zse(n))return _5(n);if(Jse(n)){var e=pH(n),t=gH(n);return""+_5(e)+_5(t)}var r=RF(n),i="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(i)},Zle=function(n){var e=0,t=function(r){e|=1<=le.Zero&&c<=le.Seven?(r+=d,(r.length===3||!(u>="0"&&u<="7"))&&(o(parseInt(r,8)),r="")):o(c):c===le.BackSlash?i=!0:o(c)}return new Uint8Array(t)},e.prototype.decodeText=function(){var t=this.asBytes();return bH(t)?mH(t):cq(t)},e.prototype.decodeDate=function(){var t=this.decodeText(),r=hH(t);if(!r)throw new uq(t);return r},e.prototype.asString=function(){return this.value},e.prototype.clone=function(){return e.of(this.value)},e.prototype.toString=function(){return"("+this.value+")"},e.prototype.sizeInBytes=function(){return this.value.length+2},e.prototype.copyBytesInto=function(t,r){return t[r++]=le.LeftParen,r+=Ro(this.value,t,r),t[r++]=le.RightParen,this.value.length+2},e.of=function(t){return new e(t)},e.fromDate=function(t){var r=_c(String(t.getUTCFullYear()),4,"0"),i=_c(String(t.getUTCMonth()+1),2,"0"),o=_c(String(t.getUTCDate()),2,"0"),a=_c(String(t.getUTCHours()),2,"0"),l=_c(String(t.getUTCMinutes()),2,"0"),d=_c(String(t.getUTCSeconds()),2,"0");return new e("D:"+r+i+o+a+l+d+"Z")},e}(Ca),h3=function(){function n(e,t,r,i){var o=this;this.allGlyphsInFontSortedById=function(){for(var a=new Array(o.font.characterSet.length),l=0,d=a.length;l>3)]>>7-((g&7)<<0)&1,P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D>2)]>>6-((g&3)<<1)&3,P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D>1)]>>4-((g&1)<<2)&15,P=3*D;l[S]=_[P],l[S+1]=_[P+1],l[S+2]=_[P+2],l[S+3]=D>>3)]>>>7-(M&7)&1),I=W==v*255?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==2)for(var M=0;M>>2)]>>>6-((M&3)<<1)&3),I=W==v*85?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==4)for(var M=0;M>>1)]>>>4-((M&1)<<2)&15),I=W==v*17?0:255;d[U+M]=I<<24|W<<16|W<<8|W}else if(u==8)for(var M=0;M>>2<<3));i==0;){if(i=v(e,p,1),o=v(e,p+1,2),p+=3,o==0){p&7&&(p+=8-(p&7));var F=(p>>>3)+4,A=e[F-4]|e[F-3]<<8;T&&(t=n.H.W(t,f+A)),t.set(new r(e.buffer,e.byteOffset+F,A),f),p=F+A<<3,f+=A;continue}if(T&&(t=n.H.W(t,f+(1<<17))),o==1&&(g=C.J,m=C.h,c=511,u=31),o==2){a=x(e,p,5)+257,l=x(e,p+5,5)+1,d=x(e,p+10,4)+4,p+=14;for(var D=1,P=0;P<38;P+=2)C.Q[P]=0,C.Q[P+1]=0;for(var P=0;PD&&(D=L)}p+=3*d,S(C.Q,D),_(C.Q,D,C.u),g=C.w,m=C.d,p=w(C.u,(1<>>4;if(!(M>>>8))t[f++]=M;else{if(M==256)break;var I=f+M-254;if(M>264){var H=C.q[M-257];I=f+(H>>>3)+x(e,p,H&7),p+=H&7}var z=m[b(e,p)&u];p+=z&15;var G=z>>>4,te=C.c[G],re=(te>>>4)+v(e,p,te&15);for(p+=te&15;f>>4;if(f<=15)a[c]=f,c++;else{var p=0,g=0;f==16?(g=3+l(i,o,2),o+=2,p=a[c-1]):f==17?(g=3+l(i,o,3),o+=3):f==18&&(g=11+l(i,o,7),o+=7);for(var m=c+g;c>>1;ao&&(o=d),a++}for(;a>1,c=e[l+1],u=d<<4|c,f=t-c,p=e[l]<>>15-t;r[m]=u,p++}},n.H.l=function(e,t){for(var r=n.H.m.r,i=15-t,o=0;o>>i}},n.H.M=function(e,t,r){r=r<<(t&7);var i=t>>>3;e[i]|=r,e[i+1]|=r>>>8},n.H.I=function(e,t,r){r=r<<(t&7);var i=t>>>3;e[i]|=r,e[i+1]|=r>>>8,e[i+2]|=r>>>16},n.H.e=function(e,t,r){return(e[t>>>3]|e[(t>>>3)+1]<<8)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)&(1<>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16)>>>(t&7)},n.H.i=function(e,t){return(e[t>>>3]|e[(t>>>3)+1]<<8|e[(t>>>3)+2]<<16|e[(t>>>3)+3]<<24)>>>(t&7)},n.H.m=function(){var e=Uint16Array,t=Uint32Array;return{K:new e(16),j:new e(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new e(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new t(32),J:new e(512),_:[],h:new e(32),$:[],w:new e(32768),C:[],v:[],d:new e(32768),D:[],u:new e(512),Q:[],r:new e(32768),s:new t(286),Y:new t(30),a:new t(19),t:new t(15e3),k:new e(65536),g:new e(32768)}}(),function(){for(var e=n.H.m,t=32768,r=0;r>>1|(i&1431655765)<<1,i=(i&3435973836)>>>2|(i&858993459)<<2,i=(i&4042322160)>>>4|(i&252645135)<<4,i=(i&4278255360)>>>8|(i&16711935)<<8,e.r[r]=(i>>>16|i<<16)>>>17}function o(a,l,d){for(;l--!=0;)a.push(0,d)}for(var r=0;r<32;r++)e.q[r]=e.S[r]<<3|e.T[r],e.c[r]=e.p[r]<<4|e.z[r];o(e._,144,8),o(e._,112,9),o(e._,24,7),o(e._,8,8),n.H.n(e._,9),n.H.A(e._,9,e.J),n.H.l(e._,9),o(e.$,32,5),n.H.n(e.$,5),n.H.A(e.$,5,e.h),n.H.l(e.$,5),o(e.Q,19,0),o(e.C,286,0),o(e.D,30,0),o(e.v,320,0)}(),n.H.N}();dt.decode._readInterlace=function(n,e){for(var t=e.width,r=e.height,i=dt.decode._getBPP(e),o=i>>3,a=Math.ceil(t*i/8),l=new Uint8Array(r*a),d=0,c=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],f=[8,8,8,4,4,2,2],p=[8,8,4,4,2,2,1],g=0;g<7;){for(var m=f[g],y=p[g],v=0,x=0,w=c[g];w>3];A=A>>7-(F&7)&1,l[C*a+(T>>3)]|=A<<7-((T&7)<<0)}if(i==2){var A=n[F>>3];A=A>>6-(F&7)&3,l[C*a+(T>>2)]|=A<<6-((T&3)<<1)}if(i==4){var A=n[F>>3];A=A>>4-(F&7)&15,l[C*a+(T>>1)]|=A<<4-((T&1)<<2)}if(i>=8)for(var D=C*a+T*o,P=0;P>3)+P];F+=i,T+=y}b++,C+=m}v*x!=0&&(d+=x*(1+_)),g=g+1}return l};dt.decode._getBPP=function(n){var e=[1,null,3,1,2,null,4][n.ctype];return e*n.depth};dt.decode._filterZero=function(n,e,t,r,i){var o=dt.decode._getBPP(e),a=Math.ceil(r*o/8),l=dt.decode._paeth;o=Math.ceil(o/8);var d=0,c=1,u=n[t],f=0;if(u>1&&(n[t]=[0,0,1][u-2]),u==3)for(f=o;f>>1)&255;for(var p=0;p>>1);for(;f>>1)}else{for(;f>8&255,n[e+1]=t&255},readUint:function(n,e){return n[e]*(256*256*256)+(n[e+1]<<16|n[e+2]<<8|n[e+3])},writeUint:function(n,e,t){n[e]=t>>24&255,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255},readASCII:function(n,e,t){for(var r="",i=0;i=0&&l>=0?(f=g*e+m<<2,p=(l+g)*i+a+m<<2):(f=(-l+g)*e-a+m<<2,p=g*i+m<<2),d==0)r[p]=n[f],r[p+1]=n[f+1],r[p+2]=n[f+2],r[p+3]=n[f+3];else if(d==1){var y=n[f+3]*.00392156862745098,v=n[f]*y,x=n[f+1]*y,w=n[f+2]*y,S=r[p+3]*(1/255),_=r[p]*S,b=r[p+1]*S,C=r[p+2]*S,T=1-y,F=y+S*T,A=F==0?0:1/F;r[p+3]=255*F,r[p+0]=(v+_*T)*A,r[p+1]=(x+b*T)*A,r[p+2]=(w+C*T)*A}else if(d==2){var y=n[f+3],v=n[f],x=n[f+1],w=n[f+2],S=r[p+3],_=r[p],b=r[p+1],C=r[p+2];y==S&&v==_&&x==b&&w==C?(r[p]=0,r[p+1]=0,r[p+2]=0,r[p+3]=0):(r[p]=v,r[p+1]=x,r[p+2]=w,r[p+3]=y)}else if(d==3){var y=n[f+3],v=n[f],x=n[f+1],w=n[f+2],S=r[p+3],_=r[p],b=r[p+1],C=r[p+2];if(y==S&&v==_&&x==b&&w==C)continue;if(y<220&&S>20)return!1}return!0};dt.encode=function(n,e,t,r,i,o,a){r==null&&(r=0),a==null&&(a=!1);var l=dt.encode.compress(n,e,t,r,[!1,!1,!1,0,a]);return dt.encode.compressPNG(l,-1),dt.encode._main(l,e,t,i,o)};dt.encodeLL=function(n,e,t,r,i,o,a,l){for(var d={ctype:0+(r==1?0:2)+(i==0?0:4),depth:o,frames:[]},c=(r+i)*o,u=c*e,f=0;f1,f=!1,p=33+(u?20:0);if(i.sRGB!=null&&(p+=13),i.pHYs!=null&&(p+=21),n.ctype==3){for(var g=n.plte.length,m=0;m>>24!=255&&(f=!0);p+=8+g*3+4+(f?8+g*1+4:0)}for(var y=0;y>>8&255,T=_>>>16&255;x[c+S+0]=b,x[c+S+1]=C,x[c+S+2]=T}if(c+=g*3,a(x,c,o(x,c-g*3-4,g*3+4)),c+=4,f){a(x,c,g),c+=4,d(x,c,"tRNS"),c+=4;for(var m=0;m>>24&255;c+=g,a(x,c,o(x,c-g-4,g+4)),c+=4}}for(var F=0,y=0;y>2,L>>2));for(var g=0;gU&&I==O[v-U])M[v]=M[v-U];else{var H=S[I];if(H==null&&(S[I]=H=_.length,_.push(I),_.length>=300))break;M[v]=H}}}var z=_.length;z<=256&&c==!1&&(z<=2?f=1:z<=4?f=2:z<=16?f=4:f=8,f=Math.max(f,d));for(var g=0;g>1)]|=ne[ke+Ye]<<4-(Ye&1)*4;else if(f==2)for(var Ye=0;Ye>2)]|=ne[ke+Ye]<<6-(Ye&3)*2;else if(f==1)for(var Ye=0;Ye>3)]|=ne[ke+Ye]<<7-(Ye&7)*1}te=J,u=3,me=1}else if(x==!1&&w.length==1){for(var J=new Uint8Array(U*G*3),De=U*G,v=0;vT&&(T=D),AF&&(F=A))}T==-1&&(b=C=T=F=0),i&&((b&1)==1&&b--,(C&1)==1&&C--);var L=(T-b+1)*(F-C+1);Lv&&(v=_),bx&&(x=b))}v==-1&&(m=y=v=x=0),a&&((m&1)==1&&m--,(y&1)==1&&y--),o={x:m,y,width:v-m+1,height:x-y+1};var F=r[i];F.rect=o,F.blend=1,F.img=new Uint8Array(o.width*o.height*4),r[i-1].dispose==0?(dt._copyTile(c,e,t,F.img,o.width,o.height,-o.x,-o.y,0),dt.encode._prepareDiff(p,e,t,F.img,o)):dt._copyTile(p,e,t,F.img,o.width,o.height,-o.x,-o.y,0)};dt.encode._prepareDiff=function(n,e,t,r,i){dt._copyTile(n,e,t,r,i.width,i.height,-i.x,-i.y,2)};dt.encode._filterZero=function(n,e,t,r,i,o,a){var l=[],d=[0,1,2,3,4];o!=-1?d=[o]:(e*r>5e5||t==1)&&(d=[0]);var c;a&&(c={level:0});for(var u=a&&UZIP!=null?UZIP:zF,f=0;f>1)+256&255;if(o==4)for(var c=i;c>1)&255;for(var c=i;c>1)&255}if(o==4){for(var c=0;c>>1:t=t>>>1;n[e]=t}return n}(),update:function(n,e,t,r){for(var i=0;i>>8;return n},crc:function(n,e,t){return dt.crc.update(4294967295,n,e,t)^4294967295}};dt.quantize=function(n,e){var t=new Uint8Array(n),r=t.slice(0),i=new Uint32Array(r.buffer),o=dt.quantize.getKDtree(r,e),a=o[0],l=o[1];dt.quantize.planeDst;for(var d=t,c=i,u=d.length,f=new Uint8Array(t.length>>2),p=0;p>2]=x.ind,c[p>>2]=x.est.rgba}return{abuf:r.buffer,inds:f,plte:l}};dt.quantize.getKDtree=function(n,e,t){t==null&&(t=1e-4);var r=new Uint32Array(n.buffer),i={i0:0,i1:n.length,bst:null,est:null,tdst:0,left:null,right:null};i.bst=dt.quantize.stats(n,i.i0,i.i1),i.est=dt.quantize.estats(i.bst);for(var o=[i];o.lengtha&&(a=o[d].est.L,l=d);if(a=u||c.i1<=u;if(f){c.est.L=0;continue}var p={i0:c.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};p.bst=dt.quantize.stats(n,p.i0,p.i1),p.est=dt.quantize.estats(p.bst);var g={i0:u,i1:c.i1,bst:null,est:null,tdst:0,left:null,right:null};g.bst={R:[],m:[],N:c.bst.N-p.bst.N};for(var d=0;d<16;d++)g.bst.R[d]=c.bst.R[d]-p.bst.R[d];for(var d=0;d<4;d++)g.bst.m[d]=c.bst.m[d]-p.bst.m[d];g.est=dt.quantize.estats(g.bst),c.left=p,c.right=g,o[l]=p,o.push(g)}o.sort(function(m,y){return y.bst.N-m.bst.N});for(var d=0;d0&&(a=n.right,l=n.left);var d=dt.quantize.getNearest(a,e,t,r,i);if(d.tdst<=o*o)return d;var c=dt.quantize.getNearest(l,e,t,r,i);return c.tdsto;)r-=4;if(t>=r)break;var l=e[t>>2];e[t>>2]=e[r>>2],e[r>>2]=l,t+=4,r-=4}for(;a(n,t,i)>o;)t-=4;return t+4};dt.quantize.vecDot=function(n,e,t){return n[e]*t[0]+n[e+1]*t[1]+n[e+2]*t[2]+n[e+3]*t[3]};dt.quantize.stats=function(n,e,t){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i=[0,0,0,0],o=t-e>>2,a=e;a>>0}};dt.M4={multVec:function(n,e){return[n[0]*e[0]+n[1]*e[1]+n[2]*e[2]+n[3]*e[3],n[4]*e[0]+n[5]*e[1]+n[6]*e[2]+n[7]*e[3],n[8]*e[0]+n[9]*e[1]+n[10]*e[2]+n[11]*e[3],n[12]*e[0]+n[13]*e[1]+n[14]*e[2]+n[15]*e[3]]},dot:function(n,e){return n[0]*e[0]+n[1]*e[1]+n[2]*e[2]+n[3]*e[3]},sml:function(n,e){return[n*e[0],n*e[1],n*e[2],n*e[3]]}};dt.encode.concatRGBA=function(n){for(var e=0,t=0;t1)throw new Error("Animated PNGs are not supported");var i=new Uint8Array(r[0]),o=ide(i),a=o.rgbChannel,l=o.alphaChannel;this.rgbChannel=a;var d=l.some(function(c){return c<255});d&&(this.alphaChannel=l),this.type=rde(t.ctype),this.width=t.width,this.height=t.height,this.bitsPerComponent=8}return n.load=function(e){return new n(e)},n}(),yq=function(){function n(e){this.image=e,this.bitsPerComponent=e.bitsPerComponent,this.width=e.width,this.height=e.height,this.colorSpace="DeviceRGB"}return n.for=function(e){return Pn(this,void 0,void 0,function(){var t;return Rn(this,function(r){return t=sde.load(e),[2,new n(t)]})})},n.prototype.embedIntoContext=function(e,t){return Pn(this,void 0,void 0,function(){var r,i;return Rn(this,function(o){return r=this.embedAlphaChannel(e),i=e.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:r}),t?(e.assign(t,i),[2,t]):[2,e.register(i)]})})},n.prototype.embedAlphaChannel=function(e){if(this.image.alphaChannel){var t=e.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return e.register(t)}},n}(),xq=function(){function n(e,t,r){this.bytes=e,this.start=t||0,this.pos=this.start,this.end=t&&r?t+r:this.bytes.length}return Object.defineProperty(n.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),n.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},n.prototype.getUint16=function(){var e=this.getByte(),t=this.getByte();return e===-1||t===-1?-1:(e<<8)+t},n.prototype.getInt32=function(){var e=this.getByte(),t=this.getByte(),r=this.getByte(),i=this.getByte();return(e<<24)+(t<<16)+(r<<8)+i},n.prototype.getBytes=function(e,t){t===void 0&&(t=!1);var r=this.bytes,i=this.pos,o=this.end;if(e){var l=i+e;l>o&&(l=o),this.pos=l;var a=r.subarray(i,l);return t?new Uint8ClampedArray(a):a}else{var a=r.subarray(i,o);return t?new Uint8ClampedArray(a):a}},n.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},n.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var r=this.getBytes(e,t);return this.pos-=r.length,r},n.prototype.skip=function(e){e||(e=1),this.pos+=e},n.prototype.reset=function(){this.pos=this.start},n.prototype.moveStart=function(){this.start=this.pos},n.prototype.makeSubStream=function(e,t){return new n(this.bytes,e,t)},n.prototype.decode=function(){return this.bytes},n}(),ode=new Uint8Array(0),sC=function(){function n(e){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=ode,this.minBufferLength=512,e)for(;this.minBufferLengtho&&(r=o)}else{for(;!this.eof;)this.readBlock();r=this.bufferLength}this.pos=r;var a=this.buffer.subarray(i,r);return t&&!(a instanceof Uint8ClampedArray)?new Uint8ClampedArray(a):a},n.prototype.peekByte=function(){var e=this.getByte();return this.pos--,e},n.prototype.peekBytes=function(e,t){t===void 0&&(t=!1);var r=this.getBytes(e,t);return this.pos-=r.length,r},n.prototype.skip=function(e){e||(e=1),this.pos+=e},n.prototype.reset=function(){this.pos=0},n.prototype.makeSubStream=function(e,t){for(var r=e+t;this.bufferLength<=r&&!this.eof;)this.readBlock();return new xq(this.buffer,e,t)},n.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},n.prototype.readBlock=function(){throw new Pd(this.constructor.name,"readBlock")},n.prototype.ensureBuffer=function(e){var t=this.buffer;if(e<=t.byteLength)return t;for(var r=this.minBufferLength;r=0;--c)d[l+c]=f&255,f>>=8}},e}(sC),lde=function(n){xt(e,n);function e(t,r){var i=n.call(this,r)||this;return i.stream=t,i.firstDigit=-1,r&&(r=.5*r),i}return e.prototype.readBlock=function(){var t=8e3,r=this.stream.getBytes(t);if(!r.length){this.eof=!0;return}for(var i=r.length+1>>1,o=this.ensureBuffer(this.bufferLength+i),a=this.bufferLength,l=this.firstDigit,d=0,c=r.length;d=48&&u<=57)f=u&15;else if(u>=65&&u<=70||u>=97&&u<=102)f=(u&15)+9;else if(u===62){this.eof=!0;break}else continue;l<0?l=f:(o[a++]=l<<4|f,l=-1)}l>=0&&this.eof&&(o[a++]=l<<4,l=-1),this.firstDigit=l,this.bufferLength=a},e}(sC),X4=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),dde=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),cde=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),ude=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],hde=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],fde=function(n){xt(e,n);function e(t,r){var i=n.call(this,r)||this;i.stream=t;var o=t.getByte(),a=t.getByte();if(o===-1||a===-1)throw new Error("Invalid header in flate stream: "+o+", "+a);if((o&15)!==8)throw new Error("Unknown compression method in flate stream: "+o+", "+a);if(((o<<8)+a)%31!==0)throw new Error("Bad FCHECK in flate stream: "+o+", "+a);if(a&32)throw new Error("FDICT bit set in flate stream: "+o+", "+a);return i.codeSize=0,i.codeBuf=0,i}return e.prototype.readBlock=function(){var t,r,i=this.stream,o=this.getBits(3);if(o&1&&(this.eof=!0),o>>=1,o===0){var a=void 0;if((a=i.getByte())===-1)throw new Error("Bad block header in flate stream");var l=a;if((a=i.getByte())===-1)throw new Error("Bad block header in flate stream");if(l|=a<<8,(a=i.getByte())===-1)throw new Error("Bad block header in flate stream");var d=a;if((a=i.getByte())===-1)throw new Error("Bad block header in flate stream");if(d|=a<<8,d!==(~l&65535)&&(l!==0||d!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var c=this.bufferLength;t=this.ensureBuffer(c+l);var u=c+l;if(this.bufferLength=u,l===0)i.peekByte()===-1&&(this.eof=!0);else for(var f=c;f0;)b[w++]=F}p=this.generateHuffmanTable(b.subarray(0,m)),g=this.generateHuffmanTable(b.subarray(m,_))}else throw new Error("Unknown block type in flate stream");t=this.buffer;for(var P=t?t.length:0,L=this.bufferLength;;){var W=this.getCode(p);if(W<256){L+1>=P&&(t=this.ensureBuffer(L+1),P=t.length),t[L++]=W;continue}if(W===256){this.bufferLength=L;return}W-=257,W=dde[W];var O=W>>16;O>0&&(O=this.getBits(O)),r=(W&65535)+O,W=this.getCode(g),W=cde[W],O=W>>16,O>0&&(O=this.getBits(O));var U=(W&65535)+O;L+r>=P&&(t=this.ensureBuffer(L+r),P=t.length);for(var M=0;M>t,this.codeSize=i-=t,a},e.prototype.getCode=function(t){for(var r=this.stream,i=t[0],o=t[1],a=this.codeSize,l=this.codeBuf,d;a>16,f=c&65535;if(u<1||a>u,this.codeSize=a-u,f},e.prototype.generateHuffmanTable=function(t){var r=t.length,i=0,o;for(o=0;oi&&(i=t[o]);for(var a=1<>=1;for(o=p;o0;if(!b||b<256)v[0]=b,x=1;else if(b>=258)if(b=0;a--)v[a]=f[l],l=g[l];else v[x++]=v[0];else if(b===256){m=9,u=258,x=0;continue}else{this.eof=!0,delete this.lzwState;break}if(C&&(g[u]=y,p[u]=p[y]+1,f[u]=v[0],u++,m=u+c&u+c-1?m:Math.min(Math.log(u+c)/.6931471805599453+1,12)|0),y=b,w+=x,r>>r&(1<0){var a=this.stream.getBytes(o);r.set(a,i),i+=o}}else{o=257-o;var l=t[1];r=this.ensureBuffer(i+o+1);for(var d=0;dr.size())throw new rT(t,0,r.size());r.remove(t)}else{if(t!==0)throw new rT(t,0,0);this.setKids([])}},e.prototype.normalizedEntries=function(){var t=this.Kids();return t||(t=this.dict.context.obj([this.ref]),this.dict.set(se.of("Kids"),t)),{Kids:t}},e.fromDict=function(t,r){return new e(t,r)},e}(wq),f3=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.Opt=function(){return this.dict.lookupMaybe(se.of("Opt"),Ir,dn,Sr)},e.prototype.setOpt=function(t){this.dict.set(se.of("Opt"),this.dict.context.obj(t))},e.prototype.getExportValues=function(){var t=this.Opt();if(t){if(t instanceof Ir||t instanceof dn)return[t];for(var r=[],i=0,o=t.size();ir.size())throw new rT(t,0,r.size());r.remove(t)}},e.prototype.normalizeExportValues=function(){for(var t,r,i,o,a=(t=this.getExportValues())!==null&&t!==void 0?t:[],l=[],d=this.getWidgets(),c=0,u=d.length;c1){if(!this.hasFlag(Br.MultiSelect))throw new Fle;this.dict.set(se.of("V"),this.dict.context.obj(t))}this.updateSelectedIndices(t)},e.prototype.valuesAreValid=function(t){for(var r=this.getOptions(),i=function(d,c){var u=t[d].decodeText();if(!r.find(function(f){return u===(f.display||f.value).decodeText()}))return{value:!1}},o=0,a=t.length;o1){for(var r=new Array(t.length),i=this.getOptions(),o=function(d,c){var u=t[d].decodeText();r[d]=i.findIndex(function(f){return u===(f.display||f.value).decodeText()})},a=0,l=t.length;a0){var l=a.lookup(0,Ir,dn),d=a.lookupMaybe(1,Ir,dn);r.push({value:l,display:d||l})}}return r}return[]},e}(j1),UF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Ch",Ff:Br.Combo,Kids:[]}),i=t.register(r);return new e(r,i)},e}(Sq),oT=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.addField=function(t){var r=this.normalizedEntries().Kids;r==null||r.push(t)},e.prototype.normalizedEntries=function(){var t=this.Kids();return t||(t=this.dict.context.obj([]),this.dict.set(se.of("Kids"),t)),{Kids:t}},e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({}),i=t.register(r);return new e(r,i)},e}(wq),p3=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.fromDict=function(t,r){return new e(t,r)},e}(j1),HF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.MaxLen=function(){var t=this.dict.lookup(se.of("MaxLen"));if(t instanceof fn)return t},e.prototype.Q=function(){var t=this.dict.lookup(se.of("Q"));if(t instanceof fn)return t},e.prototype.setMaxLength=function(t){this.dict.set(se.of("MaxLen"),fn.of(t))},e.prototype.removeMaxLength=function(){this.dict.delete(se.of("MaxLen"))},e.prototype.getMaxLength=function(){var t;return(t=this.MaxLen())===null||t===void 0?void 0:t.asNumber()},e.prototype.setQuadding=function(t){this.dict.set(se.of("Q"),fn.of(t))},e.prototype.getQuadding=function(){var t;return(t=this.Q())===null||t===void 0?void 0:t.asNumber()},e.prototype.setValue=function(t){this.dict.set(se.of("V"),t)},e.prototype.removeValue=function(){this.dict.delete(se.of("V"))},e.prototype.getValue=function(){var t=this.V();if(t instanceof Ir||t instanceof dn)return t},e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Tx",Kids:[]}),i=t.register(r);return new e(r,i)},e}(j1),qF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.fromDict=function(t,r){return new e(t,r)},e.create=function(t){var r=t.obj({FT:"Btn",Ff:Cd.PushButton,Kids:[]}),i=t.register(r);return new e(r,i)},e}(f3),VF=function(n){xt(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.setValue=function(t){var r=this.getOnValues();if(!r.includes(t)&&t!==se.of("Off"))throw new l3;this.dict.set(se.of("V"),t);for(var i=this.getWidgets(),o=0,a=i.length;oo)throw new z4(r,o);for(var a=r,l=0,d=i.size();la)return u.insertLeafNode(t,a)||c;a-=u.Count().asNumber()}u instanceof yf&&(a-=1)}if(a===0){this.insertLeafKid(i.size(),t);return}throw new O4(r,"insertLeafNode")},e.prototype.removeLeafNode=function(t,r){r===void 0&&(r=!0);var i=this.Kids(),o=this.Count().asNumber();if(t>=o)throw new z4(t,o);for(var a=t,l=0,d=i.size();la){u.removeLeafNode(a,r),r&&u.Kids().size()===0&&i.remove(l);return}else a-=u.Count().asNumber();if(u instanceof yf)if(a===0){this.removeKid(l);return}else a-=1}throw new O4(t,"removeLeafNode")},e.prototype.ascend=function(t){t(this);var r=this.Parent();r&&r.ascend(t)},e.prototype.traverse=function(t){for(var r=this.Kids(),i=0,o=r.size();iNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var i="Parsed number that is too large for some PDF readers: "+e+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(i),Number.MAX_SAFE_INTEGER}else{var i="Parsed number that is too large for some PDF readers: "+e+", not capping.";console.warn(i)}return r},n.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&Bf[this.bytes.peek()];)this.bytes.next()},n.prototype.skipLine=function(){for(;!this.bytes.done();){var e=this.bytes.peek();if(e===$4||e===Z4)return;this.bytes.next()}},n.prototype.skipComment=function(){if(this.bytes.peek()!==le.Percent)return!1;for(;!this.bytes.done();){var e=this.bytes.peek();if(e===$4||e===Z4)return!0;this.bytes.next()}return!0},n.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},n.prototype.matchKeyword=function(e){for(var t=this.bytes.offset(),r=0,i=e.length;r=this.length},n.prototype.offset=function(){return this.idx},n.prototype.slice=function(e,t){return this.bytes.slice(e,t)},n.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},n.of=function(e){return new n(e)},n.fromPDFRawStream=function(e){return n.of(bq(e).decode())},n}(),Cde=le.Space,Nw=le.CarriageReturn,Ww=le.Newline,Uw=[le.s,le.t,le.r,le.e,le.a,le.m],O2=[le.e,le.n,le.d,le.s,le.t,le.r,le.e,le.a,le.m],ai={header:[le.Percent,le.P,le.D,le.F,le.Dash],eof:[le.Percent,le.Percent,le.E,le.O,le.F],obj:[le.o,le.b,le.j],endobj:[le.e,le.n,le.d,le.o,le.b,le.j],xref:[le.x,le.r,le.e,le.f],trailer:[le.t,le.r,le.a,le.i,le.l,le.e,le.r],startxref:[le.s,le.t,le.a,le.r,le.t,le.x,le.r,le.e,le.f],true:[le.t,le.r,le.u,le.e],false:[le.f,le.a,le.l,le.s,le.e],null:[le.n,le.u,le.l,le.l],stream:Uw,streamEOF1:fr(Uw,[Cde,Nw,Ww]),streamEOF2:fr(Uw,[Nw,Ww]),streamEOF3:fr(Uw,[Nw]),streamEOF4:fr(Uw,[Ww]),endstream:O2,EOF1endstream:fr([Nw,Ww],O2),EOF2endstream:fr([Nw],O2),EOF3endstream:fr([Ww],O2)},Aq=function(n){xt(e,n);function e(t,r,i){i===void 0&&(i=!1);var o=n.call(this,t,i)||this;return o.context=r,o}return e.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(ai.true))return Uj.True;if(this.matchKeyword(ai.false))return Uj.False;if(this.matchKeyword(ai.null))return Ya;var t=this.bytes.peek();if(t===le.LessThan&&this.bytes.peekAhead(1)===le.LessThan)return this.parseDictOrStream();if(t===le.LessThan)return this.parseHexString();if(t===le.LeftParen)return this.parseString();if(t===le.ForwardSlash)return this.parseName();if(t===le.LeftSquareBracket)return this.parseArray();if(y3[t])return this.parseNumberOrRef();throw new Rle(this.bytes.position(),t)},e.prototype.parseNumberOrRef=function(){var t=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(oa[this.bytes.peek()]){var i=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===le.R)return this.bytes.assertNext(le.R),Mr.of(t,i)}return this.bytes.moveTo(r),fn.of(t)},e.prototype.parseHexString=function(){var t="";for(this.bytes.assertNext(le.LessThan);!this.bytes.done()&&this.bytes.peek()!==le.GreaterThan;)t+=gf(this.bytes.next());return this.bytes.assertNext(le.GreaterThan),dn.of(t)},e.prototype.parseString=function(){for(var t=0,r=!1,i="";!this.bytes.done();){var o=this.bytes.next();if(i+=gf(o),r||(o===le.LeftParen&&(t+=1),o===le.RightParen&&(t-=1)),o===le.BackSlash?r=!r:r&&(r=!1),t===0)return Ir.of(i.substring(1,i.length-1))}throw new Mle(this.bytes.position())},e.prototype.parseName=function(){this.bytes.assertNext(le.ForwardSlash);for(var t="";!this.bytes.done();){var r=this.bytes.peek();if(Bf[r]||qd[r])break;t+=gf(r),this.bytes.next()}return se.of(t)},e.prototype.parseArray=function(){this.bytes.assertNext(le.LeftSquareBracket),this.skipWhitespaceAndComments();for(var t=Sr.withContext(this.context);this.bytes.peek()!==le.RightSquareBracket;){var r=this.parseObject();t.push(r),this.skipWhitespaceAndComments()}return this.bytes.assertNext(le.RightSquareBracket),t},e.prototype.parseDict=function(){this.bytes.assertNext(le.LessThan),this.bytes.assertNext(le.LessThan),this.skipWhitespaceAndComments();for(var t=new Map;!this.bytes.done()&&this.bytes.peek()!==le.GreaterThan&&this.bytes.peekAhead(1)!==le.GreaterThan;){var r=this.parseName(),i=this.parseObject();t.set(r,i),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(le.GreaterThan),this.bytes.assertNext(le.GreaterThan);var o=t.get(se.of("Type"));return o===se.of("Catalog")?_q.fromMapWithContext(t,this.context):o===se.of("Pages")?Cq.fromMapWithContext(t,this.context):o===se.of("Page")?yf.fromMapWithContext(t,this.context):_n.fromMapWithContext(t,this.context)},e.prototype.parseDictOrStream=function(){var t=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(ai.streamEOF1)&&!this.matchKeyword(ai.streamEOF2)&&!this.matchKeyword(ai.streamEOF3)&&!this.matchKeyword(ai.streamEOF4)&&!this.matchKeyword(ai.stream))return r;var i=this.bytes.offset(),o,a=r.get(se.of("Length"));a instanceof fn?(o=i+a.asNumber(),this.bytes.moveTo(o),this.skipWhitespaceAndComments(),this.matchKeyword(ai.endstream)||(this.bytes.moveTo(i),o=this.findEndOfStreamFallback(t))):o=this.findEndOfStreamFallback(t);var l=this.bytes.slice(i,o);return Hj.of(r,l)},e.prototype.findEndOfStreamFallback=function(t){for(var r=1,i=this.bytes.offset();!this.bytes.done()&&(i=this.bytes.offset(),this.matchKeyword(ai.stream)?r+=1:this.matchKeyword(ai.EOF1endstream)||this.matchKeyword(ai.EOF2endstream)||this.matchKeyword(ai.EOF3endstream)||this.matchKeyword(ai.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new Ile(t);return i},e.forBytes=function(t,r,i){return new e(XF.of(t),r,i)},e.forByteStream=function(t,r,i){return i===void 0&&(i=!1),new e(t,r,i)},e}(_de),Ade=function(n){xt(e,n);function e(t,r){var i=n.call(this,XF.fromPDFRawStream(t),t.dict.context)||this,o=t.dict;return i.alreadyParsed=!1,i.shouldWaitForTick=r||function(){return!1},i.firstOffset=o.lookup(se.of("First"),fn).asNumber(),i.objectCount=o.lookup(se.of("N"),fn).asNumber(),i}return e.prototype.parseIntoContext=function(){return Pn(this,void 0,void 0,function(){var t,r,i,o,a,l,d,c;return Rn(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new a3("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,t=this.parseOffsetsAndObjectNumbers(),r=0,i=t.length,u.label=1;case 1:return r=le.Space&&r<=le.Tilde;if(i&&(this.matchKeyword(ai.xref)||this.matchKeyword(ai.trailer)||this.matchKeyword(ai.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(t);break}this.bytes.next()}},e.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var t=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(t)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},e.forBytesWithOptions=function(t,r,i,o){return new e(t,r,i,o)},e}(Aq),Gc=function(n){return 1<0&&(r[r.length]=+i),t[t.length]={cmd:e,args:r},r=[],i="",o=!1),e=c;else if([" ",","].includes(c)||c==="-"&&i.length>0&&i[i.length-1]!=="e"||c==="."&&o){if(i.length===0)continue;r.length===a?(t[t.length]={cmd:e,args:r},r=[+i],e==="M"&&(e="L"),e==="m"&&(e="l")):r[r.length]=+i,o=c===".",i=["-","."].includes(c)?c:""}else i+=c,c==="."&&(o=!0)}return i.length>0&&(r.length===a?(t[t.length]={cmd:e,args:r},r=[+i],e==="M"&&(e="L"),e==="m"&&(e="l")):r[r.length]=+i),t[t.length]={cmd:e,args:r},t},Ude=function(n){$t=Zt=ir=sr=aS=lS=0;for(var e=[],t=0;t1&&(p=Math.sqrt(p),t*=p,r*=p);var g=f/t,m=u/t,y=-u/r,v=f/r,x=g*l+m*d,w=y*l+v*d,S=g*n+m*e,_=y*n+v*e,b=(S-x)*(S-x)+(_-w)*(_-w),C=1/b-.25;C<0&&(C=0);var T=Math.sqrt(C);o===i&&(T=-T);var F=.5*(x+S)-T*(_-w),A=.5*(w+_)+T*(S-x),D=Math.atan2(w-A,x-F),P=Math.atan2(_-A,S-F),L=P-D;L<0&&o===1?L+=2*Math.PI:L>0&&o===0&&(L-=2*Math.PI);for(var W=Math.ceil(Math.abs(L/(Math.PI*.5+.001))),O=[],U=0;Un.length)return i-1;var v=e.heightAtSize(i),x=v+v*.2,w=x*o;if(w>Math.abs(t.height))return i-1;i+=1}return i},cce=function(n,e,t,r){for(var i=t.width/r,o=t.height,a=Vq,l=Lse(n);ai*.75;if(f)return a-1}var p=e.heightAtSize(a,{descender:!1});if(p>o)return a-1;a+=1}return a},uce=function(n){for(var e=n.length;e>0;e--)if(/\s/.test(n[e]))return e},hce=function(n,e,t,r){for(var i,o=n.length;o>0;){var a=n.substring(0,o),l=t.encodeText(a),d=t.widthOfTextAtSize(a,r);if(dp&&(p=T+b),m+l>g&&(g=m+l),c.push({text:S,encoded:_,width:b,height:l,x:T,y:m}),x=C==null?void 0:C.trim()}return{fontSize:r,lineHeight:d,lines:c,bounds:{x:u,y:f,width:p-u,height:g-f}}},fce=function(n,e){var t=e.fontSize,r=e.font,i=e.bounds,o=e.cellCount,a=cH(J_(n));if(a.length>o)throw new ace(a.length,o);(t===void 0||t===0)&&(t=cce(a,r,i,o));for(var l=i.width/o,d=r.heightAtSize(t,{descender:!1}),c=i.y+(i.height/2-d/2),u=[],f=i.x,p=i.y,g=i.x+i.width,m=i.y+i.height,y=0,v=0;yg&&(g=T+b),c+d>m&&(m=c+d),u.push({text:a,encoded:_,width:b,height:d,x:T,y:c}),y+=1,v+=S}return{fontSize:t,cells:u,bounds:{x:f,y:p,width:g-f,height:m-p}}},hT=function(n,e){var t=e.alignment,r=e.fontSize,i=e.font,o=e.bounds,a=cH(J_(n));(r===void 0||r===0)&&(r=Kq([a],i,o));var l=i.encodeText(a),d=i.widthOfTextAtSize(a,r),c=i.heightAtSize(r,{descender:!1}),u=t===Os.Left?o.x:t===Os.Center?o.x+o.width/2-d/2:t===Os.Right?o.x+o.width-d:o.x,f=o.y+(o.height/2-c/2);return{fontSize:r,line:{text:a,encoded:l,width:d,height:c,x:u,y:f},bounds:{x:u,y:f,width:d,height:c}}},_1=function(n){return"normal"in n?n:{normal:n}},pce=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,Lg=function(n){var e,t,r=(e=n.getDefaultAppearance())!==null&&e!==void 0?e:"",i=(t=Z6(r,pce).match)!==null&&t!==void 0?t:[],o=Number(i[2]);return isFinite(o)?o:void 0},gce=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,Wd=function(n){var e,t=(e=n.getDefaultAppearance())!==null&&e!==void 0?e:"",r=Z6(t,gce).match,i=r??[],o=i[1],a=i[2],l=i[3],d=i[4],c=i[5];if(c==="g"&&o)return Nq(Number(o));if(c==="rg"&&o&&a&&l)return zr(Number(o),Number(a),Number(l));if(c==="k"&&o&&a&&l&&d)return Wq(Number(o),Number(a),Number(l),Number(d))},Ud=function(n,e,t,r){var i;r===void 0&&(r=0);var o=[L0(e).toString(),w3((i=t==null?void 0:t.name)!==null&&i!==void 0?i:"dummy__noop",r).toString()].join(` -`);n.setDefaultAppearance(o)},mce=function(n,e){var t,r,i,o=Wd(e),a=Wd(n.acroField),l=e.getRectangle(),d=e.getAppearanceCharacteristics(),c=e.getBorderStyle(),u=(t=c==null?void 0:c.getWidth())!==null&&t!==void 0?t:0,f=If(d==null?void 0:d.getRotation()),p=z0(l,f),g=p.width,m=p.height,y=Kg(wn(wn({},l),{rotation:f})),v=zr(0,0,0),x=(r=Aa(d==null?void 0:d.getBorderColor()))!==null&&r!==void 0?r:v,w=Aa(d==null?void 0:d.getBackgroundColor()),S=Aa(d==null?void 0:d.getBackgroundColor(),.8),_=(i=o??a)!==null&&i!==void 0?i:v;Ud(o?e:n.acroField,_);var b={x:0+u/2,y:0+u/2,width:g-u,height:m-u,thickness:1.5,borderWidth:u,borderColor:x,markColor:_};return{normal:{on:fr(y,W2(wn(wn({},b),{color:w,filled:!0}))),off:fr(y,W2(wn(wn({},b),{color:w,filled:!1})))},down:{on:fr(y,W2(wn(wn({},b),{color:S,filled:!0}))),off:fr(y,W2(wn(wn({},b),{color:S,filled:!1})))}}},yce=function(n,e){var t,r,i,o=Wd(e),a=Wd(n.acroField),l=e.getRectangle(),d=e.getAppearanceCharacteristics(),c=e.getBorderStyle(),u=(t=c==null?void 0:c.getWidth())!==null&&t!==void 0?t:0,f=If(d==null?void 0:d.getRotation()),p=z0(l,f),g=p.width,m=p.height,y=Kg(wn(wn({},l),{rotation:f})),v=zr(0,0,0),x=(r=Aa(d==null?void 0:d.getBorderColor()))!==null&&r!==void 0?r:v,w=Aa(d==null?void 0:d.getBackgroundColor()),S=Aa(d==null?void 0:d.getBackgroundColor(),.8),_=(i=o??a)!==null&&i!==void 0?i:v;Ud(o?e:n.acroField,_);var b={x:g/2,y:m/2,width:g-u,height:m-u,borderWidth:u,borderColor:x,dotColor:_};return{normal:{on:fr(y,U2(wn(wn({},b),{color:w,filled:!0}))),off:fr(y,U2(wn(wn({},b),{color:w,filled:!1})))},down:{on:fr(y,U2(wn(wn({},b),{color:S,filled:!0}))),off:fr(y,U2(wn(wn({},b),{color:S,filled:!1})))}}},xce=function(n,e,t){var r,i,o,a,l,d=Wd(e),c=Wd(n.acroField),u=Lg(e),f=Lg(n.acroField),p=e.getRectangle(),g=e.getAppearanceCharacteristics(),m=e.getBorderStyle(),y=g==null?void 0:g.getCaptions(),v=(r=y==null?void 0:y.normal)!==null&&r!==void 0?r:"",x=(o=(i=y==null?void 0:y.down)!==null&&i!==void 0?i:v)!==null&&o!==void 0?o:"",w=(a=m==null?void 0:m.getWidth())!==null&&a!==void 0?a:0,S=If(g==null?void 0:g.getRotation()),_=z0(p,S),b=_.width,C=_.height,T=Kg(wn(wn({},p),{rotation:S})),F=zr(0,0,0),A=Aa(g==null?void 0:g.getBorderColor()),D=Aa(g==null?void 0:g.getBackgroundColor()),P=Aa(g==null?void 0:g.getBackgroundColor(),.8),L={x:w,y:w,width:b-w*2,height:C-w*2},W=hT(v,{alignment:Os.Center,fontSize:u??f,font:t,bounds:L}),O=hT(x,{alignment:Os.Center,fontSize:u??f,font:t,bounds:L}),U=Math.min(W.fontSize,O.fontSize),M=(l=d??c)!==null&&l!==void 0?l:F;Ud(d||u!==void 0?e:n.acroField,M,t,U);var I={x:0+w/2,y:0+w/2,width:b-w,height:C-w,borderWidth:w,borderColor:A,textColor:M,font:t.name,fontSize:U};return{normal:fr(T,sN(wn(wn({},I),{color:D,textLines:[W.line]}))),down:fr(T,sN(wn(wn({},I),{color:P,textLines:[O.line]})))}},bce=function(n,e,t){var r,i,o,a,l=Wd(e),d=Wd(n.acroField),c=Lg(e),u=Lg(n.acroField),f=e.getRectangle(),p=e.getAppearanceCharacteristics(),g=e.getBorderStyle(),m=(r=n.getText())!==null&&r!==void 0?r:"",y=(i=g==null?void 0:g.getWidth())!==null&&i!==void 0?i:0,v=If(p==null?void 0:p.getRotation()),x=z0(f,v),w=x.width,S=x.height,_=Kg(wn(wn({},f),{rotation:v})),b=zr(0,0,0),C=Aa(p==null?void 0:p.getBorderColor()),T=Aa(p==null?void 0:p.getBackgroundColor()),F,A,D=n.isCombed()?0:1,P={x:y+D,y:y+D,width:w-(y+D)*2,height:S-(y+D)*2};if(n.isMultiline()){var L=Xq(m,{alignment:n.getAlignment(),fontSize:c??u,font:t,bounds:P});F=L.lines,A=L.fontSize}else if(n.isCombed()){var L=fce(m,{fontSize:c??u,font:t,bounds:P,cellCount:(o=n.getMaxLength())!==null&&o!==void 0?o:0});F=L.cells,A=L.fontSize}else{var L=hT(m,{alignment:n.getAlignment(),fontSize:c??u,font:t,bounds:P});F=[L.line],A=L.fontSize}var W=(a=l??d)!==null&&a!==void 0?a:b;Ud(l||c!==void 0?e:n.acroField,W,t,A);var O={x:0+y/2,y:0+y/2,width:w-y,height:S-y,borderWidth:y??0,borderColor:C,textColor:W,font:t.name,fontSize:A,color:T,textLines:F,padding:D};return fr(_,Hq(O))},vce=function(n,e,t){var r,i,o,a=Wd(e),l=Wd(n.acroField),d=Lg(e),c=Lg(n.acroField),u=e.getRectangle(),f=e.getAppearanceCharacteristics(),p=e.getBorderStyle(),g=(r=n.getSelected()[0])!==null&&r!==void 0?r:"",m=(i=p==null?void 0:p.getWidth())!==null&&i!==void 0?i:0,y=If(f==null?void 0:f.getRotation()),v=z0(u,y),x=v.width,w=v.height,S=Kg(wn(wn({},u),{rotation:y})),_=zr(0,0,0),b=Aa(f==null?void 0:f.getBorderColor()),C=Aa(f==null?void 0:f.getBackgroundColor()),T=1,F={x:m+T,y:m+T,width:x-(m+T)*2,height:w-(m+T)*2},A=hT(g,{alignment:Os.Left,fontSize:d??c,font:t,bounds:F}),D=A.line,P=A.fontSize,L=(o=a??l)!==null&&o!==void 0?o:_;Ud(a||d!==void 0?e:n.acroField,L,t,P);var W={x:0+m/2,y:0+m/2,width:x-m,height:w-m,borderWidth:m??0,borderColor:b,textColor:L,font:t.name,fontSize:P,color:C,textLines:[D],padding:T};return fr(S,Hq(W))},wce=function(n,e,t){var r,i,o=Wd(e),a=Wd(n.acroField),l=Lg(e),d=Lg(n.acroField),c=e.getRectangle(),u=e.getAppearanceCharacteristics(),f=e.getBorderStyle(),p=(r=f==null?void 0:f.getWidth())!==null&&r!==void 0?r:0,g=If(u==null?void 0:u.getRotation()),m=z0(c,g),y=m.width,v=m.height,x=Kg(wn(wn({},c),{rotation:g})),w=zr(0,0,0),S=Aa(u==null?void 0:u.getBorderColor()),_=Aa(u==null?void 0:u.getBackgroundColor()),b=n.getOptions(),C=n.getSelected();n.isSorted()&&b.sort();for(var T="",F=0,A=b.length;F1||i.length===1&&r)&&this.enableMultiselect();for(var l=new Array(i.length),d=0,c=i.length;d1||i.length===1&&r)&&this.enableMultiselect();for(var a=new Array(i.length),l=0,d=i.length;lr)throw new lce(t.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),t?this.acroField.setValue(dn.fromText(t)):this.acroField.removeValue()},e.prototype.getAlignment=function(){var t=this.acroField.getQuadding();return t===0?Os.Left:t===1?Os.Center:t===2?Os.Right:Os.Left},e.prototype.setAlignment=function(t){yg(t,"alignment",Os),this.markAsDirty(),this.acroField.setQuadding(t)},e.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},e.prototype.setMaxLength=function(t){if(nc(t,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),t===void 0)this.acroField.removeMaxLength();else{var r=this.getText();if(r&&r.length>t)throw new dce(r.length,t,this.getName());this.acroField.setMaxLength(t)}},e.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},e.prototype.setImage=function(t){for(var r=this.getAlignment(),i=r===Os.Center?Pg.Center:r===Os.Right?Pg.Right:Pg.Left,o=this.acroField.getWidgets(),a=0,l=o.length;anew Promise((e,t)=>{const r=new FileReader;r.addEventListener("load",({target:{result:i}})=>{const o=new DataView(i);let a=0;if(o.getUint16(a)!==65496)return t("not a valid JPEG");for(a+=2;;){const l=o.getUint16(a);if(l===65498)break;const d=o.getUint16(a+2);if(l===65505&&o.getUint32(a+4)===1165519206){const c=a+10;let u;switch(o.getUint16(c)){case 18761:u=!0;break;case 19789:u=!1;break;default:return t("TIFF header contains invalid endian")}if(o.getUint16(c+2,u)!==42)return t("TIFF header contains invalid version");const f=o.getUint32(c+4,u),p=c+f+2+12*o.getUint16(c+f,u);for(let g=c+f+2;g>>24&255,l[a+1]=d>>>16&255,l[a+2]=d>>>8&255,l[a+3]=d>>>0&255,new Uint8Array(l.buffer,0,a+4)},r.deflateRaw=function(i,o){o==null&&(o={level:6});var a=new Uint8Array(50+Math.floor(1.1*i.length)),l=r.F.deflateRaw(i,a,l,o.level);return new Uint8Array(a.buffer,0,l)},r.encode=function(i,o){o==null&&(o=!1);var a=0,l=r.bin.writeUint,d=r.bin.writeUshort,c={};for(var u in i){var f=!r._noNeed(u)&&!o,p=i[u],g=r.crc.crc(p,0,p.length);c[u]={cpr:f,usize:p.length,crc:g,file:f?r.deflateRaw(p):p}}for(var u in c)a+=c[u].file.length+30+46+2*r.bin.sizeUTF8(u);a+=22;var m=new Uint8Array(a),y=0,v=[];for(var u in c){var x=c[u];v.push(y),y=r._writeHeader(m,y,u,x,0)}var w=0,S=y;for(var u in c)x=c[u],v.push(y),y=r._writeHeader(m,y,u,x,1,v[w++]);var _=y-S;return l(m,y,101010256),y+=4,d(m,y+=4,w),d(m,y+=2,w),l(m,y+=2,_),l(m,y+=4,S),y+=4,y+=2,m.buffer},r._noNeed=function(i){var o=i.split(".").pop().toLowerCase();return"png,jpg,jpeg,zip".indexOf(o)!=-1},r._writeHeader=function(i,o,a,l,d,c){var u=r.bin.writeUint,f=r.bin.writeUshort,p=l.file;return u(i,o,d==0?67324752:33639248),o+=4,d==1&&(o+=2),f(i,o,20),f(i,o+=2,0),f(i,o+=2,l.cpr?8:0),u(i,o+=2,0),u(i,o+=4,l.crc),u(i,o+=4,p.length),u(i,o+=4,l.usize),f(i,o+=4,r.bin.sizeUTF8(a)),f(i,o+=2,0),o+=2,d==1&&(o+=2,o+=2,u(i,o+=6,c),o+=4),o+=r.bin.writeUTF8(i,o,a),d==0&&(i.set(p,o),o+=p.length),o},r.crc={table:function(){for(var i=new Uint32Array(256),o=0;o<256;o++){for(var a=o,l=0;l<8;l++)1&a?a=3988292384^a>>>1:a>>>=1;i[o]=a}return i}(),update:function(i,o,a,l){for(var d=0;d>>8;return i},crc:function(i,o,a){return 4294967295^r.crc.update(4294967295,i,o,a)}},r.adler=function(i,o,a){for(var l=1,d=0,c=o,u=o+a;c>8&255},readUint:function(i,o){return 16777216*i[o+3]+(i[o+2]<<16|i[o+1]<<8|i[o])},writeUint:function(i,o,a){i[o]=255&a,i[o+1]=a>>8&255,i[o+2]=a>>16&255,i[o+3]=a>>24&255},readASCII:function(i,o,a){for(var l="",d=0;d>6,i[o+d+1]=128|u>>0&63,d+=2;else if(!(4294901760&u))i[o+d]=224|u>>12,i[o+d+1]=128|u>>6&63,i[o+d+2]=128|u>>0&63,d+=3;else{if(4292870144&u)throw"e";i[o+d]=240|u>>18,i[o+d+1]=128|u>>12&63,i[o+d+2]=128|u>>6&63,i[o+d+3]=128|u>>0&63,d+=4}}return d},sizeUTF8:function(i){for(var o=i.length,a=0,l=0;l>>3}var v=c.lits,x=c.strt,w=c.prev,S=0,_=0,b=0,C=0,T=0,F=0;for(y>2&&(x[F=r.F._hash(i,0)]=0),p=0;p14e3||_>26697)&&y-p>100&&(m>>16,L=65535&D;if(D!=0){L=65535&D;var W=u(P=D>>>16,c.of0);c.lhst[257+W]++;var O=u(L,c.df0);c.dhst[O]++,C+=c.exb[W]+c.dxb[O],v[S]=P<<23|p-m,v[S+1]=L<<16|W<<8|O,S+=2,m=p+P}else c.lhst[i[p]]++;_++}}for(b==p&&i.length!=0||(m>>3},r.F._bestMatch=function(i,o,a,l,d,c){var u=32767&o,f=a[u],p=u-f+32768&32767;if(f==u||l!=r.F._hash(i,o-p))return 0;for(var g=0,m=0,y=Math.min(32767,o);p<=y&&--c!=0&&f!=u;){if(g==0||i[o+g]==i[o+g-p]){var v=r.F._howLong(i,o,p);if(v>g){if(m=p,(g=v)>=d)break;p+2x&&(x=_,f=S)}}}p+=(u=f)-(f=a[u])+32768&32767}return g<<16|m},r.F._howLong=function(i,o,a){if(i[o]!=i[o-a]||i[o+1]!=i[o+1-a]||i[o+2]!=i[o+2-a])return 0;var l=o,d=Math.min(i.length,o+258);for(o+=3;o>>23,te=I+(8388607&z);I>16,J=re>>8&255,ne=255&re;F(f,p=r.F._writeLit(257+J,O,f,p),G-C.of0[J]),p+=C.exb[J],T(f,p=r.F._writeLit(ne,U,f,p),me-C.df0[ne]),p+=C.dxb[ne],I+=G}}p=r.F._writeLit(256,O,f,p)}return p},r.F._copyExact=function(i,o,a,l,d){var c=d>>>3;return l[c]=a,l[c+1]=a>>>8,l[c+2]=255-l[c],l[c+3]=255-l[c+1],c+=4,l.set(new Uint8Array(i.buffer,o,a),c),d+(a+4<<3)},r.F.getTrees=function(){for(var i=r.F.U,o=r.F._hufTree(i.lhst,i.ltree,15),a=r.F._hufTree(i.dhst,i.dtree,15),l=[],d=r.F._lenCodes(i.ltree,l),c=[],u=r.F._lenCodes(i.dtree,c),f=0;f4&&i.itree[1+(i.ordr[g-1]<<1)]==0;)g--;return[o,a,p,d,u,g,l,c]},r.F.getSecond=function(i){for(var o=[],a=0;a>1)+",");return o},r.F.contSize=function(i,o){for(var a=0,l=0;l15&&(r.F._putsE(a,l,u,f),l+=f)}return l},r.F._lenCodes=function(i,o){for(var a=i.length;a!=2&&i[a-1]==0;)a-=2;for(var l=0;l>>1,138))<11?o.push(17,g-3):o.push(18,g-11),l+=2*g-2}else if(d==f&&c==d&&u==d){for(p=l+5;p+2>>1,6);o.push(16,g-3),l+=2*g-2}else o.push(d,0)}return a>>>1},r.F._hufTree=function(i,o,a){var l=[],d=i.length,c=o.length,u=0;for(u=0;ua&&(r.F.restrictDepth(p,a,S),S=a),u=0;uo;l++){var u=i[l].d;i[l].d=o,c+=d-(1<>>=a-o;c>0;)(u=i[l].d)=0;l--)i[l].d==o&&c<0&&(i[l].d--,c++);c!=0&&console.log("debt left")},r.F._goodIndex=function(i,o){var a=0;return o[16|a]<=i&&(a|=16),o[8|a]<=i&&(a|=8),o[4|a]<=i&&(a|=4),o[2|a]<=i&&(a|=2),o[1|a]<=i&&(a|=1),a},r.F._writeLit=function(i,o,a,l){return r.F._putsF(a,l,o[i<<1]),l+o[1+(i<<1)]},r.F.inflate=function(i,o){var a=Uint8Array;if(i[0]==3&&i[1]==0)return o||new a(0);var l=r.F,d=l._bitsF,c=l._bitsE,u=l._decodeTiny,f=l.makeCodes,p=l.codes2map,g=l._get17,m=l.U,y=o==null;y&&(o=new a(i.length>>>2<<3));for(var v,x,w=0,S=0,_=0,b=0,C=0,T=0,F=0,A=0,D=0;w==0;)if(w=d(i,D,1),S=d(i,D+1,2),D+=3,S!=0){if(y&&(o=r.F._check(o,A+(1<<17))),S==1&&(v=m.flmap,x=m.fdmap,T=511,F=31),S==2){_=c(i,D,5)+257,b=c(i,D+5,5)+1,C=c(i,D+10,4)+4,D+=14;for(var P=0;P<38;P+=2)m.itree[P]=0,m.itree[P+1]=0;var L=1;for(P=0;PL&&(L=W)}D+=3*C,f(m.itree,L),p(m.itree,L,m.imap),v=m.lmap,x=m.dmap,D=u(m.imap,(1<>>4;if(!(I>>>8))o[A++]=I;else{if(I==256)break;var H=A+I-254;if(I>264){var z=m.ldef[I-257];H=A+(z>>>3)+c(i,D,7&z),D+=7&z}var G=x[g(i,D)&F];D+=15&G;var te=G>>>4,re=m.ddef[te],me=(re>>>4)+d(i,D,15&re);for(D+=15&re,y&&(o=r.F._check(o,A+(1<<17)));A>>3),ne=i[J-4]|i[J-3]<<8;y&&(o=r.F._check(o,A+ne)),o.set(new a(i.buffer,i.byteOffset+J,ne),A),D=J+ne<<3,A+=ne}return o.length==A?o:o.slice(0,A)},r.F._check=function(i,o){var a=i.length;if(o<=a)return i;var l=new Uint8Array(Math.max(a<<1,o));return l.set(i,0),l},r.F._decodeTiny=function(i,o,a,l,d,c){for(var u=r.F._bitsE,f=r.F._get17,p=0;p>>4;if(m<=15)c[p]=m,p++;else{var y=0,v=0;m==16?(v=3+u(l,d,2),d+=2,y=c[p-1]):m==17?(v=3+u(l,d,3),d+=3):m==18&&(v=11+u(l,d,7),d+=7);for(var x=p+v;p>>1;cd&&(d=f),c++}for(;c>1,f=i[c+1],p=u<<4|f,g=o-f,m=i[c]<>>15-o]=p,m++},r.F.revCodes=function(i,o){for(var a=r.F.U.rev15,l=15-o,d=0;d>>l}},r.F._putsE=function(i,o,a){a<<=7&o;var l=o>>>3;i[l]|=a,i[l+1]|=a>>>8},r.F._putsF=function(i,o,a){a<<=7&o;var l=o>>>3;i[l]|=a,i[l+1]|=a>>>8,i[l+2]|=a>>>16},r.F._bitsE=function(i,o,a){return(i[o>>>3]|i[1+(o>>>3)]<<8)>>>(7&o)&(1<>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16)>>>(7&o)&(1<>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16)>>>(7&o)},r.F._get25=function(i,o){return(i[o>>>3]|i[1+(o>>>3)]<<8|i[2+(o>>>3)]<<16|i[3+(o>>>3)]<<24)>>>(7&o)},r.F.U=(e=Uint16Array,t=Uint32Array,{next_code:new e(16),bl_count:new e(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new e(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new t(32),flmap:new e(512),fltree:[],fdmap:new e(32),fdtree:[],lmap:new e(32768),ltree:[],ttree:[],dmap:new e(32768),dtree:[],imap:new e(512),itree:[],rev15:new e(32768),lhst:new t(286),dhst:new t(30),ihst:new t(19),lits:new t(15e3),strt:new e(65536),prev:new e(32768)}),function(){for(var i=r.F.U,o=0;o<32768;o++){var a=o;a=(4278255360&(a=(4042322160&(a=(3435973836&(a=(2863311530&a)>>>1|(1431655765&a)<<1))>>>2|(858993459&a)<<2))>>>4|(252645135&a)<<4))>>>8|(16711935&a)<<8,i.rev15[o]=(a>>>16|a<<16)>>>17}function l(d,c,u){for(;c--!=0;)d.push(0,u)}for(o=0;o<32;o++)i.ldef[o]=i.of0[o]<<3|i.exb[o],i.ddef[o]=i.df0[o]<<4|i.dxb[o];l(i.fltree,144,8),l(i.fltree,112,9),l(i.fltree,24,7),l(i.fltree,8,8),r.F.makeCodes(i.fltree,9),r.F.codes2map(i.fltree,9,i.flmap),r.F.revCodes(i.fltree,9),l(i.fdtree,32,5),r.F.makeCodes(i.fdtree,5),r.F.codes2map(i.fdtree,5,i.fdmap),r.F.revCodes(i.fdtree,5),l(i.itree,19,0),l(i.ltree,286,0),l(i.dtree,30,0),l(i.ttree,320,0)}()})();var Ece=Tce({__proto__:null,default:pT},[pT]);const rc=function(){var n={nextZero(u,f){for(;u[f]!=0;)f++;return f},readUshort:(u,f)=>u[f]<<8|u[f+1],writeUshort(u,f,p){u[f]=p>>8&255,u[f+1]=255&p},readUint:(u,f)=>16777216*u[f]+(u[f+1]<<16|u[f+2]<<8|u[f+3]),writeUint(u,f,p){u[f]=p>>24&255,u[f+1]=p>>16&255,u[f+2]=p>>8&255,u[f+3]=255&p},readASCII(u,f,p){let g="";for(let m=0;mu.length<2?`0${u}`:u,readUTF8(u,f,p){let g,m="";for(let y=0;y>3)]>>7-((7&C)<<0)&1);x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O>2)]>>6-((3&C)<<1)&3),x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O>1)]>>4-((1&C)<<2)&15),x[A]=z[W],x[A+1]=z[W+1],x[A+2]=z[W+2],x[A+3]=O>>3)]>>>7-(7&I)&1))==255*F?0:255;w[G+I]=H<<24|U<<16|U<<8|U}else if(_==2)for(I=0;I>>2)]>>>6-((3&I)<<1)&3))==85*F?0:255,w[G+I]=H<<24|U<<16|U<<8|U;else if(_==4)for(I=0;I>>1)]>>>4-((1&I)<<2)&15))==17*F?0:255,w[G+I]=H<<24|U<<16|U<<8|U;else if(_==8)for(I=0;I>3,F=Math.ceil(_*C/8),A=new Uint8Array(b*F);let D=0;const P=[0,0,4,0,2,0,1],L=[0,4,0,2,0,1,0],W=[8,8,8,4,4,2,2],O=[8,8,4,4,2,2,1];let U=0;for(;U<7;){const I=W[U],H=O[U];let z=0,G=0,te=P[U];for(;te>3])>>7-(7&ke)&1,A[ne*F+(ye>>3)]|=M<<7-((7&ye)<<0)),C==2&&(M=(M=w[ke>>3])>>6-(7&ke)&3,A[ne*F+(ye>>2)]|=M<<6-((3&ye)<<1)),C==4&&(M=(M=w[ke>>3])>>4-(7&ke)&15,A[ne*F+(ye>>1)]|=M<<4-((1&ye)<<2)),C>=8){const Ye=ne*F+ye*T;for(let De=0;De>3)+De]}ke+=C,ye+=H}J++,ne+=I}z*G!=0&&(D+=G*(1+me)),U+=1}return A}(f,u)),f}function r(u,f){return i(new Uint8Array(u.buffer,2,u.length-6),f)}var i=function(){const u={H:{}};return u.H.N=function(f,p){const g=Uint8Array;let m,y,v=0,x=0,w=0,S=0,_=0,b=0,C=0,T=0,F=0;if(f[0]==3&&f[1]==0)return p||new g(0);const A=u.H,D=A.b,P=A.e,L=A.R,W=A.n,O=A.A,U=A.Z,M=A.m,I=p==null;for(I&&(p=new g(f.length>>>2<<5));v==0;)if(v=D(f,F,1),x=D(f,F+1,2),F+=3,x!=0){if(I&&(p=u.H.W(p,T+(1<<17))),x==1&&(m=M.J,y=M.h,b=511,C=31),x==2){w=P(f,F,5)+257,S=P(f,F+5,5)+1,_=P(f,F+10,4)+4,F+=14;let z=1;for(var H=0;H<38;H+=2)M.Q[H]=0,M.Q[H+1]=0;for(H=0;H<_;H++){const re=P(f,F+3*H,3);M.Q[1+(M.X[H]<<1)]=re,re>z&&(z=re)}F+=3*_,W(M.Q,z),O(M.Q,z,M.u),m=M.w,y=M.d,F=L(M.u,(1<>>4;if(!(G>>>8))p[T++]=G;else{if(G==256)break;{let te=T+G-254;if(G>264){const ye=M.q[G-257];te=T+(ye>>>3)+P(f,F,7&ye),F+=7&ye}const re=y[U(f,F)&C];F+=15&re;const me=re>>>4,J=M.c[me],ne=(J>>>4)+D(f,F,15&J);for(F+=15&J;T>>3),G=f[z-4]|f[z-3]<<8;I&&(p=u.H.W(p,T+G)),p.set(new g(f.buffer,f.byteOffset+z,G),T),F=z+G<<3,T+=G}return p.length==T?p:p.slice(0,T)},u.H.W=function(f,p){const g=f.length;if(p<=g)return f;const m=new Uint8Array(g<<1);return m.set(f,0),m},u.H.R=function(f,p,g,m,y,v){const x=u.H.e,w=u.H.Z;let S=0;for(;S>>4;if(b<=15)v[S]=b,S++;else{let C=0,T=0;b==16?(T=3+x(m,y,2),y+=2,C=v[S-1]):b==17?(T=3+x(m,y,3),y+=3):b==18&&(T=11+x(m,y,7),y+=7);const F=S+T;for(;S>>1;for(;vy&&(y=w),v++}for(;v>1,w=f[v+1],S=x<<4|w,_=p-w;let b=f[v]<<_;const C=b+(1<<_);for(;b!=C;)g[y[b]>>>15-p]=S,b++}},u.H.l=function(f,p){const g=u.H.m.r,m=15-p;for(let y=0;y>>m}},u.H.M=function(f,p,g){g<<=7&p;const m=p>>>3;f[m]|=g,f[m+1]|=g>>>8},u.H.I=function(f,p,g){g<<=7&p;const m=p>>>3;f[m]|=g,f[m+1]|=g>>>8,f[m+2]|=g>>>16},u.H.e=function(f,p,g){return(f[p>>>3]|f[1+(p>>>3)]<<8)>>>(7&p)&(1<>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16)>>>(7&p)&(1<>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16)>>>(7&p)},u.H.i=function(f,p){return(f[p>>>3]|f[1+(p>>>3)]<<8|f[2+(p>>>3)]<<16|f[3+(p>>>3)]<<24)>>>(7&p)},u.H.m=function(){const f=Uint16Array,p=Uint32Array;return{K:new f(16),j:new f(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new f(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new p(32),J:new f(512),_:[],h:new f(32),$:[],w:new f(32768),C:[],v:[],d:new f(32768),D:[],u:new f(512),Q:[],r:new f(32768),s:new p(286),Y:new p(30),a:new p(19),t:new p(15e3),k:new f(65536),g:new f(32768)}}(),function(){const f=u.H.m;for(var p=0;p<32768;p++){let m=p;m=(2863311530&m)>>>1|(1431655765&m)<<1,m=(3435973836&m)>>>2|(858993459&m)<<2,m=(4042322160&m)>>>4|(252645135&m)<<4,m=(4278255360&m)>>>8|(16711935&m)<<8,f.r[p]=(m>>>16|m<<16)>>>17}function g(m,y,v){for(;y--!=0;)m.push(0,v)}for(p=0;p<32;p++)f.q[p]=f.S[p]<<3|f.T[p],f.c[p]=f.p[p]<<4|f.z[p];g(f._,144,8),g(f._,112,9),g(f._,24,7),g(f._,8,8),u.H.n(f._,9),u.H.A(f._,9,f.J),u.H.l(f._,9),g(f.$,32,5),u.H.n(f.$,5),u.H.A(f.$,5,f.h),u.H.l(f.$,5),g(f.Q,19,0),g(f.C,286,0),g(f.D,30,0),g(f.v,320,0)}(),u.H.N}();function o(u){return[1,null,3,1,2,null,4][u.ctype]*u.depth}function a(u,f,p,g,m){let y=o(f);const v=Math.ceil(g*y/8);let x,w;y=Math.ceil(y/8);let S=u[p],_=0;if(S>1&&(u[p]=[0,0,1][S-2]),S==3)for(_=y;_>>1)&255;for(let b=0;b>>1);for(;_>>1)}else{for(;_=0&&x>=0?(b=U*f+M<<2,C=(x+U)*m+v+M<<2):(b=(-x+U)*f-v+M<<2,C=U*m+M<<2),w==0)g[C]=u[b],g[C+1]=u[b+1],g[C+2]=u[b+2],g[C+3]=u[b+3];else if(w==1){var T=u[b+3]*.00392156862745098,F=u[b]*T,A=u[b+1]*T,D=u[b+2]*T,P=g[C+3]*(1/255),L=g[C]*P,W=g[C+1]*P,O=g[C+2]*P;const I=1-T,H=T+P*I,z=H==0?0:1/H;g[C+3]=255*H,g[C+0]=(F+L*I)*z,g[C+1]=(A+W*I)*z,g[C+2]=(D+O*I)*z}else if(w==2)T=u[b+3],F=u[b],A=u[b+1],D=u[b+2],P=g[C+3],L=g[C],W=g[C+1],O=g[C+2],T==P&&F==L&&A==W&&D==O?(g[C]=0,g[C+1]=0,g[C+2]=0,g[C+3]=0):(g[C]=F,g[C+1]=A,g[C+2]=D,g[C+3]=T);else if(w==3){if(T=u[b+3],F=u[b],A=u[b+1],D=u[b+2],P=g[C+3],L=g[C],W=g[C+1],O=g[C+2],T==P&&F==L&&A==W&&D==O)continue;if(T<220&&P>20)return!1}return!0}return{decode:function(f){const p=new Uint8Array(f);let g=8;const m=n,y=m.readUshort,v=m.readUint,x={tabs:{},frames:[]},w=new Uint8Array(p.length);let S,_=0,b=0;const C=[137,80,78,71,13,10,26,10];for(var T=0;T<8;T++)if(p[T]!=C[T])throw"The input is not a PNG file!";for(;g>>1:D>>>=1;F[A]=D}return F}(),update(F,A,D,P){for(let L=0;L>>8;return F},crc:(F,A,D)=>4294967295^r.update(4294967295,F,A,D)};function i(F,A,D,P){A[D]+=F[0]*P>>4,A[D+1]+=F[1]*P>>4,A[D+2]+=F[2]*P>>4,A[D+3]+=F[3]*P>>4}function o(F){return Math.max(0,Math.min(255,F))}function a(F,A){const D=F[0]-A[0],P=F[1]-A[1],L=F[2]-A[2],W=F[3]-A[3];return D*D+P*P+L*L+W*W}function l(F,A,D,P,L,W,O){O==null&&(O=1);const U=P.length,M=[];for(var I=0;I>>0&255,ne>>>8&255,ne>>>16&255,ne>>>24&255])}for(I=0;I>2]=H,te[I>>2]=P[H]}}function d(F,A,D,P,L){L==null&&(L={});const{crc:W}=r,O=e.writeUint,U=e.writeUshort,M=e.writeASCII;let I=8;const H=F.frames.length>1;let z,G=!1,te=33+(H?20:0);if(L.sRGB!=null&&(te+=13),L.pHYs!=null&&(te+=21),L.iCCP!=null&&(z=pako.deflate(L.iCCP),te+=21+z.length+4),F.ctype==3){for(var re=F.plte.length,me=0;me>>24!=255&&(G=!0);te+=8+3*re+4+(G?8+1*re+4:0)}for(var J=0;J>>8&255,ee=qe>>>16&255;ne[I+De+0]=ue,ne[I+De+1]=Ze,ne[I+De+2]=ee}if(I+=3*re,O(ne,I,W(ne,I-3*re-4,3*re+4)),I+=4,G){for(O(ne,I,re),I+=4,M(ne,I,"tRNS"),I+=4,me=0;me>>24&255;I+=re,O(ne,I,W(ne,I-re-4,re+4)),I+=4}}let ke=0;for(J=0;JAn&&(An=vt),Rton&&(on=Rt));An==-1&&(ut=Ot=An=on=0),ae&&((1&ut)==1&&ut--,(1&Ot)==1&&Ot--);const Ke=(An-ut+1)*(on-Ot+1);Ke>2,Ge>>2);De.push(qe);const ae=new Uint8Array(he.abuf,He,Ge);H&&l(ue.img,ue.rect.width,ue.rect.height,Ye,ae,qe),ue.img.set(ae),He+=Ge}}else for(re=0;reZe&&Be==Te[J-Ze])qe[J]=qe[J-Ze];else{let he=ke[Be];if(he==null&&(ke[Be]=he=Ye.length,Ye.push(Be),Ye.length>=300))break;qe[J]=he}}}const ee=Ye.length;for(ee<=256&&I==0&&(G=ee<=2?1:ee<=4?2:ee<=16?4:8,G=Math.max(G,M)),re=0;re>1)]|=Ge[K+ge]<<4-4*(1&ge);else if(G==2)for(ge=0;ge>2)]|=Ge[K+ge]<<6-2*(3&ge);else if(G==1)for(ge=0;ge>3)]|=Ge[K+ge]<<7-1*(7&ge)}Be=Z,z=3,He=1}else if(ne==0&&ye.length==1){Z=new Uint8Array(Ze*Te*3);const Ge=Ze*Te;for(J=0;JJ&&(J=De),qene&&(ne=qe))}J==-1&&(re=me=J=ne=0),O&&((1&re)==1&&re--,(1&me)==1&&me--),W={x:re,y:me,width:J-re+1,height:ne-me+1};const ye=P[L];ye.rect=W,ye.blend=1,ye.img=new Uint8Array(W.width*W.height*4),P[L-1].dispose==0?(n(I,A,D,ye.img,W.width,W.height,-W.x,-W.y,0),p(G,A,D,ye.img,W)):n(G,A,D,ye.img,W.width,W.height,-W.x,-W.y,0)}function p(F,A,D,P,L){n(F,A,D,P,L.width,L.height,-L.x,-L.y,2)}function g(F,A,D,P,L,W,O){const U=[];let M,I=[0,1,2,3,4];W!=-1?I=[W]:(A*P>5e5||D==1)&&(I=[0]),O&&(M={level:0});const H=Ece;for(var z=0;z>1)+256&255;if(W==4)for(M=L;M>1)&255;for(M=L;M>1)&255}if(W==4){for(M=0;M>2);let H;if(D.length<2e7)for(var z=0;z>2]=H.ind,L[z>>2]=H.est.rgba;else for(z=0;z>2]=H.ind,L[z>>2]=H.est.rgba}return{abuf:P.buffer,inds:I,plte:U}}function v(F,A,D){D==null&&(D=1e-4);const P=new Uint32Array(F.buffer),L={i0:0,i1:F.length,bst:null,est:null,tdst:0,left:null,right:null};L.bst=b(F,L.i0,L.i1),L.est=C(L.bst);const W=[L];for(;W.lengthU&&(U=W[O].est.L,M=O);if(U=H||I.i1<=H){I.est.L=0;continue}const z={i0:I.i0,i1:H,bst:null,est:null,tdst:0,left:null,right:null};z.bst=b(F,z.i0,z.i1),z.est=C(z.bst);const G={i0:H,i1:I.i1,bst:null,est:null,tdst:0,left:null,right:null};for(G.bst={R:[],m:[],N:I.bst.N-z.bst.N},O=0;O<16;O++)G.bst.R[O]=I.bst.R[O]-z.bst.R[O];for(O=0;O<4;O++)G.bst.m[O]=I.bst.m[O]-z.bst.m[O];G.est=C(G.bst),I.left=z,I.right=G,W[M]=z,W.push(G)}for(W.sort((U,M)=>M.bst.N-U.bst.N),O=0;O0&&(O=F.right,U=F.left);const M=x(O,A,D,P,L);if(M.tdst<=W*W)return M;const I=x(U,A,D,P,L);return I.tdstW;)P-=4;if(D>=P)break;const O=A[D>>2];A[D>>2]=A[P>>2],A[P>>2]=O,D+=4,P-=4}for(;_(F,D,L)>W;)D-=4;return D+4}function _(F,A,D){return F[A]*D[0]+F[A+1]*D[1]+F[A+2]*D[2]+F[A+3]*D[3]}function b(F,A,D){const P=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],L=[0,0,0,0],W=D-A>>2;for(let O=A;O>>0}}var T={multVec:(F,A)=>[F[0]*A[0]+F[1]*A[1]+F[2]*A[2]+F[3]*A[3],F[4]*A[0]+F[5]*A[1]+F[6]*A[2]+F[7]*A[3],F[8]*A[0]+F[9]*A[1]+F[10]*A[2]+F[11]*A[3],F[12]*A[0]+F[13]*A[1]+F[14]*A[2]+F[15]*A[3]],dot:(F,A)=>F[0]*A[0]+F[1]*A[1]+F[2]*A[2]+F[3]*A[3],sml:(F,A)=>[F*A[0],F*A[1],F*A[2],F*A[3]]};rc.encode=function(A,D,P,L,W,O,U){L==null&&(L=0),U==null&&(U=!1);const M=u(A,D,P,L,[!1,!1,!1,0,U,!1]);return c(M,-1),d(M,D,P,W,O)},rc.encodeLL=function(A,D,P,L,W,O,U,M){const I={ctype:0+(L==1?0:2)+(W==0?0:4),depth:O,frames:[]},H=(L+W)*O,z=H*D;for(let G=0;G>>0),b(1),b(32),C(3),C(d),C(2835),C(2835),T(8),C(16711680),C(65280),C(255),C(4278190080),C(1466527264),function F(){for(;w0;){for(v=122+w*l,g=0;g>>24,f.setUint32(v+g,m<<8|y),g+=4;w++}_{e(new Blob([t],{type:"image/bmp"}))})},_dly:9};var $a={CHROME:"CHROME",FIREFOX:"FIREFOX",DESKTOP_SAFARI:"DESKTOP_SAFARI",IE:"IE",IOS:"IOS",ETC:"ETC"},Pce={[$a.CHROME]:16384,[$a.FIREFOX]:11180,[$a.DESKTOP_SAFARI]:16384,[$a.IE]:8192,[$a.IOS]:4096,[$a.ETC]:8192};const A3=typeof window<"u",Zq=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,gT=A3&&window.cordova&&window.cordova.require&&window.cordova.require("cordova/modulemapper"),Rce=(A3||Zq)&&(gT&&gT.getOriginalSymbol(window,"File")||typeof File<"u"&&File),Jq=(A3||Zq)&&(gT&&gT.getOriginalSymbol(window,"FileReader")||typeof FileReader<"u"&&FileReader);function T3(n,e,t=Date.now()){return new Promise(r=>{const i=n.split(","),o=i[0].match(/:(.*?);/)[1],a=globalThis.atob(i[1]);let l=a.length;const d=new Uint8Array(l);for(;l--;)d[l]=a.charCodeAt(l);const c=new Blob([d],{type:o});c.name=e,c.lastModified=t,r(c)})}function eV(n){return new Promise((e,t)=>{const r=new Jq;r.onload=()=>e(r.result),r.onerror=i=>t(i),r.readAsDataURL(n)})}function tV(n){return new Promise((e,t)=>{const r=new Image;r.onload=()=>e(r),r.onerror=i=>t(i),r.src=n})}function km(){if(km.cachedResult!==void 0)return km.cachedResult;let n=$a.ETC;const{userAgent:e}=navigator;return/Chrom(e|ium)/i.test(e)?n=$a.CHROME:/iP(ad|od|hone)/i.test(e)&&/WebKit/i.test(e)?n=$a.IOS:/Safari/i.test(e)?n=$a.DESKTOP_SAFARI:/Firefox/i.test(e)?n=$a.FIREFOX:(/MSIE/i.test(e)||document.documentMode)&&(n=$a.IE),km.cachedResult=n,km.cachedResult}function nV(n,e){const t=km(),r=Pce[t];let i=n,o=e,a=i*o;const l=i>o?o/i:i/o;for(;a>r*r;){const d=(r+i)/2,c=(r+o)/2;d$q.toBlob(n,u)).then((function(u){try{return l=u,l.name=t,l.lastModified=r,c.call(this)}catch(f){return a(f)}}).bind(this),a);{let u=function(){return c.call(this)};if(typeof OffscreenCanvas=="function"&&n instanceof OffscreenCanvas)return n.convertToBlob({type:e,quality:i}).then((function(f){try{return l=f,l.name=t,l.lastModified=r,u.call(this)}catch(p){return a(p)}}).bind(this),a);{let f;return f=n.toDataURL(e,i),T3(f,t,r).then((function(p){try{return l=p,u.call(this)}catch(g){return a(g)}}).bind(this),a)}}}function d(){return o(l)}})}function _u(n){n.width=0,n.height=0}function Xx(){return new Promise(function(n,e){let t,r,i,o;return Xx.cachedResult!==void 0?n(Xx.cachedResult):T3("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAEAAgMBEQACEQEDEQH/xABKAAEAAAAAAAAAAAAAAAAAAAALEAEAAAAAAAAAAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAAAAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/8H//2Q==","test.jpg",Date.now()).then(function(a){try{return t=a,mT(t).then(function(l){try{return r=l[1],yT(r,t.type,t.name,t.lastModified).then(function(d){try{return i=d,_u(r),mT(i).then(function(c){try{return o=c[0],Xx.cachedResult=o.width===1&&o.height===2,n(Xx.cachedResult)}catch(u){return e(u)}},e)}catch(c){return e(c)}},e)}catch(d){return e(d)}},e)}catch(l){return e(l)}},e)})}function iV(n){return new Promise((e,t)=>{const r=new Jq;r.onload=i=>{const o=new DataView(i.target.result);if(o.getUint16(0,!1)!=65496)return e(-2);const a=o.byteLength;let l=2;for(;lt(i),r.readAsArrayBuffer(n)})}function sV(n,e){const{width:t}=n,{height:r}=n,{maxWidthOrHeight:i}=e;let o,a=n;return isFinite(i)&&(t>i||r>i)&&([a,o]=JF(t,r),t>r?(a.width=i,a.height=r/t*i):(a.width=t/r*i,a.height=i),o.drawImage(n,0,0,a.width,a.height),_u(n)),a}function oV(n,e){const{width:t}=n,{height:r}=n,[i,o]=JF(t,r);switch(e>4&&e<9?(i.width=r,i.height=t):(i.width=t,i.height=r),e){case 2:o.transform(-1,0,0,1,t,0);break;case 3:o.transform(-1,0,0,-1,t,r);break;case 4:o.transform(1,0,0,-1,0,r);break;case 5:o.transform(0,1,1,0,0,0);break;case 6:o.transform(0,1,-1,0,r,0);break;case 7:o.transform(0,-1,-1,0,r,t);break;case 8:o.transform(0,-1,1,0,0,t)}return o.drawImage(n,0,0,t,r),_u(n),i}function oN(n,e,t=0){return new Promise(function(r,i){let o,a,l,d,c,u,f,p,g,m,y,v,x,w,S,_,b,C,T,F;function A(P=5){if(e.signal&&e.signal.aborted)throw e.signal.reason;o+=P,e.onProgress(Math.min(o,100))}function D(P){if(e.signal&&e.signal.aborted)throw e.signal.reason;o=Math.min(Math.max(P,o),100),e.onProgress(o)}return o=t,a=e.maxIteration||10,l=1024*e.maxSizeMB*1024,A(),mT(n,e).then((function(P){try{return[,d]=P,A(),c=sV(d,e),A(),new Promise(function(L,W){var O;if(!(O=e.exifOrientation))return iV(n).then((function(M){try{return O=M,U.call(this)}catch(I){return W(I)}}).bind(this),W);function U(){return L(O)}return U.call(this)}).then((function(L){try{return u=L,A(),Xx().then((function(W){try{return f=W?c:oV(c,u),A(),p=e.initialQuality||1,g=e.fileType||n.type,yT(f,g,n.name,n.lastModified,p).then((function(O){try{{let M=function(){if(a--&&(S>l||S>x)){let H,z;return H=F?.95*T.width:T.width,z=F?.95*T.height:T.height,[b,C]=JF(H,z),C.drawImage(T,0,0,H,z),p*=g==="image/png"?.85:.95,yT(b,g,n.name,n.lastModified,p).then(function(G){try{return _=G,_u(T),T=b,S=_.size,D(Math.min(99,Math.floor((w-S)/(w-l)*100))),M}catch(te){return i(te)}},i)}return[1]},I=function(){return _u(T),_u(b),_u(c),_u(f),_u(d),D(100),r(_)};if(m=O,A(),y=m.size>l,v=m.size>n.size,!y&&!v)return D(100),r(m);var U;return x=n.size,w=m.size,S=w,T=f,F=!e.alwaysKeepResolution&&y,(U=(function(H){for(;H;){if(H.then)return void H.then(U,i);try{if(H.pop){if(H.length)return H.pop()?I.call(this):H;H=M}else H=H.call(this)}catch(z){return i(z)}}}).bind(this))(M)}}catch(M){return i(M)}}).bind(this),i)}catch(O){return i(O)}}).bind(this),i)}catch(W){return i(W)}}).bind(this),i)}catch(L){return i(L)}}).bind(this),i)})}const Bce=` -let scriptImported = false -self.addEventListener('message', async (e) => { - const { file, id, imageCompressionLibUrl, options } = e.data - options.onProgress = (progress) => self.postMessage({ progress, id }) - try { - if (!scriptImported) { - // console.log('[worker] importScripts', imageCompressionLibUrl) - self.importScripts(imageCompressionLibUrl) - scriptImported = true - } - // console.log('[worker] self', self) - const compressedFile = await imageCompression(file, options) - self.postMessage({ file: compressedFile, id }) - } catch (e) { - // console.error('[worker] error', e) - self.postMessage({ error: e.message + '\\n' + e.stack, id }) - } -}) -`;let zP;function Ice(n,e){return new Promise((t,r)=>{zP||(zP=function(a){const l=[];return l.push(a),URL.createObjectURL(new Blob(l))}(Bce));const i=new Worker(zP);i.addEventListener("message",function(a){if(e.signal&&e.signal.aborted)i.terminate();else if(a.data.progress===void 0){if(a.data.error)return r(new Error(a.data.error)),void i.terminate();t(a.data.file),i.terminate()}else e.onProgress(a.data.progress)}),i.addEventListener("error",r),e.signal&&e.signal.addEventListener("abort",()=>{r(e.signal.reason),i.terminate()}),i.postMessage({file:n,imageCompressionLibUrl:e.libURL,options:{...e,onProgress:void 0,signal:void 0}})})}function bo(n,e){return new Promise(function(t,r){let i,o,a,l,d,c;if(i={...e},a=0,{onProgress:l}=i,i.maxSizeMB=i.maxSizeMB||Number.POSITIVE_INFINITY,d=typeof i.useWebWorker!="boolean"||i.useWebWorker,delete i.useWebWorker,i.onProgress=g=>{a=g,typeof l=="function"&&l(a)},!(n instanceof Blob||n instanceof Rce))return r(new Error("The file given is not an instance of Blob or File"));if(!/^image/.test(n.type))return r(new Error("The file given is not an image"));if(c=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,!d||typeof Worker!="function"||c)return oN(n,i).then((function(g){try{return o=g,p.call(this)}catch(m){return r(m)}}).bind(this),r);var u=(function(){try{return p.call(this)}catch(g){return r(g)}}).bind(this),f=function(g){try{return oN(n,i).then(function(m){try{return o=m,u()}catch(y){return r(y)}},r)}catch(m){return r(m)}};try{return i.libURL=i.libURL||"https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js",Ice(n,i).then(function(g){try{return o=g,u()}catch{return f()}},f)}catch{f()}function p(){try{o.name=n.name,o.lastModified=n.lastModified}catch{}try{i.preserveExif&&n.type==="image/jpeg"&&(!i.fileType||i.fileType&&i.fileType===n.type)&&(o=Qq(n,o))}catch{}return t(o)}})}bo.getDataUrlFromFile=eV,bo.getFilefromDataUrl=T3,bo.loadImage=tV,bo.drawImageInCanvas=rV,bo.drawFileInCanvas=mT,bo.canvasToFile=yT,bo.getExifOrientation=iV,bo.handleMaxWidthOrHeight=sV,bo.followExifOrientation=oV,bo.cleanupCanvasMemory=_u,bo.isAutoOrientationInBrowser=Xx,bo.approximateBelowMaximumCanvasSizeOfBrowser=nV,bo.copyExifWithoutOrientation=Qq,bo.getBrowserName=km,bo.version="2.0.2";function Mce(){const{token:n,user:e,login:t,logout:r}=gn(),i=k.useRef(null),o=k.useRef(null),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState(""),[p,g]=k.useState(!1),[m,y]=k.useState([]),[v,x]=k.useState([]);k.useEffect(()=>{const A=document.querySelector('meta[name="viewport"]'),D=(A==null?void 0:A.getAttribute("content"))||"";return A&&A.setAttribute("content","width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"),()=>{A&&D&&A.setAttribute("content",D)}},[]);const w=async A=>{A.preventDefault(),f(""),g(!0);try{const D=await fetch("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:a,password:d})});if(!D.ok){const L=await D.json();throw new Error(L.detail||"Login failed")}const P=await D.json();t(P.access_token)}catch(D){f(D instanceof Error?D.message:"Login failed")}finally{g(!1)}};if(!n||!e)return s.jsx("div",{style:wr.container,children:s.jsxs("div",{style:wr.loginCard,children:[s.jsx("h1",{style:wr.brand,children:"Invoice Upload"}),s.jsx("p",{style:wr.subtitle,children:"Sign in to upload invoices"}),u&&s.jsx("div",{style:wr.error,children:u}),s.jsxs("form",{onSubmit:w,style:wr.form,children:[s.jsx("input",{type:"email",placeholder:"Email",value:a,onChange:A=>l(A.target.value),style:wr.input,required:!0,autoFocus:!0}),s.jsx("input",{type:"password",placeholder:"Password",value:d,onChange:A=>c(A.target.value),style:wr.input,required:!0}),s.jsx("button",{type:"submit",style:wr.loginBtn,disabled:p,children:p?"Signing in...":"Sign In"})]})]})});const S=()=>Math.random().toString(36).substr(2,9),_=async A=>{if(!A.target.files||A.target.files.length===0)return;const D=Array.from(A.target.files);for(const P of D){if(P.type==="application/pdf"){C(P);continue}if(!P.type.startsWith("image/"))continue;const L=await new Promise(W=>{const O=new FileReader;O.onload=U=>{var M;return W((M=U.target)==null?void 0:M.result)},O.readAsDataURL(P)});x(W=>[...W,{id:S(),file:P,preview:L}])}A.target.value=""},b=A=>{x(D=>D.filter(P=>P.id!==A))},C=async A=>{const D=S();y(P=>[...P,{id:D,status:"uploading"}]);try{const P=new FormData;P.append("file",A),y(W=>W.map(O=>O.id===D?{...O,status:"processing"}:O));const L=await fetch("/api/invoices/upload",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:P});if(!L.ok){const W=await L.json();throw new Error(W.detail||"Upload failed")}y(W=>W.map(O=>O.id===D?{...O,status:"complete"}:O)),setTimeout(()=>{y(W=>W.filter(O=>O.id!==D))},3e3)}catch(P){y(L=>L.map(W=>W.id===D?{...W,status:"error",error:P instanceof Error?P.message:"Upload failed"}:W))}},T=async()=>{var L;if(v.length===0)return;const A=S(),D=(L=v[0])==null?void 0:L.preview,P=v.length;y(W=>[...W,{id:A,status:"compressing",preview:D}]),x([]);try{const W=[];for(const z of v){const G=await bo(z.file,{maxSizeMB:1,maxWidthOrHeight:2e3,useWebWorker:!0,fileType:"image/jpeg",initialQuality:.85}),te=new Image,re=URL.createObjectURL(G);await new Promise(me=>{te.onload=()=>{URL.revokeObjectURL(re),me()},te.src=re}),W.push({data:await G.arrayBuffer(),width:te.width,height:te.height})}y(z=>z.map(G=>G.id===A?{...G,status:"uploading"}:G));const O=await Af.create();for(const{data:z,width:G,height:te}of W){const re=await O.embedJpg(z);O.addPage([G,te]).drawImage(re,{x:0,y:0,width:G,height:te})}const U=await O.save(),M=new File([new Blob([U],{type:"application/pdf"})],`invoice-${P}pages.pdf`,{type:"application/pdf"});y(z=>z.map(G=>G.id===A?{...G,status:"processing"}:G));const I=new FormData;I.append("file",M);const H=await fetch("/api/invoices/upload",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:I});if(!H.ok){const z=await H.json();throw new Error(z.detail||"Upload failed")}y(z=>z.map(G=>G.id===A?{...G,status:"complete"}:G)),setTimeout(()=>{y(z=>z.filter(G=>G.id!==A))},3e3)}catch(W){y(O=>O.map(U=>U.id===A?{...U,status:"error",error:W instanceof Error?W.message:"Failed"}:U))}},F=m.some(A=>A.status==="compressing"||A.status==="uploading"||A.status==="processing");return s.jsx("div",{style:wr.container,children:s.jsxs("div",{style:wr.app,children:[s.jsxs("div",{style:wr.header,children:[s.jsxs("div",{children:[s.jsx("div",{style:wr.brandSmall,children:"Invoice Upload"}),s.jsx("div",{style:wr.kitchenName,children:e.kitchen_name})]}),s.jsx("button",{onClick:r,style:wr.logoutBtn,children:"Sign Out"})]}),m.length>0&&s.jsx("div",{style:wr.queueArea,children:m.map(A=>s.jsxs("div",{style:{...wr.queueItem,borderLeftColor:A.status==="complete"?"#4caf50":A.status==="error"?"#f44336":"#2196f3"},children:[s.jsxs("span",{style:wr.queueText,children:[A.status==="compressing"&&"Compressing...",A.status==="uploading"&&"Uploading...",A.status==="processing"&&"Processing OCR...",A.status==="complete"&&"Uploaded successfully",A.status==="error"&&(A.error||"Upload failed")]}),(A.status==="compressing"||A.status==="uploading"||A.status==="processing")&&s.jsx("div",{style:wr.spinner})]},A.id))}),v.length===0?s.jsxs("div",{style:wr.captureArea,children:[s.jsxs("button",{onClick:()=>{var A;return(A=i.current)==null?void 0:A.click()},style:wr.cameraBtn,disabled:F,children:[s.jsx("span",{style:wr.cameraIcon,children:"📷"}),s.jsx("span",{children:"Take Photo"})]}),s.jsx("button",{onClick:()=>{var A;return(A=o.current)==null?void 0:A.click()},style:wr.fileBtn,disabled:F,children:"Choose File / PDF"}),s.jsx("input",{ref:i,type:"file",accept:"image/*",capture:"environment",onChange:_,style:{display:"none"}}),s.jsx("input",{ref:o,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:_,style:{display:"none"}})]}):s.jsxs("div",{style:wr.reviewArea,children:[s.jsxs("div",{style:wr.previewGrid,children:[v.map((A,D)=>s.jsxs("div",{style:wr.previewCard,children:[s.jsx("img",{src:A.preview,alt:`Page ${D+1}`,style:wr.previewImg}),s.jsx("button",{onClick:()=>b(A.id),style:wr.removeBtn,disabled:F,children:"×"}),s.jsxs("div",{style:wr.pageLabel,children:["Page ",D+1]})]},A.id)),s.jsxs("button",{onClick:()=>{var A;return(A=i.current)==null?void 0:A.click()},style:wr.addPageCard,disabled:F,children:[s.jsx("span",{style:{fontSize:"2.5rem"},children:"📷"}),s.jsx("span",{style:{fontSize:"0.8rem",fontWeight:500},children:"Add Page"})]})]}),s.jsx("div",{style:wr.actionBar,children:s.jsx("button",{onClick:()=>x([]),style:wr.clearBtn,disabled:F,children:"Clear All"})}),s.jsx("button",{onClick:T,style:{...wr.uploadBtn,...F?{opacity:.6,cursor:"wait"}:{}},disabled:F,children:F?"Processing...":`Upload ${v.length} Page${v.length!==1?"s":""}`}),s.jsx("input",{ref:i,type:"file",accept:"image/*",capture:"environment",onChange:_,style:{display:"none"}}),s.jsx("input",{ref:o,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:_,style:{display:"none"}})]})]})})}const wr={container:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"#1a1a2e",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"},app:{width:"100%",maxWidth:"500px",height:"100%",display:"flex",flexDirection:"column",background:"#16213e",overflow:"auto"},loginCard:{background:"white",padding:"2rem",borderRadius:"12px",width:"90%",maxWidth:"360px",textAlign:"center"},brand:{color:"#1a1a2e",marginBottom:"0.25rem",fontSize:"1.4rem"},subtitle:{color:"#666",marginBottom:"1.5rem",fontSize:"0.9rem"},error:{background:"#fee",color:"#c00",padding:"0.6rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.85rem"},form:{display:"flex",flexDirection:"column",gap:"0.75rem"},input:{padding:"0.75rem 1rem",borderRadius:"8px",border:"1px solid #ddd",fontSize:"1rem",outline:"none"},loginBtn:{padding:"0.75rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontSize:"1rem",fontWeight:"bold",cursor:"pointer"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#1a1a2e",borderBottom:"1px solid rgba(255,255,255,0.1)"},brandSmall:{color:"white",fontWeight:"bold",fontSize:"1rem"},kitchenName:{color:"rgba(255,255,255,0.5)",fontSize:"0.75rem"},logoutBtn:{padding:"0.4rem 0.75rem",background:"rgba(255,255,255,0.1)",color:"rgba(255,255,255,0.7)",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"6px",fontSize:"0.8rem",cursor:"pointer"},queueArea:{padding:"0.5rem 1rem",display:"flex",flexDirection:"column",gap:"0.4rem"},queueItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.6rem 0.75rem",background:"rgba(255,255,255,0.05)",borderRadius:"8px",borderLeft:"3px solid #2196f3"},queueText:{color:"rgba(255,255,255,0.8)",fontSize:"0.85rem"},spinner:{width:"16px",height:"16px",border:"2px solid rgba(255,255,255,0.2)",borderTopColor:"white",borderRadius:"50%",animation:"spin 1s linear infinite"},captureArea:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"1.5rem",padding:"2rem"},cameraBtn:{width:"200px",height:"200px",borderRadius:"50%",background:"#e94560",border:"none",color:"white",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"0.5rem",cursor:"pointer",fontSize:"1.2rem",fontWeight:"bold",boxShadow:"0 8px 32px rgba(233,69,96,0.4)"},cameraIcon:{fontSize:"3rem"},fileBtn:{padding:"0.75rem 2rem",background:"transparent",border:"2px solid rgba(255,255,255,0.3)",borderRadius:"8px",color:"rgba(255,255,255,0.7)",fontSize:"1rem",cursor:"pointer"},reviewArea:{flex:1,display:"flex",flexDirection:"column",padding:"1rem",gap:"1rem",overflow:"auto"},previewGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:"0.75rem",alignContent:"start"},previewCard:{position:"relative",borderRadius:"8px",overflow:"hidden",background:"#0f0f23",height:"180px"},previewImg:{width:"100%",height:"100%",objectFit:"cover",display:"block"},addPageCard:{height:"180px",borderRadius:"8px",border:"2px dashed rgba(255,255,255,0.25)",background:"rgba(255,255,255,0.05)",color:"rgba(255,255,255,0.7)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"0.5rem",cursor:"pointer"},removeBtn:{position:"absolute",top:"4px",right:"4px",width:"28px",height:"28px",borderRadius:"50%",background:"rgba(0,0,0,0.6)",color:"white",border:"none",fontSize:"1.2rem",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},pageLabel:{position:"absolute",bottom:"4px",left:"4px",background:"rgba(0,0,0,0.6)",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"bold"},actionBar:{display:"flex",justifyContent:"flex-end"},clearBtn:{padding:"0.5rem 1rem",background:"transparent",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"8px",color:"rgba(255,255,255,0.5)",fontSize:"0.85rem",cursor:"pointer"},uploadBtn:{padding:"1rem",background:"#e94560",color:"white",border:"none",borderRadius:"10px",fontSize:"1.1rem",fontWeight:"bold",cursor:"pointer",boxShadow:"0 4px 16px rgba(233,69,96,0.3)"}},yx=n=>n.toISOString().split("T")[0],H2=(n,e)=>{const t=r=>{const i=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],o=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return`${i[r.getDay()]} ${r.getDate()} ${o[r.getMonth()]}`};return`${t(n)} - ${t(e)}`},zce=()=>{const n=new Date;n.setHours(0,0,0,0);const e=n.getDay(),t=e===0?6:e-1,r=new Date(n);r.setDate(n.getDate()-t);const i=new Date(n),o=new Date(r);o.setDate(r.getDate()-7);const a=new Date(r);a.setDate(r.getDate()-1);const l=new Date(n);l.setDate(n.getDate()-1);const d=new Date(l);return d.setDate(l.getDate()-29),{thisWeek:{start:r,end:i},lastWeek:{start:o,end:a},last30Days:{start:d,end:l}}};function Oce(){var x;const{token:n}=gn(),e=go(),t=zce(),{data:r}=Oe({queryKey:["resos-settings"],queryFn:async()=>{const w=await fetch("/api/resos/settings",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch Resos settings");return w.json()},enabled:!!n}),{data:i,isLoading:o,error:a}=Oe({queryKey:["dashboard"],queryFn:async()=>{const w=await fetch("/api/reports/dashboard",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch dashboard");return w.json()}}),{data:l}=Oe({queryKey:["resos-dashboard-covers"],queryFn:async()=>{const w=await fetch("/api/resos/dashboard/today-tomorrow",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch Resos covers");return await w.json()},staleTime:5*60*1e3}),{data:d}=Oe({queryKey:["newbook-arrival-stats"],queryFn:async()=>{const w=await fetch("/api/newbook/dashboard/arrivals?days=3",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch arrival stats");return w.json()},enabled:!!n,staleTime:5*60*1e3}),{data:c}=Oe({queryKey:["upcoming-events"],queryFn:async()=>{const w=await fetch("/api/calendar-events/dashboard/upcoming",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch upcoming events");return w.json()},enabled:!!n,staleTime:5*60*1e3}),{data:u}=Oe({queryKey:["recipe-dashboard-stats"],queryFn:async()=>{const w=await fetch("/api/recipes/dashboard-stats",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch recipe stats");return w.json()},enabled:!!n,staleTime:5*60*1e3}),{data:f}=Oe({queryKey:["dispute-stats"],queryFn:async()=>{const w=await fetch("/api/disputes/stats/summary",{headers:{Authorization:`Bearer ${n}`}});if(!w.ok)throw new Error("Failed to fetch dispute stats");return w.json()},enabled:!!n,staleTime:5*60*1e3}),p=w=>{const S=(r==null?void 0:r.resos_flag_icon_mapping)||{},_={allergies:"🦀",large_group:"⚠️",note_keyword_birthday:"🎂",note_keyword_anniversary:"💍"};if(S[w])return S[w];if(w.startsWith("note_keyword_")){const b=w.replace("note_keyword_","");if(S[b])return S[b]}return _[w]?_[w]:"⚠️"},g=w=>{if(!w||w.length===0)return[];const S=new Set;for(const _ of w){const b=p(_);S.add(b)}return Array.from(S)},m=(w,S)=>{const _=()=>{w!=null&&w.date&&e(`/resos?date=${w.date}`)};return s.jsxs("div",{style:{...We.card,cursor:w?"pointer":"default"},onClick:_,title:w?`Click to view bookings for ${w.date}`:void 0,children:[s.jsxs("h3",{style:We.cardTitle,children:[S,(w==null?void 0:w.has_flagged_bookings)&&s.jsx("span",{style:We.flagIcon,children:g(w.unique_flag_types).map((b,C)=>s.jsx("span",{children:b},C))})]}),w&&w.total_covers>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.coverValue,children:[w.total_covers," covers"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:[w.total_bookings," bookings"]}),w.service_breakdown.map(b=>s.jsxs("span",{children:[b.period,": ",b.bookings," : ",b.covers]},b.period))]})]}):s.jsx("p",{style:We.noData,children:"No booking data"})]})};if(o)return s.jsx("div",{style:We.loading,children:"Loading dashboard..."});if(a)return s.jsx("div",{style:We.loading,children:"Error loading dashboard. Please try logging in again."});const y=i==null?void 0:i.current_period,v=i==null?void 0:i.previous_period;return s.jsxs("div",{children:[s.jsx("h2",{style:We.title,children:"Dashboard"}),s.jsx("h3",{style:We.sectionTitle,children:"Gross Profit"}),s.jsxs("div",{style:We.fourGrid,children:[s.jsxs("div",{style:{...We.card,cursor:"pointer"},onClick:()=>e(`/purchases?from=${yx(t.thisWeek.start)}&to=${yx(t.thisWeek.end)}`),title:"Click to view flash report for this period",children:[s.jsx("h3",{style:We.cardTitle,children:"This Week"}),s.jsx("div",{style:We.dateRange,children:H2(t.thisWeek.start,t.thisWeek.end)}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(y.gp_percentage).toFixed(1),"%"]}),y.gp_with_allowances!=null&&s.jsxs("div",{style:We.wastageAdjusted,children:["(",Number(y.gp_with_allowances).toFixed(1),"% with allowances)"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(y.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(y.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"No data for this period"})]}),s.jsxs("div",{style:We.card,children:[s.jsx("h3",{style:We.cardTitle,children:"This Week Forecast"}),s.jsx("div",{style:We.dateRange,children:H2(t.thisWeek.start,t.thisWeek.end)}),i!=null&&i.forecast_period?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(i.forecast_period.gp_percentage).toFixed(1),"%"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(i.forecast_period.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(i.forecast_period.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"Coming soon"})]}),s.jsxs("div",{style:{...We.card,cursor:"pointer"},onClick:()=>e(`/purchases?from=${yx(t.lastWeek.start)}&to=${yx(t.lastWeek.end)}`),title:"Click to view flash report for this period",children:[s.jsx("h3",{style:We.cardTitle,children:"Last Week"}),s.jsx("div",{style:We.dateRange,children:H2(t.lastWeek.start,t.lastWeek.end)}),v?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(v.gp_percentage).toFixed(1),"%"]}),v.gp_with_allowances!=null&&s.jsxs("div",{style:We.wastageAdjusted,children:["(",Number(v.gp_with_allowances).toFixed(1),"% with allowances)"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(v.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(v.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"No data for this period"})]}),s.jsxs("div",{style:{...We.card,cursor:"pointer"},onClick:()=>e(`/purchases?from=${yx(t.last30Days.start)}&to=${yx(t.last30Days.end)}`),title:"Click to view flash report for this period",children:[s.jsx("h3",{style:We.cardTitle,children:"Last 30 Days"}),s.jsx("div",{style:We.dateRange,children:H2(t.last30Days.start,t.last30Days.end)}),i!=null&&i.rolling_30_days?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:We.gpValue,children:[Number(i.rolling_30_days.gp_percentage).toFixed(1),"%"]}),i.rolling_30_days.gp_with_allowances!=null&&s.jsxs("div",{style:We.wastageAdjusted,children:["(",Number(i.rolling_30_days.gp_with_allowances).toFixed(1),"% with allowances)"]}),s.jsxs("div",{style:We.details,children:[s.jsxs("span",{children:["Revenue: £",Number(i.rolling_30_days.total_revenue).toFixed(2)]}),s.jsxs("span",{children:["Costs: £",Number(i.rolling_30_days.total_costs).toFixed(2)]})]})]}):s.jsx("p",{style:We.noData,children:"No data for this period"})]})]}),s.jsx("h3",{style:We.sectionTitle,children:"Documents"}),s.jsxs("div",{style:We.fourGrid,children:[s.jsxs("a",{href:"/upload",style:{...We.card,...We.uploadCard,...We.cardFlex,textDecoration:"none"},children:[s.jsx("h3",{style:We.cardTitle,children:"Upload New"}),s.jsx("div",{style:We.uploadIcon,children:"+"}),s.jsx("p",{style:We.statLabel,children:"Upload invoice"})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex,...i!=null&&i.pending_review?We.alertCard:{},cursor:((i==null?void 0:i.pending_review)||0)>0?"pointer":"default"},onClick:()=>((i==null?void 0:i.pending_review)||0)>0&&e("/invoices?status=pending_confirmation"),children:[s.jsx("h3",{style:We.cardTitle,children:"Pending Confirmation"}),s.jsx("div",{style:We.statValue,children:(i==null?void 0:i.pending_review)||0}),s.jsx("p",{style:We.statLabel,children:"Awaiting confirmation"}),s.jsx("div",{style:We.cardLinkArea,children:((i==null?void 0:i.pending_review)||0)>0&&s.jsx("span",{style:We.linkText,children:"Review now →"})})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex,...((f==null?void 0:f.open_disputes)||0)>0?We.alertCard:{},cursor:((f==null?void 0:f.open_disputes)||0)>0?"pointer":"default"},onClick:()=>((f==null?void 0:f.open_disputes)||0)>0&&e("/disputes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Disputes"}),s.jsx("div",{style:{...We.statValue,color:((f==null?void 0:f.open_disputes)||0)>0?"#e94560":"#4ade80"},children:(f==null?void 0:f.open_disputes)||0}),s.jsx("p",{style:We.statLabel,children:"Open disputes"}),f&&f.status_counts&&Object.keys(f.status_counts).length>0&&s.jsx("div",{style:We.statusBreakdown,children:Object.entries(f.status_counts).filter(([w])=>w!=="RESOLVED").filter(([,w])=>w.count>0).map(([w,S])=>s.jsxs("span",{style:We.statusBreakdownItem,children:[w.replace(/_/g," ").toLowerCase().replace(/\b\w/g,_=>_.toUpperCase()),": ",S.count]},w))}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View open →"})})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex},children:[s.jsx("h3",{style:We.cardTitle,children:"Recent Invoices"}),s.jsx("div",{style:We.statValue,children:(i==null?void 0:i.recent_invoices)||0}),s.jsx("p",{style:We.statLabel,children:"Uploaded this week"}),s.jsx("div",{style:We.cardLinkArea,children:((i==null?void 0:i.recent_invoices)||0)>0&&s.jsx("a",{href:`/invoices?status=&date_from=${new Date(Date.now()-7*24*60*60*1e3).toISOString().split("T")[0]}&date_to=${new Date().toISOString().split("T")[0]}`,style:We.linkText,children:"View all →"})})]})]}),u&&(u.total_recipes>0||u.unmapped_ingredients>0)&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:We.sectionTitle,children:"Recipes & Dishes"}),s.jsxs("div",{style:We.fourGrid,children:[s.jsxs("div",{style:{...We.card,...We.cardFlex,cursor:"pointer"},onClick:()=>e("/recipes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Recipes"}),s.jsx("div",{style:We.statValue,children:u.component_recipes}),s.jsx("p",{style:We.statLabel,children:"Component recipes"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View recipes →"})})]}),s.jsxs("div",{style:{...We.card,...We.cardFlex,cursor:"pointer"},onClick:()=>e("/dishes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Dishes"}),s.jsx("div",{style:We.statValue,children:u.dish_count}),s.jsx("p",{style:We.statLabel,children:"Plated dishes"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View dishes →"})})]}),u.dishes_missing_allergens>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/allergens"),children:[s.jsx("h3",{style:We.cardTitle,children:"Missing Allergens"}),s.jsx("div",{style:{...We.statValue,color:"#e94560"},children:u.dishes_missing_allergens}),s.jsx("p",{style:We.statLabel,children:"Dishes with unassessed ingredients"}),u.dishes_missing_allergens_list.length>0&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#94a3b8",marginTop:"0.25rem",lineHeight:1.4},children:[u.dishes_missing_allergens_list.slice(0,3).map(w=>w.name).join(", "),u.dishes_missing_allergens_list.length>3&&` +${u.dishes_missing_allergens_list.length-3} more`]}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"Review allergens →"})})]}),u.unmapped_ingredients>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/ingredients?unmapped=true"),children:[s.jsx("h3",{style:We.cardTitle,children:"Unmapped Ingredients"}),s.jsx("div",{style:{...We.statValue,color:"#e94560"},children:u.unmapped_ingredients}),s.jsx("p",{style:We.statLabel,children:"Without supplier source"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"Map now →"})})]}),u.recipes_without_costing>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/recipes"),children:[s.jsx("h3",{style:We.cardTitle,children:"Without Costing"}),s.jsx("div",{style:{...We.statValue,color:"#f59e0b"},children:u.recipes_without_costing}),s.jsx("p",{style:We.statLabel,children:"Recipes with no cost snapshot"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View recipes →"})})]}),u.recipes_with_price_changes>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,cursor:"pointer",borderLeft:"3px solid #f59e0b"},onClick:()=>e("/price-impact"),children:[s.jsx("h3",{style:We.cardTitle,children:"Price Changes"}),s.jsx("div",{style:{...We.statValue,color:"#f59e0b"},children:u.recipes_with_price_changes}),s.jsx("p",{style:We.statLabel,children:"Recipes affected by ingredient price changes (14 days)"}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View report →"})})]}),u.stale_menu_items>0&&s.jsxs("div",{style:{...We.card,...We.cardFlex,...We.alertCard,cursor:"pointer"},onClick:()=>e("/menus"),children:[s.jsx("h3",{style:We.cardTitle,children:"Menus Need Republishing"}),s.jsx("div",{style:{...We.statValue,color:"#92400e"},children:u.stale_menu_items}),s.jsxs("p",{style:We.statLabel,children:["Dish",u.stale_menu_items!==1?"es":""," changed since last publish"]}),u.stale_menu_names.length>0&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#94a3b8",marginTop:"0.25rem",lineHeight:1.4},children:u.stale_menu_names.join(", ")}),s.jsx("div",{style:We.cardLinkArea,children:s.jsx("span",{style:We.linkText,children:"View menus →"})})]})]})]}),s.jsx("h3",{style:We.sectionTitle,children:"Covers"}),s.jsxs("div",{style:We.fourGrid,children:[m((l==null?void 0:l.today)||null,"Today"),m((l==null?void 0:l.tomorrow)||null,"Tomorrow"),m((l==null?void 0:l.day_after)||null,((x=l==null?void 0:l.day_after)==null?void 0:x.day_label)||"Day After"),s.jsxs("div",{style:We.card,children:[s.jsx("h3",{style:We.cardTitle,children:"Upcoming Events"}),c&&c.total_count>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{style:We.gpValue,children:c.total_count}),s.jsx("div",{style:We.details,children:c.upcoming_events.map(w=>s.jsxs("span",{style:{fontSize:"0.85rem"},children:[w.event_date,": ",w.title]},w.id))}),s.jsx("a",{href:"/resos",style:We.link,children:"View Calendar →"})]}):s.jsx("p",{style:We.noData,children:"No upcoming events"})]})]}),d&&d.days&&d.days.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:We.sectionTitle,children:d.service_filter_name?`Hotel Arrivals & ${d.service_filter_name} Bookings`:"Hotel Arrivals & Restaurant Bookings"}),s.jsxs("div",{style:We.wideCard,children:[d.service_filter_name&&s.jsxs("span",{style:We.serviceFilterInfo,children:["(showing ",d.service_filter_name," tables only)"]}),s.jsx("div",{style:We.arrivalGrid,children:d.days.map(w=>s.jsxs("div",{style:We.arrivalDay,children:[s.jsx("div",{style:We.dayName,children:w.day_name}),s.jsxs("div",{style:We.arrivalStats,children:[s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:We.arrivalValue,children:w.arrival_count}),s.jsx("div",{style:We.arrivalLabel,children:"arrivals"}),s.jsxs("div",{style:We.arrivalSubtext,children:[w.arrival_guests," guests"]})]}),s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:We.arrivalValue,children:w.table_bookings}),s.jsx("div",{style:We.arrivalLabel,children:"table bookings"}),s.jsxs("div",{style:We.arrivalSubtext,children:[w.table_covers," covers"]})]}),s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:{...We.arrivalValue,color:"#4ade80"},children:w.matched_arrivals}),s.jsx("div",{style:We.arrivalLabel,children:"have booked"})]}),s.jsxs("div",{style:We.arrivalStat,children:[s.jsx("div",{style:{...We.arrivalValue,color:"#e94560"},children:w.unmatched_arrivals}),s.jsx("div",{style:We.arrivalLabel,children:"no booking yet"}),s.jsxs("div",{style:We.arrivalSubtext,children:[w.opportunity_guests," guests"]})]})]})]},w.date))})]})]})]})}const We={loading:{padding:"2rem",textAlign:"center",color:"#666"},title:{marginBottom:"1.5rem",color:"#1a1a2e"},sectionTitle:{color:"#1a1a2e",fontSize:"1rem",fontWeight:600,marginBottom:"1rem",marginTop:"0.5rem",textTransform:"uppercase",letterSpacing:"0.05em"},fourGrid:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1.5rem",marginBottom:"2rem"},card:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},uploadCard:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"transform 0.2s, box-shadow 0.2s",border:"2px dashed #e94560"},uploadIcon:{fontSize:"3rem",fontWeight:"bold",color:"#e94560",marginBottom:"0.5rem"},alertCard:{borderLeft:"4px solid #e94560"},cardTitle:{color:"#666",fontSize:"0.9rem",marginBottom:"0.25rem",textTransform:"uppercase"},dateRange:{color:"#999",fontSize:"0.75rem",marginBottom:"0.75rem"},serviceFilterInfo:{color:"#999",fontSize:"0.75rem",fontWeight:"normal",textTransform:"none",marginBottom:"1rem",display:"block"},gpValue:{fontSize:"2.5rem",fontWeight:"bold",color:"#1a1a2e"},wastageAdjusted:{fontSize:"0.9rem",color:"#888",marginTop:"-0.25rem",marginBottom:"0.25rem"},statValue:{fontSize:"2.5rem",fontWeight:"bold",color:"#1a1a2e"},coverValue:{fontSize:"2rem",fontWeight:"bold",color:"#1a1a2e"},flagIcon:{fontSize:"1.2rem",marginLeft:"0.5rem"},statLabel:{color:"#666",marginTop:"0.5rem"},details:{marginTop:"1rem",display:"flex",flexDirection:"column",gap:"0.25rem",color:"#666",fontSize:"0.9rem"},noData:{color:"#999",fontStyle:"italic"},link:{display:"inline-block",marginTop:"1rem",color:"#e94560",textDecoration:"none",fontWeight:"bold"},wideCard:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",marginBottom:"2rem"},arrivalGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))",gap:"1.5rem"},arrivalDay:{border:"1px solid #e5e7eb",borderRadius:"8px",padding:"1rem"},dayName:{fontSize:"0.875rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"0.75rem",textTransform:"uppercase"},arrivalStats:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"0.75rem"},arrivalStat:{textAlign:"center"},arrivalValue:{fontSize:"1.75rem",fontWeight:"bold",color:"#1a1a2e"},arrivalLabel:{fontSize:"0.75rem",color:"#666",marginTop:"0.25rem"},arrivalSubtext:{fontSize:"0.75rem",color:"#999",marginTop:"0.125rem"},statusBreakdown:{display:"flex",flexDirection:"column",gap:"0.25rem",marginTop:"0.5rem",marginBottom:"0.75rem"},statusBreakdownItem:{fontSize:"0.75rem",color:"#666"},cardFlex:{display:"flex",flexDirection:"column"},cardLinkArea:{marginTop:"auto",paddingTop:"0.5rem"},linkText:{color:"#e94560",textDecoration:"none",fontSize:"0.9rem",fontWeight:"bold"}};function Lce(){const{token:n}=gn(),e=go(),t=pi(),r=k.useRef(null),i=k.useRef(null),o=k.useRef(null),[a,l]=k.useState([]),[d,c]=k.useState(!1),[u,f]=k.useState(!1),[p,g]=k.useState(""),[m,y]=k.useState(""),[v,x]=k.useState([]),[w,S]=k.useState(null);k.useEffect(()=>{const H=z=>{z.preventDefault(),S(z)};return window.addEventListener("beforeinstallprompt",H),()=>window.removeEventListener("beforeinstallprompt",H)},[]);const _={maxSizeMB:1,maxWidthOrHeight:2e3,useWebWorker:!0,fileType:"image/jpeg",initialQuality:.85},b=()=>Math.random().toString(36).substr(2,9),C=async H=>{const z=Array.from(H),G=[];for(const te of z){const re=te.type.startsWith("image/"),me=te.type==="application/pdf";if(!re&&!me){g("Please upload image or PDF files only");continue}if(me){L(te);continue}const J=await new Promise(ne=>{const ye=new FileReader;ye.onload=ke=>{var Ye;return ne((Ye=ke.target)==null?void 0:Ye.result)},ye.readAsDataURL(te)});G.push({id:b(),file:te,preview:J})}G.length>0&&l(te=>[...te,...G]),g("")},T=H=>{H.preventDefault(),c(!1),H.dataTransfer.files.length>0&&C(H.dataTransfer.files)},F=H=>{H.target.files&&H.target.files.length>0&&C(H.target.files),H.target.value=""},A=H=>{l(z=>z.filter(G=>G.id!==H))},D=(H,z)=>{l(G=>{const te=G.findIndex(J=>J.id===H);if(te===-1||z==="up"&&te===0||z==="down"&&te===G.length-1)return G;const re=[...G],me=z==="up"?te-1:te+1;return[re[te],re[me]]=[re[me],re[te]],re})},P=()=>Math.random().toString(36).substr(2,9),L=async(H,z=!1)=>{const G=P(),te=H.name||"invoice.pdf";x(re=>[...re,{id:G,filename:te,status:"uploading"}]),z&&(l([]),f(!1),y(""));try{const re=new FormData;re.append("file",H),x(ne=>ne.map(ye=>ye.id===G?{...ye,status:"processing"}:ye));const me=await fetch("/api/invoices/upload",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:re});if(!me.ok){const ne=await me.json();throw new Error(ne.detail||"Upload failed")}const J=await me.json();x(ne=>ne.map(ye=>ye.id===G?{...ye,status:"complete",invoiceId:J.id}:ye)),t.invalidateQueries({queryKey:["invoices"]})}catch(re){x(me=>me.map(J=>J.id===G?{...J,status:"error",error:re instanceof Error?re.message:"Upload failed"}:J))}},W=H=>{x(z=>z.filter(G=>G.id!==H))},O=()=>{x(H=>H.filter(z=>z.status!=="complete"&&z.status!=="error"))},U=async()=>{if(a.length===0){g("Please add at least one page");return}f(!0),g("");try{y(`Compressing ${a.length} image(s)...`);const H=[];for(let me=0;me{ne.onload=()=>{URL.revokeObjectURL(ye),Ye()},ne.src=ye});const ke=await J.arrayBuffer();H.push({data:ke,width:ne.width,height:ne.height})}y("Creating PDF...");const z=await Af.create();for(let me=0;me{l([]),g(""),y("")},I=u||v.some(H=>H.status==="uploading"||H.status==="processing");return s.jsxs("div",{children:[s.jsx("h2",{style:an.title,children:"Upload Invoice"}),p&&s.jsx("div",{style:an.error,children:p}),v.length>0&&s.jsxs("div",{style:an.queueSection,children:[s.jsxs("div",{style:an.queueHeader,children:[s.jsx("h3",{style:an.queueTitle,children:"Processing Queue"}),v.some(H=>H.status==="complete"||H.status==="error")&&s.jsx("button",{onClick:O,style:an.clearQueueBtn,children:"Clear Completed"})]}),s.jsx("div",{style:an.queueList,children:v.map(H=>s.jsxs("div",{style:{...an.queueItem,...H.status==="complete"?an.queueItemComplete:{},...H.status==="error"?an.queueItemError:{}},children:[s.jsxs("div",{style:an.queueItemInfo,children:[s.jsx("span",{style:an.queueItemName,children:H.filename}),s.jsxs("span",{style:{...an.queueItemStatus,color:H.status==="complete"?"#28a745":H.status==="error"?"#dc3545":H.status==="processing"?"#0066cc":"#666"},children:[H.status==="uploading"&&"⬆️ Uploading...",H.status==="processing"&&"⏳ Processing OCR...",H.status==="complete"&&"✓ Complete",H.status==="error"&&`✗ ${H.error||"Failed"}`]})]}),s.jsxs("div",{style:an.queueItemActions,children:[H.status==="complete"&&H.invoiceId&&s.jsx("button",{onClick:()=>e(`/invoice/${H.invoiceId}`),style:an.queueViewBtn,children:"View"}),(H.status==="complete"||H.status==="error")&&s.jsx("button",{onClick:()=>W(H.id),style:an.queueRemoveBtn,children:"×"}),(H.status==="uploading"||H.status==="processing")&&s.jsx("div",{style:an.queueSpinner})]})]},H.id))})]}),a.length===0?s.jsxs("div",{style:{...an.dropzone,...d?an.dropzoneActive:{}},onDragOver:H=>{H.preventDefault(),c(!0)},onDragLeave:()=>c(!1),onDrop:T,onClick:()=>{var H;return(H=r.current)==null?void 0:H.click()},children:[s.jsxs("div",{style:an.uploadPrompt,children:[s.jsx("div",{style:an.uploadIcon,children:"📄"}),s.jsx("p",{children:"Drag and drop invoice images"}),s.jsx("p",{style:an.subtext,children:"or click to select files"}),s.jsx("p",{style:an.formats,children:"Supports: JPG, PNG, WebP, HEIC, PDF"}),s.jsx("p",{style:an.multiPageHint,children:"Add multiple images for multi-page invoices"})]}),s.jsx("input",{ref:r,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:F,style:{display:"none"}})]}):s.jsxs("div",{style:an.pagesContainer,children:[s.jsxs("div",{style:an.pagesHeader,children:[s.jsxs("h3",{children:[a.length," Page",a.length!==1?"s":""," Ready"]}),s.jsxs("div",{style:an.headerActions,children:[s.jsx("button",{onClick:()=>{var H;return(H=o.current)==null?void 0:H.click()},style:an.addMoreBtn,disabled:I,children:"+ Add More Pages"}),s.jsx("button",{onClick:M,style:an.clearBtn,disabled:I,children:"Clear All"})]}),s.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,onChange:F,style:{display:"none"}})]}),s.jsx("div",{style:an.pagesGrid,children:a.map((H,z)=>s.jsxs("div",{style:an.pageCard,children:[s.jsxs("div",{style:an.pageNumber,children:["Page ",z+1]}),s.jsx("img",{src:H.preview,alt:`Page ${z+1}`,style:an.pagePreview}),s.jsxs("div",{style:an.pageActions,children:[s.jsx("button",{onClick:()=>D(H.id,"up"),disabled:z===0||I,style:an.moveBtn,title:"Move up",children:"↑"}),s.jsx("button",{onClick:()=>D(H.id,"down"),disabled:z===a.length-1||I,style:an.moveBtn,title:"Move down",children:"↓"}),s.jsx("button",{onClick:()=>A(H.id),disabled:I,style:an.removeBtn,title:"Remove page",children:"×"})]})]},H.id))}),u&&s.jsxs("div",{style:an.processingOverlay,children:[s.jsx("div",{style:an.spinner}),s.jsx("p",{children:m||"Processing..."})]}),s.jsx("button",{onClick:U,disabled:I,style:{...an.uploadBtn,...I?an.uploadBtnDisabled:{}},children:I?m||"Processing...":`Create PDF & Upload (${a.length} page${a.length!==1?"s":""})`})]}),s.jsxs("div",{style:an.cameraSection,children:[s.jsx("p",{children:s.jsx("strong",{children:"Take photos with camera:"})}),s.jsx("p",{style:an.cameraHint,children:'For multi-page invoices, take each page separately then click "Add More Pages"'}),s.jsx("input",{ref:i,type:"file",accept:"image/*",capture:"environment",onChange:F,style:an.cameraInput})]}),s.jsx("div",{style:an.pwaSection,children:s.jsxs("div",{style:an.pwaContent,children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Upload App"}),s.jsx("p",{style:an.pwaHint,children:"Install the upload app for quick camera access on mobile"})]}),w?s.jsx("button",{onClick:async()=>{w.prompt();const{outcome:H}=await w.userChoice;H==="accepted"&&S(null)},style:an.installBtn,children:"Install App"}):s.jsx("a",{href:"/upload-app",style:an.openAppLink,children:"Open Upload App"})]})}),s.jsxs("div",{style:an.infoSection,children:[s.jsx("h4",{children:"How it works:"}),s.jsxs("ol",{style:an.infoList,children:[s.jsx("li",{children:"Add one or more invoice page images"}),s.jsx("li",{children:"Reorder pages if needed using the arrows"}),s.jsx("li",{children:'Click "Create PDF & Upload" to combine and process'}),s.jsx("li",{children:"Images are compressed to save space while maintaining OCR quality"})]})]})]})}const an={title:{marginBottom:"1.5rem",color:"#1a1a2e"},error:{background:"#fee",color:"#c00",padding:"1rem",borderRadius:"8px",marginBottom:"1rem"},dropzone:{background:"white",border:"3px dashed #ddd",borderRadius:"12px",padding:"3rem",textAlign:"center",cursor:"pointer",transition:"all 0.2s",minHeight:"300px",display:"flex",alignItems:"center",justifyContent:"center"},dropzoneActive:{borderColor:"#e94560",background:"#fff5f7"},uploadPrompt:{color:"#666"},uploadIcon:{fontSize:"4rem",marginBottom:"1rem"},subtext:{color:"#999",fontSize:"0.9rem",marginTop:"0.5rem"},formats:{marginTop:"1rem",fontSize:"0.8rem",color:"#999"},multiPageHint:{marginTop:"1.5rem",padding:"0.5rem 1rem",background:"#e8f4fd",borderRadius:"6px",fontSize:"0.85rem",color:"#0066cc"},pagesContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",position:"relative"},pagesHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap",gap:"0.5rem"},headerActions:{display:"flex",gap:"0.5rem"},addMoreBtn:{padding:"0.5rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},clearBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",color:"#666",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},pagesGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))",gap:"1rem",marginBottom:"1.5rem"},pageCard:{background:"#f8f9fa",borderRadius:"8px",padding:"0.5rem",position:"relative"},pageNumber:{position:"absolute",top:"0.75rem",left:"0.75rem",background:"rgba(0,0,0,0.7)",color:"white",padding:"0.25rem 0.5rem",borderRadius:"4px",fontSize:"0.75rem",fontWeight:"bold"},pagePreview:{width:"100%",height:"180px",objectFit:"cover",borderRadius:"6px"},pageActions:{display:"flex",justifyContent:"center",gap:"0.5rem",marginTop:"0.5rem"},moveBtn:{width:"32px",height:"32px",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem"},removeBtn:{width:"32px",height:"32px",background:"#fee",border:"1px solid #fcc",borderRadius:"4px",cursor:"pointer",fontSize:"1.2rem",color:"#c00"},processingOverlay:{position:"absolute",top:0,left:0,right:0,bottom:0,background:"rgba(255,255,255,0.9)",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:"12px",zIndex:10},spinner:{width:"40px",height:"40px",border:"4px solid #ddd",borderTopColor:"#e94560",borderRadius:"50%",animation:"spin 1s linear infinite",marginBottom:"1rem"},uploadBtn:{width:"100%",padding:"1rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"1rem",fontWeight:"bold"},uploadBtnDisabled:{background:"#999",cursor:"wait"},cameraSection:{marginTop:"2rem",padding:"1.5rem",background:"white",borderRadius:"12px",textAlign:"center"},cameraHint:{fontSize:"0.85rem",color:"#666",marginTop:"0.5rem",marginBottom:"1rem"},cameraInput:{marginTop:"0.5rem"},infoSection:{marginTop:"1.5rem",padding:"1.5rem",background:"#f8f9fa",borderRadius:"12px"},infoList:{margin:"0.5rem 0 0 1.5rem",color:"#666",lineHeight:"1.8"},queueSection:{background:"white",borderRadius:"12px",padding:"1rem 1.5rem",marginBottom:"1.5rem"},queueHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},queueTitle:{margin:0,fontSize:"1rem",color:"#1a1a2e"},clearQueueBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",color:"#666"},queueList:{display:"flex",flexDirection:"column",gap:"0.5rem"},queueItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",borderRadius:"8px",borderLeft:"4px solid #0066cc"},queueItemComplete:{borderLeftColor:"#28a745",background:"#f0fff4"},queueItemError:{borderLeftColor:"#dc3545",background:"#fff5f5"},queueItemInfo:{display:"flex",flexDirection:"column",gap:"0.25rem"},queueItemName:{fontWeight:"500",fontSize:"0.9rem"},queueItemStatus:{fontSize:"0.8rem"},queueItemActions:{display:"flex",alignItems:"center",gap:"0.5rem"},queueViewBtn:{padding:"0.35rem 0.75rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},queueRemoveBtn:{width:"24px",height:"24px",background:"transparent",border:"none",cursor:"pointer",fontSize:"1.2rem",color:"#999",display:"flex",alignItems:"center",justifyContent:"center"},queueSpinner:{width:"20px",height:"20px",border:"2px solid #ddd",borderTopColor:"#0066cc",borderRadius:"50%",animation:"spin 1s linear infinite"},pwaSection:{marginTop:"1.5rem",padding:"1.25rem 1.5rem",background:"linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)",borderRadius:"12px"},pwaContent:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"1rem",color:"white"},pwaHint:{fontSize:"0.8rem",color:"rgba(255,255,255,0.6)",marginTop:"0.25rem"},installBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"8px",fontSize:"0.9rem",fontWeight:"bold",cursor:"pointer",whiteSpace:"nowrap"},openAppLink:{padding:"0.6rem 1.25rem",background:"rgba(255,255,255,0.1)",color:"white",border:"1px solid rgba(255,255,255,0.3)",borderRadius:"8px",fontSize:"0.9rem",textDecoration:"none",whiteSpace:"nowrap"}},aN={upload:{label:"Upload",color:"#6c757d",icon:"📤"},email:{label:"Email",color:"#3498db",icon:"📧"},api:{label:"API",color:"#9b59b6",icon:"🔌"}},lN=({source:n})=>{const{label:e,color:t,icon:r}=aN[n]||aN.upload;return s.jsxs("span",{style:{background:t,color:"white",padding:"0.15rem 0.4rem",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"bold",display:"inline-flex",alignItems:"center",gap:"0.2rem"},children:[r," ",e]})},q2={PENDING:"#f59e0b",PROCESSED:"#3b82f6",REVIEWED:"#8b5cf6",CONFIRMED:"#22c55e",NEW:"#06b6d4"};function Nce(){const{token:n}=gn(),[e,t]=K_(),[r,i]=k.useState(()=>{const b=e.get("status");return b!==null?b:"pending_confirmation"}),[o,a]=k.useState(()=>e.get("supplier_id")||""),[l,d]=k.useState(()=>e.get("date_from")||""),[c,u]=k.useState(()=>e.get("date_to")||"");k.useEffect(()=>{e.toString()&&t({},{replace:!0})},[]);const{data:f}=Oe({queryKey:["suppliers"],queryFn:async()=>{const b=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():[]}}),p=new URLSearchParams;r&&p.append("status",r),o&&p.append("supplier_id",o),l&&p.append("date_from",l),c&&p.append("date_to",c);const g=p.toString(),{data:m,isLoading:y,error:v}=Oe({queryKey:["invoices",r,o,l,c],queryFn:async()=>{const b=g?`/api/invoices/?${g}`:"/api/invoices/",C=await fetch(b,{headers:{Authorization:`Bearer ${n}`}});if(!C.ok)throw new Error("Failed to fetch invoices");return C.json()}}),x=r==="pending_confirmation"&&(m==null?void 0:m.invoices.length)===0,{data:w}=Oe({queryKey:["completed-invoices"],queryFn:async()=>{const b=new URLSearchParams;b.set("status","confirmed"),b.set("limit","20"),b.set("sort","recent");const C=await fetch(`/api/invoices/?${b}`,{headers:{Authorization:`Bearer ${n}`}});if(!C.ok)throw new Error("Failed to fetch completed invoices");return C.json()},enabled:x&&!!n});if(y)return s.jsx("div",{style:Xt.loading,children:"Loading invoices..."});if(v)return s.jsxs("div",{style:Xt.error,children:["Error loading invoices: ",v.message]});const S=(m==null?void 0:m.invoices)||[],_=(w==null?void 0:w.invoices)||[];return s.jsxs("div",{children:[s.jsxs("div",{style:Xt.header,children:[s.jsx("h2",{style:Xt.title,children:"Uploaded Invoices"}),s.jsx("a",{href:"/upload",style:Xt.uploadBtn,children:"+ Upload New"})]}),s.jsxs("div",{style:Xt.filters,children:[s.jsxs("select",{value:r,onChange:b=>i(b.target.value),style:Xt.filterSelect,children:[s.jsx("option",{value:"",children:"All Statuses"}),s.jsx("option",{value:"pending_confirmation",children:"Pending Confirmation"}),s.jsx("option",{value:"pending",children:"Pending"}),s.jsx("option",{value:"processed",children:"Processed"}),s.jsx("option",{value:"reviewed",children:"Reviewed"}),s.jsx("option",{value:"confirmed",children:"Confirmed"})]}),s.jsxs("select",{value:o,onChange:b=>a(b.target.value),style:Xt.filterSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),f==null?void 0:f.map(b=>s.jsx("option",{value:b.id,children:b.name},b.id))]}),s.jsxs("div",{style:Xt.dateFilters,children:[s.jsxs("label",{style:Xt.dateLabel,children:["Upload Date From:",s.jsx("input",{type:"date",value:l,onChange:b=>d(b.target.value),style:Xt.dateInput})]}),s.jsxs("label",{style:Xt.dateLabel,children:["Upload Date To:",s.jsx("input",{type:"date",value:c,onChange:b=>u(b.target.value),style:Xt.dateInput})]})]}),(r!=="pending_confirmation"||o||l||c)&&s.jsx("button",{onClick:()=>{i("pending_confirmation"),a(""),d(""),u("")},style:Xt.clearBtn,children:"Clear Filters"})]}),S.length===0?s.jsxs("div",{style:Xt.empty,children:[s.jsx("p",{children:"No invoices pending confirmation."}),s.jsx("a",{href:"/upload",style:Xt.link,children:"Upload one now"})]}):s.jsx("div",{style:Xt.list,children:S.map(b=>s.jsxs("a",{href:`/invoice/${b.id}`,style:{...Xt.card,borderLeft:`4px solid ${q2[b.status]||"#999"}`},children:[s.jsxs("div",{style:Xt.cardMain,children:[s.jsxs("div",{style:Xt.invoiceNumberRow,children:[s.jsx("span",{style:Xt.invoiceNumber,children:b.invoice_number||(b.status==="PENDING"?"Pending extraction...":b.vendor_name?`(${b.vendor_name})`:"No invoice #")}),b.document_type==="delivery_note"&&s.jsx("span",{style:Xt.dnBadge,children:"DN"}),b.duplicate_status==="firm_duplicate"&&s.jsx("span",{style:Xt.duplicateBadge,children:"DUPLICATE"}),b.duplicate_status==="possible_duplicate"&&s.jsx("span",{style:Xt.possibleDuplicateBadge,children:"POSSIBLE DUPLICATE"})]}),s.jsxs("div",{style:Xt.invoiceMeta,children:[b.supplier_name?s.jsxs("span",{style:{...Xt.supplierName,...b.supplier_match_type==="fuzzy"?Xt.fuzzySupplier:{}},children:[b.supplier_name,b.supplier_match_type==="fuzzy"&&s.jsx("span",{style:Xt.fuzzyBadge,title:"Suggested match - please verify",children:"?"})]}):b.vendor_name?s.jsxs("span",{style:Xt.unmatchedSupplier,title:"No matching supplier found - click to assign",children:[b.vendor_name,s.jsx("span",{style:Xt.unmatchedBadge,children:"!"})]}):null,s.jsx("span",{style:Xt.invoiceDate,children:b.invoice_date?new Date(b.invoice_date).toLocaleDateString():"No date"})]})]}),s.jsxs("div",{style:Xt.cardRight,children:[s.jsx("div",{style:Xt.total,children:b.stock_total!=null&&b.total!=null&&b.stock_total!==b.total?s.jsxs(s.Fragment,{children:["£",Number(b.stock_total).toFixed(2),s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.net_total!=null?s.jsxs(s.Fragment,{children:["£",Number(b.net_total).toFixed(2),b.total!=null&&b.total!==b.net_total&&s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.total!=null?`£${Number(b.total).toFixed(2)}`:"—"}),s.jsxs("div",{style:Xt.badgeRow,children:[b.source&&b.source!=="upload"&&s.jsx(lN,{source:b.source}),s.jsx("div",{style:{...Xt.status,background:q2[b.status]||"#999"},children:b.status})]})]}),b.ocr_confidence!=null&&s.jsxs("div",{style:Xt.confidence,children:[(Number(b.ocr_confidence)*100).toFixed(0),"% confidence"]})]},b.id))}),x&&_.length>0&&s.jsxs("div",{style:{marginTop:"2rem"},children:[s.jsx("h3",{style:{...Xt.title,fontSize:"1.2rem",marginBottom:"1rem"},children:"Recently Completed Invoices"}),s.jsx("div",{style:Xt.list,children:_.map(b=>s.jsxs("a",{href:`/invoice/${b.id}`,style:{...Xt.card,borderLeft:`4px solid ${q2[b.status]||"#999"}`},children:[s.jsxs("div",{style:Xt.cardMain,children:[s.jsxs("div",{style:Xt.invoiceNumberRow,children:[s.jsx("span",{style:Xt.invoiceNumber,children:b.invoice_number||(b.status==="PENDING"?"Pending extraction...":b.vendor_name?`(${b.vendor_name})`:"No invoice #")}),b.document_type==="delivery_note"&&s.jsx("span",{style:Xt.dnBadge,children:"DN"}),b.duplicate_status==="firm_duplicate"&&s.jsx("span",{style:Xt.duplicateBadge,children:"DUPLICATE"}),b.duplicate_status==="possible_duplicate"&&s.jsx("span",{style:Xt.possibleDuplicateBadge,children:"POSSIBLE DUPLICATE"})]}),s.jsxs("div",{style:Xt.invoiceMeta,children:[b.supplier_name?s.jsxs("span",{style:{...Xt.supplierName,...b.supplier_match_type==="fuzzy"?Xt.fuzzySupplier:{}},children:[b.supplier_name,b.supplier_match_type==="fuzzy"&&s.jsx("span",{style:Xt.fuzzyBadge,title:"Suggested match - please verify",children:"?"})]}):b.vendor_name?s.jsxs("span",{style:Xt.unmatchedSupplier,title:"No matching supplier found - click to assign",children:[b.vendor_name,s.jsx("span",{style:Xt.unmatchedBadge,children:"!"})]}):null,s.jsx("span",{style:Xt.invoiceDate,children:b.invoice_date?new Date(b.invoice_date).toLocaleDateString():"No date"})]})]}),s.jsxs("div",{style:Xt.cardRight,children:[s.jsx("div",{style:Xt.total,children:b.stock_total!=null&&b.total!=null&&b.stock_total!==b.total?s.jsxs(s.Fragment,{children:["£",Number(b.stock_total).toFixed(2),s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.net_total!=null?s.jsxs(s.Fragment,{children:["£",Number(b.net_total).toFixed(2),b.total!=null&&b.total!==b.net_total&&s.jsxs("span",{style:Xt.fullTotal,children:["(£",Number(b.total).toFixed(2),")"]})]}):b.total!=null?`£${Number(b.total).toFixed(2)}`:"—"}),s.jsxs("div",{style:Xt.badgeRow,children:[b.source&&b.source!=="upload"&&s.jsx(lN,{source:b.source}),s.jsx("div",{style:{...Xt.status,background:q2[b.status]||"#999"},children:b.status})]})]}),b.ocr_confidence!=null&&s.jsxs("div",{style:Xt.confidence,children:[(Number(b.ocr_confidence)*100).toFixed(0),"% confidence"]})]},b.id))})]})]})}const Xt={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},uploadBtn:{padding:"0.75rem 1.5rem",background:"#e94560",color:"white",textDecoration:"none",borderRadius:"8px",fontWeight:"bold"},filters:{display:"flex",gap:"1rem",marginBottom:"1.5rem",alignItems:"center",flexWrap:"wrap",background:"white",padding:"1rem",borderRadius:"8px"},filterSelect:{padding:"0.5rem 1rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.9rem",minWidth:"150px"},dateFilters:{display:"flex",gap:"1rem",alignItems:"center"},dateLabel:{display:"flex",alignItems:"center",gap:"0.5rem",fontSize:"0.9rem",color:"#666"},dateInput:{padding:"0.5rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.9rem"},clearBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},empty:{background:"white",padding:"3rem",borderRadius:"12px",textAlign:"center",color:"#666"},link:{color:"#e94560",marginTop:"1rem",display:"inline-block"},list:{display:"flex",flexDirection:"column",gap:"1rem"},card:{display:"flex",alignItems:"center",justifyContent:"space-between",background:"white",padding:"1.25rem 1.5rem",borderRadius:"12px",textDecoration:"none",color:"inherit",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",transition:"transform 0.2s, box-shadow 0.2s",position:"relative"},cardMain:{flex:1},invoiceNumberRow:{display:"flex",alignItems:"center",gap:"0.5rem",flexWrap:"wrap"},invoiceNumber:{fontWeight:"bold",fontSize:"1.1rem",color:"#1a1a2e"},dnBadge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#6c757d",color:"white",fontSize:"0.65rem",fontWeight:"bold",borderRadius:"4px",textTransform:"uppercase"},duplicateBadge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#dc3545",color:"white",fontSize:"0.65rem",fontWeight:"bold",borderRadius:"4px",textTransform:"uppercase"},possibleDuplicateBadge:{display:"inline-block",padding:"0.15rem 0.5rem",background:"#fd7e14",color:"white",fontSize:"0.65rem",fontWeight:"bold",borderRadius:"4px",textTransform:"uppercase"},invoiceMeta:{display:"flex",gap:"0.75rem",marginTop:"0.25rem",alignItems:"center"},supplierName:{color:"#1a1a2e",fontSize:"0.9rem",fontWeight:"500"},fuzzySupplier:{color:"#856404",background:"#fff3cd",padding:"0.1rem 0.4rem",borderRadius:"4px",border:"1px solid #ffc107"},fuzzyBadge:{display:"inline-block",marginLeft:"0.3rem",width:"14px",height:"14px",lineHeight:"14px",textAlign:"center",background:"#ffc107",color:"#856404",borderRadius:"50%",fontSize:"0.7rem",fontWeight:"bold"},unmatchedSupplier:{color:"#721c24",background:"#f8d7da",padding:"0.1rem 0.4rem",borderRadius:"4px",border:"1px solid #f5c6cb",fontSize:"0.9rem"},unmatchedBadge:{display:"inline-block",marginLeft:"0.3rem",width:"14px",height:"14px",lineHeight:"14px",textAlign:"center",background:"#dc3545",color:"white",borderRadius:"50%",fontSize:"0.7rem",fontWeight:"bold"},invoiceDate:{color:"#666",fontSize:"0.9rem"},cardRight:{textAlign:"right",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"0.5rem"},badgeRow:{display:"flex",gap:"0.4rem",alignItems:"center",justifyContent:"flex-end"},total:{fontWeight:"bold",fontSize:"1.2rem",color:"#1a1a2e"},fullTotal:{fontSize:"0.85rem",fontWeight:"normal",color:"#666",marginLeft:"0.25rem"},status:{display:"inline-block",padding:"0.25rem 0.75rem",borderRadius:"20px",color:"white",fontSize:"0.75rem",textTransform:"uppercase"},confidence:{position:"absolute",top:"0.5rem",right:"0.75rem",fontSize:"0.7rem",color:"#999"}},zl=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),hf=[1/0,1/0,-1/0,-1/0],_m=new Float32Array(hf),GB=[.001,0,0,.001,0,0],OP=1.35,Rl={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Ru={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Gj="pdfjs_internal_editor_",jn={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},Wn={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},Wce={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Rs={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},E5={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Cs={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},Sx={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},eD={ERRORS:0,WARNINGS:1,INFOS:5},Sh={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},Hw={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},Uce={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let tD=eD.WARNINGS;function Hce(n){Number.isInteger(n)&&(tD=n)}function qce(){return tD}function nD(n){tD>=eD.INFOS&&console.info(`Info: ${n}`)}function Bn(n){tD>=eD.WARNINGS&&console.warn(`Warning: ${n}`)}function Hr(n){throw new Error(n)}function Zi(n,e){n||Hr(e)}function Vce(n){switch(n==null?void 0:n.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function aV(n,e=null,t=null){if(!n)return null;if(t&&typeof n=="string"){if(t.addDefaultProtocol&&n.startsWith("www.")){const i=n.match(/\./g);(i==null?void 0:i.length)>=2&&(n=`http://${n}`)}if(t.tryConvertEncoding)try{n=Yce(n)}catch{}}const r=e?URL.parse(n,e):URL.parse(n);return Vce(r)?r:null}function lV(n,e,t=!1){const r=URL.parse(n);return r?(r.hash=e,r.href):t&&aV(n,"http://example.com")?n.split("#",1)[0]+`${e?`#${e}`:""}`:""}function KB(n){return n.substring(n.lastIndexOf("/")+1)}function Cn(n,e,t,r=!1){return Object.defineProperty(n,e,{value:t,enumerable:!r,configurable:!0,writable:!1}),t}const W0=function(){function e(t,r){this.message=t,this.name=r}return e.prototype=new Error,e.constructor=e,e}();class dN extends W0{constructor(e,t){super(e,"PasswordException"),this.code=t}}class LP extends W0{constructor(e,t){super(e,"UnknownErrorException"),this.details=t}}class XB extends W0{constructor(e){super(e,"InvalidPDFException")}}class xT extends W0{constructor(e,t,r){super(e,"ResponseException"),this.status=t,this.missing=r}}class Gce extends W0{constructor(e){super(e,"FormatError")}}class Ng extends W0{constructor(e){super(e,"AbortException")}}function Kce(n){(typeof n!="object"||(n==null?void 0:n.length)===void 0)&&Hr("Invalid argument for bytesToString");const e=n.length,t=8192;if(e{if(typeof document>"u")return!1;const e=document.createElement("input");return e.type="color",e.setAttribute("alpha",""),e.value="#ff000080",e.value!=="#ff0000"})())}}var bf,P5,YB;class yt{static get hexNums(){return Cn(this,"hexNums",Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,"0")))}static makeHexColor(e,t,r){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[r]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,t){let r;e[0]?(e[0]<0&&(r=t[0],t[0]=t[2],t[2]=r),t[0]*=e[0],t[2]*=e[0],e[3]<0&&(r=t[1],t[1]=t[3],t[3]=r),t[1]*=e[3],t[3]*=e[3]):(r=t[0],t[0]=t[1],t[1]=r,r=t[2],t[2]=t[3],t[3]=r,e[1]<0&&(r=t[1],t[1]=t[3],t[3]=r),t[1]*=e[1],t[3]*=e[1],e[2]<0&&(r=t[0],t[0]=t[2],t[2]=r),t[0]*=e[2],t[2]*=e[2]),t[0]+=e[4],t[1]+=e[5],t[2]+=e[4],t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,r=0){const i=e[r],o=e[r+1];e[r]=i*t[0]+o*t[2]+t[4],e[r+1]=i*t[1]+o*t[3]+t[5]}static applyTransformToBezier(e,t,r=0){const i=t[0],o=t[1],a=t[2],l=t[3],d=t[4],c=t[5];for(let u=0;u<6;u+=2){const f=e[r+u],p=e[r+u+1];e[r+u]=f*i+p*a+d,e[r+u+1]=f*o+p*l+c}}static applyInverseTransform(e,t){const r=e[0],i=e[1],o=t[0]*t[3]-t[1]*t[2];e[0]=(r*t[3]-i*t[2]+t[2]*t[5]-t[4]*t[3])/o,e[1]=(-r*t[1]+i*t[0]+t[4]*t[1]-t[5]*t[0])/o}static axialAlignedBoundingBox(e,t,r){const i=t[0],o=t[1],a=t[2],l=t[3],d=t[4],c=t[5],u=e[0],f=e[1],p=e[2],g=e[3];let m=i*u+d,y=m,v=i*p+d,x=v,w=l*f+c,S=w,_=l*g+c,b=_;if(o!==0||a!==0){const C=o*u,T=o*p,F=a*f,A=a*g;m+=F,x+=F,v+=A,y+=A,w+=C,b+=C,_+=T,S+=T}r[0]=Math.min(r[0],m,v,y,x),r[1]=Math.min(r[1],w,_,S,b),r[2]=Math.max(r[2],m,v,y,x),r[3]=Math.max(r[3],w,_,S,b)}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){const r=e[0],i=e[1],o=e[2],a=e[3],l=r**2+i**2,d=r*o+i*a,c=o**2+a**2,u=(l+c)/2,f=Math.sqrt(u**2-(l*c-d**2));t[0]=Math.sqrt(u+f||1),t[1]=Math.sqrt(u-f||1)}static normalizeRect(e){const t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){const r=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),i=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(r>i)return null;const o=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return o>a?null:[r,o,i,a]}static pointBoundingBox(e,t,r){r[0]=Math.min(r[0],e),r[1]=Math.min(r[1],t),r[2]=Math.max(r[2],e),r[3]=Math.max(r[3],t)}static rectBoundingBox(e,t,r,i,o){o[0]=Math.min(o[0],e,r),o[1]=Math.min(o[1],t,i),o[2]=Math.max(o[2],e,r),o[3]=Math.max(o[3],t,i)}static bezierBoundingBox(e,t,r,i,o,a,l,d,c){c[0]=Math.min(c[0],e,l),c[1]=Math.min(c[1],t,d),c[2]=Math.max(c[2],e,l),c[3]=Math.max(c[3],t,d),q(this,bf,YB).call(this,e,r,o,l,t,i,a,d,3*(-e+3*(r-o)+l),6*(e-2*r+o),3*(r-e),c),q(this,bf,YB).call(this,e,r,o,l,t,i,a,d,3*(-t+3*(i-a)+d),6*(t-2*i+a),3*(i-t),c)}}bf=new WeakSet,P5=function(e,t,r,i,o,a,l,d,c,u){if(c<=0||c>=1)return;const f=1-c,p=c*c,g=p*c,m=f*(f*(f*e+3*c*t)+3*p*r)+g*i,y=f*(f*(f*o+3*c*a)+3*p*l)+g*d;u[0]=Math.min(u[0],m),u[1]=Math.min(u[1],y),u[2]=Math.max(u[2],m),u[3]=Math.max(u[3],y)},YB=function(e,t,r,i,o,a,l,d,c,u,f,p){if(Math.abs(c)<1e-12){Math.abs(u)>=1e-12&&q(this,bf,P5).call(this,e,t,r,i,o,a,l,d,-f/u,p);return}const g=u**2-4*f*c;if(g<0)return;const m=Math.sqrt(g),y=2*c;q(this,bf,P5).call(this,e,t,r,i,o,a,l,d,(-u+m)/y,p),q(this,bf,P5).call(this,e,t,r,i,o,a,l,d,(-u-m)/y,p)},N(yt,bf);function Yce(n){return decodeURIComponent(escape(n))}let NP=null,cN=null;function Qce(n){return NP||(NP=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,cN=new Map([["ſt","ſt"]])),n.replaceAll(NP,(e,t,r)=>t?t.normalize("NFKC"):cN.get(r))}function dV(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const n=new Uint8Array(32);return crypto.getRandomValues(n),Kce(n)}const Yx="pdfjs_internal_id_";function $ce(n,e,t){if(!Array.isArray(t)||t.length<2)return!1;const[r,i,...o]=t;if(!n(r)&&!Number.isInteger(r)||!e(i))return!1;const a=o.length;let l=!0;switch(i.name){case"XYZ":if(a<2||a>3)return!1;break;case"Fit":case"FitB":return a===0;case"FitH":case"FitBH":case"FitV":case"FitBV":if(a>1)return!1;break;case"FitR":if(a!==4)return!1;l=!1;break;default:return!1}for(const d of o)if(!(typeof d=="number"||l&&d===null))return!1;return!0}const F3=()=>[],D3=()=>new Map,QB=()=>Object.create(null);function Bi(n,e,t){return Math.min(Math.max(n,e),t)}class Kj{static textContent(e){const t=[],r={items:t,styles:Object.create(null)};function i(o){var d;if(!o)return;let a=null;const l=o.name;if(l==="#text")a=o.value;else if(Kj.shouldBuildText(l))(d=o==null?void 0:o.attributes)!=null&&d.textContent?a=o.attributes.textContent:o.value&&(a=o.value);else return;if(a!==null&&t.push({str:a}),!!o.children)for(const c of o.children)i(c)}return i(e),r}static shouldBuildText(e){return!(e==="textarea"||e==="input"||e==="option"||e==="select")}}class cV{static setupStorage(e,t,r,i,o){const a=i.getValue(t,{value:null});switch(r.name){case"textarea":if(a.value!==null&&(e.textContent=a.value),o==="print")break;e.addEventListener("input",l=>{i.setValue(t,{value:l.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(a.value===r.attributes.xfaOn?e.setAttribute("checked",!0):a.value===r.attributes.xfaOff&&e.removeAttribute("checked"),o==="print")break;e.addEventListener("change",l=>{i.setValue(t,{value:l.target.checked?l.target.getAttribute("xfaOn"):l.target.getAttribute("xfaOff")})})}else{if(a.value!==null&&e.setAttribute("value",a.value),o==="print")break;e.addEventListener("input",l=>{i.setValue(t,{value:l.target.value})})}break;case"select":if(a.value!==null){e.setAttribute("value",a.value);for(const l of r.children)l.attributes.value===a.value?l.attributes.selected=!0:Object.hasOwn(l.attributes,"selected")&&delete l.attributes.selected}e.addEventListener("input",l=>{const d=l.target.options,c=d.selectedIndex===-1?"":d[d.selectedIndex].value;i.setValue(t,{value:c})});break}}static setAttributes({html:e,element:t,storage:r=null,intent:i,linkService:o}){const{attributes:a}=t,l=e instanceof HTMLAnchorElement;a.type==="radio"&&(a.name=`${a.name}-${i}`);for(const[d,c]of Object.entries(a))if(c!=null)switch(d){case"class":c.length&&e.setAttribute(d,c.join(" "));break;case"dataId":break;case"id":e.setAttribute("data-element-id",c);break;case"style":Object.assign(e.style,c);break;case"textContent":e.textContent=c;break;default:(!l||d!=="href"&&d!=="newWindow")&&e.setAttribute(d,c)}l&&o.addLinkAttributes(e,a.href,a.newWindow),r&&a.dataId&&this.setupStorage(e,a.dataId,t,r)}static render(e){var f,p;const t=e.annotationStorage,r=e.linkService,i=e.xfaHtml,o=e.intent||"display",a=document.createElement(i.name);i.attributes&&this.setAttributes({html:a,element:i,intent:o,linkService:r});const l=o!=="richText",d=e.div;if(d.append(a),e.viewport){const g=`matrix(${e.viewport.transform.join(",")})`;d.style.transform=g}l&&d.setAttribute("class","xfaLayer xfaFont");const c=[];if(i.children.length===0){if(i.value){const g=document.createTextNode(i.value);a.append(g),l&&Kj.shouldBuildText(i.name)&&c.push(g)}return{textDivs:c}}const u=[[i,-1,a]];for(;u.length>0;){const[g,m,y]=u.at(-1);if(m+1===g.children.length){u.pop();continue}const v=g.children[++u.at(-1)[1]];if(v===null)continue;const{name:x}=v;if(x==="#text"){const S=document.createTextNode(v.value);c.push(S),y.append(S);continue}const w=(f=v==null?void 0:v.attributes)!=null&&f.xmlns?document.createElementNS(v.attributes.xmlns,x):document.createElement(x);if(y.append(w),v.attributes&&this.setAttributes({html:w,element:v,storage:t,intent:o,linkService:r}),((p=v.children)==null?void 0:p.length)>0)u.push([v,-1,w]);else if(v.value){const S=document.createTextNode(v.value);l&&Kj.shouldBuildText(x)&&c.push(S),w.append(S)}}for(const g of d.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))g.setAttribute("readOnly",!0);return{textDivs:c}}static update(e){const t=`matrix(${e.viewport.transform.join(",")})`;e.div.style.transform=t,e.div.hidden=!1}}const hh="http://www.w3.org/2000/svg",hm=class hm{};ve(hm,"CSS",96),ve(hm,"PDF",72),ve(hm,"PDF_TO_CSS_UNITS",hm.CSS/hm.PDF);let Wg=hm;async function E3(n,e="text"){if(rj(n,document.baseURI)){const t=await fetch(n);if(!t.ok)throw new Error(t.statusText);switch(e){case"blob":return t.blob();case"bytes":return t.bytes();case"json":return t.json()}return t.text()}return new Promise((t,r)=>{const i=new XMLHttpRequest;i.open("GET",n,!0),i.responseType=e==="bytes"?"arraybuffer":e,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(e){case"bytes":t(new Uint8Array(i.response));return;case"blob":case"json":t(i.response);return}t(i.responseText);return}r(new Error(i.statusText))}},i.send(null)})}class dC{constructor({viewBox:e,userUnit:t,scale:r,rotation:i,offsetX:o=0,offsetY:a=0,dontFlip:l=!1}){this.viewBox=e,this.userUnit=t,this.scale=r,this.rotation=i,this.offsetX=o,this.offsetY=a,r*=t;const d=(e[2]+e[0])/2,c=(e[3]+e[1])/2;let u,f,p,g;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,f=0,p=0,g=1;break;case 90:u=0,f=1,p=1,g=0;break;case 270:u=0,f=-1,p=-1,g=0;break;case 0:u=1,f=0,p=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(p=-p,g=-g);let m,y,v,x;u===0?(m=Math.abs(c-e[1])*r+o,y=Math.abs(d-e[0])*r+a,v=(e[3]-e[1])*r,x=(e[2]-e[0])*r):(m=Math.abs(d-e[0])*r+o,y=Math.abs(c-e[1])*r+a,v=(e[2]-e[0])*r,x=(e[3]-e[1])*r),this.transform=[u*r,f*r,p*r,g*r,m-u*r*d-p*r*c,y-f*r*d-g*r*c],this.width=v,this.height=x}get rawDims(){const e=this.viewBox;return Cn(this,"rawDims",{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:e=this.scale,rotation:t=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:o=!1}={}){return new dC({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:e,rotation:t,offsetX:r,offsetY:i,dontFlip:o})}convertToViewportPoint(e,t){const r=[e,t];return yt.applyTransform(r,this.transform),r}convertToViewportRectangle(e){const t=[e[0],e[1]];yt.applyTransform(t,this.transform);const r=[e[2],e[3]];return yt.applyTransform(r,this.transform),[t[0],t[1],r[0],r[1]]}convertToPdfPoint(e,t){const r=[e,t];return yt.applyInverseTransform(r,this.transform),r}}class P3 extends W0{constructor(e,t=0){super(e,"RenderingCancelledException"),this.extraDelay=t}}function iD(n){const e=n.length;let t=0;for(;t{try{return new URL(l)}catch{try{return new URL(decodeURIComponent(l))}catch{try{return new URL(l,"https://foo.bar")}catch{try{return new URL(decodeURIComponent(l),"https://foo.bar")}catch{return null}}}}})(n);if(!r)return e;const i=l=>{try{let d=decodeURIComponent(l);return d.includes("/")&&(d=KB(d),/^\.pdf$/i.test(d))?l:d}catch{return l}},o=/\.pdf$/i,a=KB(r.pathname);if(o.test(a))return i(a);if(r.searchParams.size>0){const l=c=>[...c].findLast(u=>o.test(u)),d=l(r.searchParams.values())??l(r.searchParams.keys());if(d)return i(d)}if(r.hash){const d=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(r.hash);if(d)return i(d[0])}return e}var gp;class uN{constructor(){N(this,gp,new Map);ve(this,"times",[])}time(e){h(this,gp).has(e)&&Bn(`Timer is already running for ${e}`),h(this,gp).set(e,Date.now())}timeEnd(e){h(this,gp).has(e)||Bn(`Timer has not been started for ${e}`),this.times.push({name:e,start:h(this,gp).get(e),end:Date.now()}),h(this,gp).delete(e)}toString(){const e=Math.max(...this.times.map(t=>t.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms -`).join("")}}gp=new WeakMap;function rj(n,e){const t=e?URL.parse(n,e):URL.parse(n);return/https?:/.test((t==null?void 0:t.protocol)??"")}function Hd(n){n.preventDefault()}function $i(n){n.preventDefault(),n.stopPropagation()}function eue(n){console.log("Deprecated API usage: "+n)}var rk;class bT{static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!="string")return null;h(this,rk)||R(this,rk,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const t=h(this,rk).exec(e);if(!t)return null;const r=parseInt(t[1],10);let i=parseInt(t[2],10);i=i>=1&&i<=12?i-1:0;let o=parseInt(t[3],10);o=o>=1&&o<=31?o:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let l=parseInt(t[5],10);l=l>=0&&l<=59?l:0;let d=parseInt(t[6],10);d=d>=0&&d<=59?d:0;const c=t[7]||"Z";let u=parseInt(t[8],10);u=u>=0&&u<=23?u:0;let f=parseInt(t[9],10)||0;return f=f>=0&&f<=59?f:0,c==="-"?(a+=u,l+=f):c==="+"&&(a-=u,l-=f),new Date(Date.UTC(r,i,o,a,l,d))}}rk=new WeakMap,N(bT,rk);function tue(n,{scale:e=1,rotation:t=0}){const{width:r,height:i}=n.attributes.style,o=[0,0,parseInt(r,10),parseInt(i,10)];return new dC({viewBox:o,userUnit:1,scale:e,rotation:t})}function B3(n){if(n.startsWith("#")){const t=n.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(n.startsWith("rgb(")){const[t,r,i]=n.slice(4,-1).split(",").map(o=>parseInt(o,10));return[t,r,i,1]}if(n.startsWith("rgba(")){const t=n.slice(5,-1).split(",");return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}const e=n.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return e?[Math.round(parseFloat(e[1])*255),Math.round(parseFloat(e[2])*255),Math.round(parseFloat(e[3])*255),e[4]!==void 0&&e[4]!=="none"?parseFloat(e[4]):1]:null}function cC(n){const e=B3(n);return e?e.slice(0,3):(Bn(`Not a valid color format: "${n}"`),[0,0,0])}function nue(n){const e=document.createElement("span");e.style.visibility="hidden",e.style.colorScheme="only light",document.body.append(e);for(const t of n.keys()){e.style.color=t;const r=window.getComputedStyle(e).color;n.set(t,cC(r))}e.remove()}function ji(n){const{a:e,b:t,c:r,d:i,e:o,f:a}=n.getTransform();return[e,t,r,i,o,a]}function Kc(n){const{a:e,b:t,c:r,d:i,e:o,f:a}=n.getTransform().invertSelf();return[e,t,r,i,o,a]}function k0(n,e,t=!1,r=!0){if(e instanceof dC){const{pageWidth:i,pageHeight:o}=e.rawDims,{style:a}=n,l=Ds.isCSSRoundSupported,d=`var(--total-scale-factor) * ${i}px`,c=`var(--total-scale-factor) * ${o}px`,u=l?`round(down, ${d}, var(--scale-round-x))`:`calc(${d})`,f=l?`round(down, ${c}, var(--scale-round-y))`:`calc(${c})`;!t||e.rotation%180===0?(a.width=u,a.height=f):(a.width=f,a.height=u)}r&&n.setAttribute("data-main-rotation",e.rotation)}class Lu{constructor(){const{pixelRatio:e}=Lu;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(e,t,r,i,o=-1){let a=1/0,l=1/0,d=1/0;r=Lu.capPixels(r,o),r>0&&(a=Math.sqrt(r/(e*t))),i!==-1&&(l=i/e,d=i/t);const c=Math.min(a,l,d);return this.sx>c||this.sy>c?(this.sx=c,this.sy=c,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){const r=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,r):r}return e}}const $B=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class rue{static get isDarkMode(){var e;return Cn(this,"isDarkMode",!!((e=window==null?void 0:window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches))}}class iue{static get commentForegroundColor(){const e=document.createElement("span");e.classList.add("comment","sidebar");const{style:t}=e;t.width=t.height="0",t.display="none",t.color="var(--comment-fg-color)",document.body.append(e);const{color:r}=window.getComputedStyle(e);return e.remove(),Cn(this,"commentForegroundColor",cC(r))}}function sue(n,e){e=Bi(e??1,0,1);const t=255*(1-e);return n.map(r=>Math.round(r*e+t))}function hN(n,e){const t=n[0]/255,r=n[1]/255,i=n[2]/255,o=Math.max(t,r,i),a=Math.min(t,r,i),l=(o+a)/2;if(o===a)e[0]=e[1]=0;else{const d=o-a;switch(e[1]=l<.5?d/(o+a):d/(2-o-a),o){case t:e[0]=((r-i)/d+(ri?(r+.05)/(i+.05):(i+.05)/(r+.05)}const gN=new Map;function oue(n,e){const t=n[0]+n[1]*256+n[2]*65536+e[0]*16777216+e[1]*4294967296+e[2]*1099511627776;let r=gN.get(t);if(r)return r;const i=new Float32Array(9),o=i.subarray(0,3),a=i.subarray(3,6);hN(n,a);const l=i.subarray(6,9);hN(e,l);const d=l[2]<.5,c=d?12:4.5;if(a[2]=d?Math.sqrt(a[2]):1-Math.sqrt(1-a[2]),pN(a,l,o)p;){const g=a[2]=(u+f)/2;d===pN(a,l,o){t.delete()},{signal:t._signal}),h(this,ud).append(r)}async addAltText(e){const t=await e.render();q(this,Do,jx).call(this,t),h(this,ud).append(t,h(this,Do,uS)),R(this,ik,e)}addComment(e,t=null){if(h(this,xp))return;const r=e.renderForToolbar();if(!r)return;q(this,Do,jx).call(this,r);const i=R(this,jb,h(this,Do,uS));t?(h(this,ud).insertBefore(r,t),h(this,ud).insertBefore(i,t)):h(this,ud).append(r,i),R(this,xp,e),e.toolbar=this}addColorPicker(e){if(h(this,yp))return;R(this,yp,e);const t=e.renderButton();q(this,Do,jx).call(this,t),h(this,ud).append(t,h(this,Do,uS))}async addEditSignatureButton(e){const t=R(this,kb,await e.renderEditButton(h(this,cd)));q(this,Do,jx).call(this,t),h(this,ud).append(t,h(this,Do,uS))}removeButton(e){var t,r;switch(e){case"comment":(t=h(this,xp))==null||t.removeToolbarCommentButton(),R(this,xp,null),(r=h(this,jb))==null||r.remove(),R(this,jb,null);break}}async addButton(e,t){switch(e){case"colorPicker":t&&this.addColorPicker(t);break;case"altText":t&&await this.addAltText(t);break;case"editSignature":t&&await this.addEditSignatureButton(t);break;case"delete":this.addDeleteButton();break;case"comment":t&&this.addComment(t);break}}async addButtonBefore(e,t,r){if(!t&&e==="comment")return;const i=h(this,ud).querySelector(r);i&&e==="comment"&&this.addComment(t,i)}updateEditSignatureButton(e){h(this,kb)&&(h(this,kb).title=e)}remove(){var e;h(this,mp).remove(),(e=h(this,yp))==null||e.destroy(),R(this,yp,null)}};mp=new WeakMap,yp=new WeakMap,cd=new WeakMap,ud=new WeakMap,ik=new WeakMap,xp=new WeakMap,jb=new WeakMap,kb=new WeakMap,sk=new WeakMap,FT=new WeakSet,fV=function(e){e.stopPropagation()},Do=new WeakSet,pV=function(e){h(this,cd)._focusEventsAllowed=!1,$i(e)},gV=function(e){h(this,cd)._focusEventsAllowed=!0,$i(e)},jx=function(e){const t=h(this,cd)._uiManager._signal;return!(t instanceof AbortSignal)||t.aborted?!1:(e.addEventListener("focusin",q(this,Do,pV).bind(this),{capture:!0,signal:t}),e.addEventListener("focusout",q(this,Do,gV).bind(this),{capture:!0,signal:t}),e.addEventListener("contextmenu",Hd,{signal:t}),!0)},uS=function(){const e=document.createElement("div");return e.className="divider",e},N(yh,FT),N(yh,sk,null);let JB=yh;var ok,Mm,Ah,Tf,mV,yV,eI;class aue{constructor(e){N(this,Tf);N(this,ok,null);N(this,Mm,null);N(this,Ah);R(this,Ah,e)}show(e,t,r){const[i,o]=q(this,Tf,yV).call(this,t,r),{style:a}=h(this,Mm)||R(this,Mm,q(this,Tf,mV).call(this));e.append(h(this,Mm)),a.insetInlineEnd=`${100*i}%`,a.top=`calc(${100*o}% + var(--editor-toolbar-vert-offset))`}hide(){h(this,Mm).remove()}}ok=new WeakMap,Mm=new WeakMap,Ah=new WeakMap,Tf=new WeakSet,mV=function(){const e=R(this,Mm,document.createElement("div"));e.className="editToolbar",e.setAttribute("role","toolbar");const t=h(this,Ah)._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener("contextmenu",Hd,{signal:t});const r=R(this,ok,document.createElement("div"));return r.className="buttons",e.append(r),h(this,Ah).hasCommentManager()&&q(this,Tf,eI).call(this,"commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{h(this,Ah).commentSelection("floating_button")}),q(this,Tf,eI).call(this,"highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{h(this,Ah).highlightSelection("floating_button")}),e},yV=function(e,t){let r=0,i=0;for(const o of e){const a=o.y+o.height;if(ar){i=l,r=a;continue}t?l>i&&(i=l):l=1}static clearPointerType(){R(ni,Lm,null)}static clearPointerIds(){R(ni,zm,NaN),R(ni,Om,null)}static clearTimeStamp(){R(ni,_b,NaN)}};zm=new WeakMap,Om=new WeakMap,_b=new WeakMap,Lm=new WeakMap,N(ni,zm,NaN),N(ni,Om,null),N(ni,_b,NaN),N(ni,Lm,null);let Yo=ni;var DT;class lue{constructor(){N(this,DT,0)}get id(){return`${Gj}${Gi(this,DT)._++}`}}DT=new WeakMap;var Cb,ak,$o,Ab,R5;const W3=class W3{constructor(){N(this,Ab);N(this,Cb,dV());N(this,ak,0);N(this,$o,null)}static get _isSVGFittingCanvas(){const e='data:image/svg+xml;charset=UTF-8,',r=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=e;const o=i.decode().then(()=>(r.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(r.getImageData(0,0,1,1).data.buffer)[0]===0));return Cn(this,"_isSVGFittingCanvas",o)}async getFromFile(e){const{lastModified:t,name:r,size:i,type:o}=e;return q(this,Ab,R5).call(this,`${t}_${r}_${i}_${o}`,e)}async getFromUrl(e){return q(this,Ab,R5).call(this,e,e)}async getFromBlob(e,t){const r=await t;return q(this,Ab,R5).call(this,e,r)}async getFromId(e){h(this,$o)||R(this,$o,new Map);const t=h(this,$o).get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){const{blobPromise:r}=t;return delete t.blobPromise,this.getFromBlob(t.id,r)}return this.getFromUrl(t.url)}getFromCanvas(e,t){h(this,$o)||R(this,$o,new Map);let r=h(this,$o).get(e);if(r!=null&&r.bitmap)return r.refCounter+=1,r;const i=new OffscreenCanvas(t.width,t.height);return i.getContext("2d").drawImage(t,0,0),r={bitmap:i.transferToImageBitmap(),id:`image_${h(this,Cb)}_${Gi(this,ak)._++}`,refCounter:1,isSvg:!1},h(this,$o).set(e,r),h(this,$o).set(r.id,r),r}getSvgUrl(e){const t=h(this,$o).get(e);return t!=null&&t.isSvg?t.svgUrl:null}deleteId(e){var i;h(this,$o)||R(this,$o,new Map);const t=h(this,$o).get(e);if(!t||(t.refCounter-=1,t.refCounter!==0))return;const{bitmap:r}=t;if(!t.url&&!t.file){const o=new OffscreenCanvas(r.width,r.height);o.getContext("bitmaprenderer").transferFromImageBitmap(r),t.blobPromise=o.convertToBlob()}(i=r.close)==null||i.call(r),t.bitmap=null}isValidId(e){return e.startsWith(`image_${h(this,Cb)}_`)}};Cb=new WeakMap,ak=new WeakMap,$o=new WeakMap,Ab=new WeakSet,R5=async function(e,t){h(this,$o)||R(this,$o,new Map);let r=h(this,$o).get(e);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${h(this,Cb)}_${Gi(this,ak)._++}`,refCounter:0,isSvg:!1});let i;if(typeof t=="string"?(r.url=t,i=await E3(t,"blob")):t instanceof File?i=r.file=t:t instanceof Blob&&(i=t),i.type==="image/svg+xml"){const o=W3._isSVGFittingCanvas,a=new FileReader,l=new Image,d=new Promise((c,u)=>{l.onload=()=>{r.bitmap=l,r.isSvg=!0,c()},a.onload=async()=>{const f=r.svgUrl=a.result;l.src=await o?`${f}#svgView(preserveAspectRatio(none))`:f},l.onerror=a.onerror=u});a.readAsDataURL(i),await d}else r.bitmap=await createImageBitmap(i);r.refCounter=1}catch(i){Bn(i),r=null}return h(this,$o).set(e,r),r&&h(this,$o).set(r.id,r),r};let tI=W3;var ys,bp,lk,Xi;class due{constructor(e=128){N(this,ys,[]);N(this,bp,!1);N(this,lk);N(this,Xi,-1);R(this,lk,e)}add({cmd:e,undo:t,post:r,mustExec:i,type:o=NaN,overwriteIfSameType:a=!1,keepUndo:l=!1}){if(i&&e(),h(this,bp))return;const d={cmd:e,undo:t,post:r,type:o};if(h(this,Xi)===-1){h(this,ys).length>0&&(h(this,ys).length=0),R(this,Xi,0),h(this,ys).push(d);return}if(a&&h(this,ys)[h(this,Xi)].type===o){l&&(d.undo=h(this,ys)[h(this,Xi)].undo),h(this,ys)[h(this,Xi)]=d;return}const c=h(this,Xi)+1;c===h(this,lk)?h(this,ys).splice(0,1):(R(this,Xi,c),c=0;t--)if(h(this,ys)[t].type!==e){h(this,ys).splice(t+1,h(this,Xi)-t),R(this,Xi,t);return}h(this,ys).length=0,R(this,Xi,-1)}}destroy(){R(this,ys,null)}}ys=new WeakMap,bp=new WeakMap,lk=new WeakMap,Xi=new WeakMap;var ET,bV;class uC{constructor(e){N(this,ET);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:t}=Ds.platform;for(const[r,i,o={}]of e)for(const a of r){const l=a.startsWith("mac+");t&&l?(this.callbacks.set(a.slice(4),{callback:i,options:o}),this.allKeys.add(a.split("+").at(-1))):!t&&!l&&(this.callbacks.set(a,{callback:i,options:o}),this.allKeys.add(a.split("+").at(-1)))}}exec(e,t){if(!this.allKeys.has(t.key))return;const r=this.callbacks.get(q(this,ET,bV).call(this,t));if(!r)return;const{callback:i,options:{bubbles:o=!1,args:a=[],checker:l=null}}=r;l&&!l(e,t)||(i.bind(e,...a,t)(),o||$i(t))}}ET=new WeakSet,bV=function(e){e.altKey&&this.buffer.push("alt"),e.ctrlKey&&this.buffer.push("ctrl"),e.metaKey&&this.buffer.push("meta"),e.shiftKey&&this.buffer.push("shift"),this.buffer.push(e.key);const t=this.buffer.join("+");return this.buffer.length=0,t};const PT=class PT{get _colors(){const e=new Map([["CanvasText",null],["Canvas",null]]);return nue(e),Cn(this,"_colors",e)}convert(e){const t=cC(e);if(!window.matchMedia("(forced-colors: active)").matches)return t;for(const[r,i]of this._colors)if(i.every((o,a)=>o===t[a]))return PT._colorsMapping.get(r);return t}getHexCode(e){const t=this._colors.get(e);return t?yt.makeHexColor(...t):e}};ve(PT,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let nI=PT;var Tb,ml,Fb,as,Yi,Db,Eb,pa,Pb,hd,to,vp,wp,Sp,jp,ru,fd,Nm,dk,ck,Rb,uk,iu,kp,Bb,_p,su,RT,Th,Ib,hk,Cp,Wm,Mb,Ap,fk,As,Kr,Fh,Tp,Fp,pk,zb,gk,Dp,ou,Dh,mk,yk,pd,Tt,B5,rI,vV,wV,SV,hS,jV,kV,_V,iI,CV,AV,TV,FV,ua,fh,DV,EV,sI,PV,fS,oI;const Qx=class Qx{constructor(e,t,r,i,o,a,l,d,c,u,f,p,g,m,y,v){N(this,Tt);N(this,Tb,new AbortController);N(this,ml,null);N(this,Fb,null);N(this,as,new Map);N(this,Yi,new Map);N(this,Db,null);N(this,Eb,null);N(this,pa,null);N(this,Pb,null);N(this,hd,new due);N(this,to,null);N(this,vp,null);N(this,wp,null);N(this,Sp,0);N(this,jp,new Set);N(this,ru,null);N(this,fd,null);N(this,Nm,new Set);ve(this,"_editorUndoBar",null);N(this,dk,!1);N(this,ck,!1);N(this,Rb,!1);N(this,uk,null);N(this,iu,null);N(this,kp,null);N(this,Bb,null);N(this,_p,!1);N(this,su,null);N(this,RT,new lue);N(this,Th,!1);N(this,Ib,!1);N(this,hk,!1);N(this,Cp,null);N(this,Wm,null);N(this,Mb,null);N(this,Ap,null);N(this,fk,null);N(this,As,jn.NONE);N(this,Kr,new Set);N(this,Fh,null);N(this,Tp,null);N(this,Fp,null);N(this,pk,null);N(this,zb,null);N(this,gk,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});N(this,Dp,[0,0]);N(this,ou,null);N(this,Dh,null);N(this,mk,null);N(this,yk,null);N(this,pd,null);const x=this._signal=h(this,Tb).signal;R(this,Dh,e),R(this,mk,t),R(this,yk,r),R(this,Eb,i),R(this,to,o),R(this,Tp,a),R(this,zb,d),this._eventBus=l,l._on("editingaction",this.onEditingAction.bind(this),{signal:x}),l._on("pagechanging",this.onPageChanging.bind(this),{signal:x}),l._on("scalechanging",this.onScaleChanging.bind(this),{signal:x}),l._on("rotationchanging",this.onRotationChanging.bind(this),{signal:x}),l._on("setpreference",this.onSetPreference.bind(this),{signal:x}),l._on("switchannotationeditorparams",w=>this.updateParams(w.type,w.value),{signal:x}),window.addEventListener("pointerdown",()=>{R(this,Ib,!0)},{capture:!0,signal:x}),window.addEventListener("pointerup",()=>{R(this,Ib,!1)},{capture:!0,signal:x}),window.addEventListener("beforeunload",q(this,Tt,vV).bind(this),{capture:!0,signal:x}),q(this,Tt,jV).call(this),q(this,Tt,FV).call(this),q(this,Tt,iI).call(this),R(this,pa,d.annotationStorage),R(this,uk,d.filterFactory),R(this,Fp,c),R(this,Bb,u||null),R(this,dk,f),R(this,ck,p),R(this,Rb,g),R(this,fk,m||null),this.viewParameters={realScale:Wg.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=y||null,this._supportsPinchToZoom=v!==!1,o==null||o.setSidebarUiManager(this)}static get _keyboardManager(){const e=Qx.prototype,t=a=>h(a,Dh).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&a.hasSomethingToControl(),r=(a,{target:l})=>{if(l instanceof HTMLInputElement){const{type:d}=l;return d!=="text"&&d!=="number"}return!0},i=this.TRANSLATE_SMALL,o=this.TRANSLATE_BIG;return Cn(this,"_keyboardManager",new uC([[["ctrl+a","mac+meta+a"],e.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],e.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],e.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],e.delete,{checker:r}],[["Enter","mac+Enter"],e.addNewEditorFromKeyboard,{checker:(a,{target:l})=>!(l instanceof HTMLButtonElement)&&h(a,Dh).contains(l)&&!a.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(a,{target:l})=>!(l instanceof HTMLButtonElement)&&h(a,Dh).contains(document.activeElement)}],[["Escape","mac+Escape"],e.unselectAll],[["ArrowLeft","mac+ArrowLeft"],e.translateSelectedEditors,{args:[-i,0],checker:t}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e.translateSelectedEditors,{args:[-o,0],checker:t}],[["ArrowRight","mac+ArrowRight"],e.translateSelectedEditors,{args:[i,0],checker:t}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e.translateSelectedEditors,{args:[o,0],checker:t}],[["ArrowUp","mac+ArrowUp"],e.translateSelectedEditors,{args:[0,-i],checker:t}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e.translateSelectedEditors,{args:[0,-o],checker:t}],[["ArrowDown","mac+ArrowDown"],e.translateSelectedEditors,{args:[0,i],checker:t}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e.translateSelectedEditors,{args:[0,o],checker:t}]]))}destroy(){var e,t,r,i,o,a,l,d,c;(e=h(this,pd))==null||e.resolve(),R(this,pd,null),(t=h(this,Tb))==null||t.abort(),R(this,Tb,null),this._signal=null;for(const u of h(this,Yi).values())u.destroy();h(this,Yi).clear(),h(this,as).clear(),h(this,Nm).clear(),(r=h(this,Ap))==null||r.clear(),R(this,ml,null),h(this,Kr).clear(),h(this,hd).destroy(),(i=h(this,Eb))==null||i.destroy(),(o=h(this,to))==null||o.destroy(),(a=h(this,Tp))==null||a.destroy(),(l=h(this,su))==null||l.hide(),R(this,su,null),(d=h(this,Mb))==null||d.destroy(),R(this,Mb,null),R(this,Fb,null),h(this,iu)&&(clearTimeout(h(this,iu)),R(this,iu,null)),h(this,ou)&&(clearTimeout(h(this,ou)),R(this,ou,null)),(c=this._editorUndoBar)==null||c.destroy(),R(this,zb,null)}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return h(this,fk)}get useNewAltTextFlow(){return h(this,ck)}get useNewAltTextWhenAddingImage(){return h(this,Rb)}get hcmFilter(){return Cn(this,"hcmFilter",h(this,Fp)?h(this,uk).addHCMFilter(h(this,Fp).foreground,h(this,Fp).background):"none")}get direction(){return Cn(this,"direction",getComputedStyle(h(this,Dh)).direction)}get _highlightColors(){return Cn(this,"_highlightColors",h(this,Bb)?new Map(h(this,Bb).split(",").map(e=>(e=e.split("=").map(t=>t.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){const{_highlightColors:e}=this;if(!e)return Cn(this,"highlightColors",null);const t=new Map,r=!!h(this,Fp);for(const[i,o]of e){const a=i.endsWith("_HCM");if(r&&a){t.set(i.replace("_HCM",""),o);continue}!r&&!a&&t.set(i,o)}return Cn(this,"highlightColors",t)}get highlightColorNames(){return Cn(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;const t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),R(this,wp,e)}setMainHighlightColorPicker(e){R(this,Mb,e)}editAltText(e,t=!1){var r;(r=h(this,Eb))==null||r.editAltText(this,e,t)}hasCommentManager(){return!!h(this,to)}editComment(e,t,r,i){var o;(o=h(this,to))==null||o.showDialog(this,e,t,r,i)}selectComment(e,t){const r=h(this,Yi).get(e),i=r==null?void 0:r.getEditorByUID(t);i==null||i.toggleComment(!0,!0)}updateComment(e){var t;(t=h(this,to))==null||t.updateComment(e.getData())}updatePopupColor(e){var t;(t=h(this,to))==null||t.updatePopupColor(e)}removeComment(e){var t;(t=h(this,to))==null||t.removeComments([e.uid])}deleteComment(e,t){const r=()=>{e.comment=t},i=()=>{var o;(o=this._editorUndoBar)==null||o.show(r,"comment"),this.toggleComment(null),e.comment=null};this.addCommands({cmd:i,undo:r,mustExec:!0})}toggleComment(e,t,r=void 0){var i;(i=h(this,to))==null||i.toggleCommentPopup(e,t,r)}makeCommentColor(e,t){var r;return e&&((r=h(this,to))==null?void 0:r.makeCommentColor(e,t))||null}getCommentDialogElement(){var e;return((e=h(this,to))==null?void 0:e.dialogElement)||null}async waitForEditorsRendered(e){if(h(this,Yi).has(e-1))return;const{resolve:t,promise:r}=Promise.withResolvers(),i=o=>{o.pageNumber===e&&(this._eventBus._off("editorsrendered",i),t())};this._eventBus.on("editorsrendered",i),await r}getSignature(e){var t;(t=h(this,Tp))==null||t.getSignature({uiManager:this,editor:e})}get signatureManager(){return h(this,Tp)}switchToMode(e,t){this._eventBus.on("annotationeditormodechanged",t,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch("setpreference",{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){switch(e){case"enableNewAltTextWhenAddingImage":R(this,Rb,t);break}}onPageChanging({pageNumber:e}){R(this,Sp,e-1)}deletePage(e){for(const t of this.getEditors(e))t.remove();h(this,Yi).delete(e),h(this,Sp)===e&&R(this,Sp,0)}focusMainContainer(){h(this,Dh).focus()}findParent(e,t){for(const r of h(this,Yi).values()){const{x:i,y:o,width:a,height:l}=r.div.getBoundingClientRect();if(e>=i&&e<=i+a&&t>=o&&t<=o+l)return r}return null}disableUserSelect(e=!1){h(this,mk).classList.toggle("noUserSelect",e)}addShouldRescale(e){h(this,Nm).add(e)}removeShouldRescale(e){h(this,Nm).delete(e)}onScaleChanging({scale:e}){var t;this.commitOrRemove(),this.viewParameters.realScale=e*Wg.PDF_TO_CSS_UNITS;for(const r of h(this,Nm))r.onScaleChanging();(t=h(this,wp))==null||t.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}highlightSelection(e="",t=!1){const r=document.getSelection();if(!r||r.isCollapsed)return;const{anchorNode:i,anchorOffset:o,focusNode:a,focusOffset:l}=r,d=r.toString(),u=q(this,Tt,B5).call(this,r).closest(".textLayer"),f=this.getSelectionBoxes(u);if(!f)return;r.empty();const p=q(this,Tt,rI).call(this,u),g=h(this,As)===jn.NONE,m=()=>{const y=p==null?void 0:p.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:f,anchorNode:i,anchorOffset:o,focusNode:a,focusOffset:l,text:d});g&&this.showAllEditors("highlight",!0,!0),t&&(y==null||y.editComment())};if(g){this.switchToMode(jn.HIGHLIGHT,m);return}m()}commentSelection(e=""){this.highlightSelection(e,!0)}getAndRemoveDataFromAnnotationStorage(e){if(!h(this,pa))return null;const t=`${Gj}${e}`,r=h(this,pa).getRawValue(t);return r&&h(this,pa).remove(t),r}addToAnnotationStorage(e){!e.isEmpty()&&h(this,pa)&&!h(this,pa).has(e.id)&&h(this,pa).setValue(e.id,e)}a11yAlert(e,t=null){const r=h(this,yk);r&&(r.setAttribute("data-l10n-id",e),t?r.setAttribute("data-l10n-args",JSON.stringify(t)):r.removeAttribute("data-l10n-args"))}blur(){if(this.isShiftKeyDown=!1,h(this,_p)&&(R(this,_p,!1),q(this,Tt,hS).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:e}=document;for(const t of h(this,Kr))if(t.div.contains(e)){R(this,Wm,[t,e]),t._focusEventsAllowed=!1;break}}focus(){if(!h(this,Wm))return;const[e,t]=h(this,Wm);R(this,Wm,null),t.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}addEditListeners(){q(this,Tt,iI).call(this),this.setEditingState(!0)}removeEditListeners(){q(this,Tt,CV).call(this),this.setEditingState(!1)}dragOver(e){for(const{type:t}of e.dataTransfer.items)for(const r of h(this,fd))if(r.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect="copy",e.preventDefault();return}}drop(e){for(const t of e.dataTransfer.items)for(const r of h(this,fd))if(r.isHandlingMimeForPasting(t.type)){r.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){var r;if(e.preventDefault(),(r=h(this,ml))==null||r.commitOrRemove(),!this.hasSelection)return;const t=[];for(const i of h(this,Kr)){const o=i.serialize(!0);o&&t.push(o)}t.length!==0&&e.clipboardData.setData("application/pdfjs",JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();const{clipboardData:t}=e;for(const o of t.items)for(const a of h(this,fd))if(a.isHandlingMimeForPasting(o.type)){a.paste(o,this.currentLayer);return}let r=t.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(o){Bn(`paste: "${o.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();const i=this.currentLayer;try{const o=[];for(const d of r){const c=await i.deserialize(d);if(!c)return;o.push(c)}const a=()=>{for(const d of o)q(this,Tt,sI).call(this,d);q(this,Tt,oI).call(this,o)},l=()=>{for(const d of o)d.remove()};this.addCommands({cmd:a,undo:l,mustExec:!0})}catch(o){Bn(`paste: "${o.message}".`)}}keydown(e){!this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!0),h(this,As)!==jn.NONE&&!this.isEditorHandlingKeyboard&&Qx._keyboardManager.exec(this,e)}keyup(e){this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!1,h(this,_p)&&(R(this,_p,!1),q(this,Tt,hS).call(this,"main_toolbar")))}onEditingAction({name:e}){switch(e){case"undo":case"redo":case"delete":case"selectAll":this[e]();break;case"highlightSelection":this.highlightSelection("context_menu");break;case"commentSelection":this.commentSelection("context_menu");break}}updatePageIndex(e,t){for(const i of this.getEditors(e))i.pageIndex=t;const r=h(this,Db).get(e);r&&(r.pageIndex=t,h(this,Yi).set(t,r),h(this,Th)?r.enable():r.disable())}startUpdatePages(){R(this,Db,new Map(h(this,Yi))),h(this,Yi).clear()}endUpdatePages(){R(this,Db,null)}clonePage(e,t){for(const r of this.getEditors(e)){const i=r.serialize(r.mode!==jn.HIGHLIGHT);i&&(i.pageIndex=t,i.id=this.getId(),i.isClone=!0,delete i.popupRef,h(this,pa).setValue(i.id,i))}}findClonesForPage(e){const t=[],{pageIndex:r}=e;for(const[i,o]of h(this,pa))o.pageIndex===r&&o.isClone&&(h(this,pa).remove(i),t.push(e.deserialize(o).then(a=>{a&&(a.isClone=!0,e.addOrRebuild(a))})));return Promise.all(t)}setEditingState(e){e?(q(this,Tt,kV).call(this),q(this,Tt,AV).call(this),q(this,Tt,ua).call(this,{isEditing:h(this,As)!==jn.NONE,isEmpty:q(this,Tt,fS).call(this),hasSomethingToUndo:h(this,hd).hasSomethingToUndo(),hasSomethingToRedo:h(this,hd).hasSomethingToRedo(),hasSelectedEditor:!1})):(q(this,Tt,_V).call(this),q(this,Tt,TV).call(this),q(this,Tt,ua).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!h(this,fd)){R(this,fd,e);for(const t of h(this,fd))q(this,Tt,fh).call(this,t.defaultPropertiesToUpdate)}}getId(){return h(this,RT).id}get currentLayer(){return h(this,Yi).get(h(this,Sp))}getLayer(e){return h(this,Yi).get(e)}get currentPageIndex(){return h(this,Sp)}addLayer(e){h(this,Yi).set(e.pageIndex,e),h(this,Th)?e.enable():e.disable()}removeLayer(e){h(this,Yi).delete(e.pageIndex)}async updateMode(e,t=null,r=!1,i=!1,o=!1,a=!1){var l,d,c,u,f,p;if(h(this,As)!==e&&!(h(this,pd)&&(await h(this,pd).promise,!h(this,pd)))){if(R(this,pd,Promise.withResolvers()),(l=h(this,wp))==null||l.commitOrRemove(),h(this,As)===jn.POPUP&&((d=h(this,to))==null||d.hideSidebar()),(c=h(this,to))==null||c.destroyPopup(),R(this,As,e),e===jn.NONE){this.setEditingState(!1),q(this,Tt,EV).call(this);for(const g of h(this,as).values())g.hideStandaloneCommentButton();(u=this._editorUndoBar)==null||u.hide(),this.toggleComment(null),h(this,pd).resolve();return}for(const g of h(this,as).values())g.addStandaloneCommentButton();e===jn.SIGNATURE&&await((f=h(this,Tp))==null?void 0:f.loadSignatures()),r&&Yo.clearPointerType(),this.setEditingState(!0),await q(this,Tt,DV).call(this),this.unselectAll();for(const g of h(this,Yi).values())g.updateMode(e);if(e===jn.POPUP){h(this,Fb)||R(this,Fb,await h(this,zb).getAnnotationsByType(new Set(h(this,fd).map(y=>y._editorType))));const g=new Set,m=[];for(const y of h(this,as).values()){const{annotationElementId:v,hasComment:x,deleted:w}=y;v&&g.add(v),x&&!w&&m.push(y.getData())}for(const y of h(this,Fb)){const{id:v,popupRef:x,contentsObj:w}=y;x&&(w!=null&&w.str)&&!g.has(v)&&!h(this,jp).has(v)&&m.push(y)}(p=h(this,to))==null||p.showSidebar(m)}if(!t){i&&this.addNewEditorFromKeyboard(),h(this,pd).resolve();return}for(const g of h(this,as).values())g.uid===t?(this.setSelected(g),a?g.editComment():o?g.enterInEditMode():g.focus()):g.unselect();h(this,pd).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==h(this,As)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...e})}updateParams(e,t){if(h(this,fd)){switch(e){case Wn.CREATE:this.currentLayer.addNewEditor(t);return;case Wn.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(h(this,pk)||R(this,pk,new Map)).set(e,t),this.showAllEditors("highlight",t);break}if(this.hasSelection)for(const r of h(this,Kr))r.updateParams(e,t);else for(const r of h(this,fd))r.updateDefaultParams(e,t)}}showAllEditors(e,t,r=!1){var o;for(const a of h(this,as).values())a.editorType===e&&a.show(t);(((o=h(this,pk))==null?void 0:o.get(Wn.HIGHLIGHT_SHOW_ALL))??!0)!==t&&q(this,Tt,fh).call(this,[[Wn.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(h(this,hk)!==e){R(this,hk,e);for(const t of h(this,Yi).values())e?t.disableClick():t.enableClick(),t.div.classList.toggle("waiting",e)}}*getEditors(e){for(const t of h(this,as).values())t.pageIndex===e&&(yield t)}getEditor(e){return h(this,as).get(e)}addEditor(e){h(this,as).set(e.id,e)}removeEditor(e){var t,r;e.div.contains(document.activeElement)&&(h(this,iu)&&clearTimeout(h(this,iu)),R(this,iu,setTimeout(()=>{this.focusMainContainer(),R(this,iu,null)},0))),h(this,as).delete(e.id),e.annotationElementId&&((t=h(this,Ap))==null||t.delete(e.annotationElementId)),this.unselect(e),(!e.annotationElementId||!h(this,jp).has(e.annotationElementId))&&((r=h(this,pa))==null||r.remove(e.id))}addDeletedAnnotationElement(e){h(this,jp).add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return h(this,jp).has(e)}removeDeletedAnnotationElement(e){h(this,jp).delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}setActiveEditor(e){h(this,ml)!==e&&(R(this,ml,e),e&&q(this,Tt,fh).call(this,e.propertiesToUpdate))}updateUI(e){h(this,Tt,PV)===e&&q(this,Tt,fh).call(this,e.propertiesToUpdate)}updateUIForDefaultProperties(e){q(this,Tt,fh).call(this,e.defaultPropertiesToUpdate)}toggleSelected(e){if(h(this,Kr).has(e)){h(this,Kr).delete(e),e.unselect(),q(this,Tt,ua).call(this,{hasSelectedEditor:this.hasSelection});return}h(this,Kr).add(e),e.select(),q(this,Tt,fh).call(this,e.propertiesToUpdate),q(this,Tt,ua).call(this,{hasSelectedEditor:!0})}setSelected(e){var t,r;this.updateToolbar({mode:e.mode,editId:e.uid}),(t=h(this,wp))==null||t.commitOrRemove();for(const i of h(this,Kr))i!==e&&i.unselect();(r=h(this,to))==null||r.destroyPopup(),h(this,Kr).clear(),h(this,Kr).add(e),e.select(),q(this,Tt,fh).call(this,e.propertiesToUpdate),q(this,Tt,ua).call(this,{hasSelectedEditor:!0})}isSelected(e){return h(this,Kr).has(e)}get firstSelectedEditor(){return h(this,Kr).values().next().value}unselect(e){e.unselect(),h(this,Kr).delete(e),q(this,Tt,ua).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return h(this,Kr).size!==0}get isEnterHandled(){return h(this,Kr).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){var e;h(this,hd).undo(),q(this,Tt,ua).call(this,{hasSomethingToUndo:h(this,hd).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:q(this,Tt,fS).call(this)}),(e=this._editorUndoBar)==null||e.hide()}redo(){h(this,hd).redo(),q(this,Tt,ua).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:h(this,hd).hasSomethingToRedo(),isEmpty:q(this,Tt,fS).call(this)})}addCommands(e){h(this,hd).add(e),q(this,Tt,ua).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:q(this,Tt,fS).call(this)})}cleanUndoStack(e){h(this,hd).cleanType(e)}delete(){var o;this.commitOrRemove();const e=(o=this.currentLayer)==null?void 0:o.endDrawingSession(!0);if(!this.hasSelection&&!e)return;const t=e?[e]:[...h(this,Kr)],r=()=>{var a;(a=this._editorUndoBar)==null||a.show(i,t.length===1?t[0].editorType:t.length);for(const l of t)l.remove()},i=()=>{for(const a of t)q(this,Tt,sI).call(this,a)};this.addCommands({cmd:r,undo:i,mustExec:!0})}commitOrRemove(){var e;(e=h(this,ml))==null||e.commitOrRemove()}hasSomethingToControl(){return h(this,ml)||this.hasSelection}selectAll(){for(const e of h(this,Kr))e.commit();q(this,Tt,oI).call(this,h(this,as).values())}unselectAll(){var e,t;if(!(h(this,ml)&&(h(this,ml).commitOrRemove(),h(this,As)!==jn.NONE))&&!((e=h(this,wp))!=null&&e.commitOrRemove())&&((t=h(this,to))==null||t.destroyPopup(),!!this.hasSelection)){for(const r of h(this,Kr))r.unselect();h(this,Kr).clear(),q(this,Tt,ua).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(e,t,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;h(this,Dp)[0]+=e,h(this,Dp)[1]+=t;const[i,o]=h(this,Dp),a=[...h(this,Kr)],l=1e3;h(this,ou)&&clearTimeout(h(this,ou)),R(this,ou,setTimeout(()=>{R(this,ou,null),h(this,Dp)[0]=h(this,Dp)[1]=0,this.addCommands({cmd:()=>{for(const d of a)h(this,as).has(d.id)&&(d.translateInPage(i,o),d.translationDone())},undo:()=>{for(const d of a)h(this,as).has(d.id)&&(d.translateInPage(-i,-o),d.translationDone())},mustExec:!1})},l));for(const d of a)d.translateInPage(e,t),d.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),R(this,ru,new Map);for(const e of h(this,Kr))h(this,ru).set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!h(this,ru))return!1;this.disableUserSelect(!1);const e=h(this,ru);R(this,ru,null);let t=!1;for(const[{x:i,y:o,pageIndex:a},l]of e)l.newX=i,l.newY=o,l.newPageIndex=a,t||(t=i!==l.savedX||o!==l.savedY||a!==l.savedPageIndex);if(!t)return!1;const r=(i,o,a,l)=>{if(h(this,as).has(i.id)){const d=h(this,Yi).get(l);d?i._setParentAndPosition(d,o,a):(i.pageIndex=l,i.x=o,i.y=a)}};return this.addCommands({cmd:()=>{for(const[i,{newX:o,newY:a,newPageIndex:l}]of e)r(i,o,a,l)},undo:()=>{for(const[i,{savedX:o,savedY:a,savedPageIndex:l}]of e)r(i,o,a,l)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(h(this,ru))for(const r of h(this,ru).keys())r.drag(e,t)}rebuild(e){if(e.parent===null){const t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){var e;return((e=this.getActive())==null?void 0:e.shouldGetKeyboardEvents())||h(this,Kr).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return h(this,ml)===e}getActive(){return h(this,ml)}getMode(){return h(this,As)}isEditingMode(){return h(this,As)!==jn.NONE}get imageManager(){return Cn(this,"imageManager",new tI)}getSelectionBoxes(e){if(!e)return null;const t=document.getSelection();for(let c=0,u=t.rangeCount;c({x:(u-i)/a,y:1-(c+f-r)/o,width:p/a,height:f/o});break;case"180":l=(c,u,f,p)=>({x:1-(c+f-r)/o,y:1-(u+p-i)/a,width:f/o,height:p/a});break;case"270":l=(c,u,f,p)=>({x:1-(u+p-i)/a,y:(c-r)/o,width:p/a,height:f/o});break;default:l=(c,u,f,p)=>({x:(c-r)/o,y:(u-i)/a,width:f/o,height:p/a});break}const d=[];for(let c=0,u=t.rangeCount;c{p.type==="pointerup"&&p.button!==0||(c.abort(),d==null||d.toggleDrawing(!0),p.type==="pointerup"&&q(this,Tt,hS).call(this,"main_toolbar"))};window.addEventListener("pointerup",f,{signal:u}),window.addEventListener("blur",f,{signal:u})}else d==null||d.toggleDrawing(!0),q(this,Tt,hS).call(this,"main_toolbar")}},hS=function(e=""){h(this,As)===jn.HIGHLIGHT?this.highlightSelection(e):h(this,dk)&&q(this,Tt,wV).call(this)},jV=function(){document.addEventListener("selectionchange",q(this,Tt,SV).bind(this),{signal:this._signal})},kV=function(){if(h(this,kp))return;R(this,kp,new AbortController);const e=this.combinedSignal(h(this,kp));window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})},_V=function(){var e;(e=h(this,kp))==null||e.abort(),R(this,kp,null)},iI=function(){if(h(this,Cp))return;R(this,Cp,new AbortController);const e=this.combinedSignal(h(this,Cp));window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})},CV=function(){var e;(e=h(this,Cp))==null||e.abort(),R(this,Cp,null)},AV=function(){if(h(this,vp))return;R(this,vp,new AbortController);const e=this.combinedSignal(h(this,vp));document.addEventListener("copy",this.copy.bind(this),{signal:e}),document.addEventListener("cut",this.cut.bind(this),{signal:e}),document.addEventListener("paste",this.paste.bind(this),{signal:e})},TV=function(){var e;(e=h(this,vp))==null||e.abort(),R(this,vp,null)},FV=function(){const e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})},ua=function(e){Object.entries(e).some(([r,i])=>h(this,gk)[r]!==i)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(h(this,gk),e)}),h(this,As)===jn.HIGHLIGHT&&e.hasSelectedEditor===!1&&q(this,Tt,fh).call(this,[[Wn.HIGHLIGHT_FREE,!0]]))},fh=function(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})},DV=async function(){if(!h(this,Th)){R(this,Th,!0);const e=[];for(const t of h(this,Yi).values())e.push(t.enable());await Promise.all(e);for(const t of h(this,as).values())t.enable()}},EV=function(){if(this.unselectAll(),h(this,Th)){R(this,Th,!1);for(const e of h(this,Yi).values())e.disable();for(const e of h(this,as).values())e.disable()}},sI=function(e){const t=h(this,Yi).get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))},PV=function(){let e=null;for(e of h(this,Kr));return e},fS=function(){if(h(this,as).size===0)return!0;if(h(this,as).size===1)for(const e of h(this,as).values())return e.isEmpty();return!1},oI=function(e){for(const t of h(this,Kr))t.unselect();h(this,Kr).clear();for(const t of e)t.isEmpty()||(h(this,Kr).add(t),t.select());q(this,Tt,ua).call(this,{hasSelectedEditor:this.hasSelection})},ve(Qx,"TRANSLATE_SMALL",1),ve(Qx,"TRANSLATE_BIG",10);let _0=Qx;var no,au,dc,Ob,lu,yl,Lb,du,Ha,Eh,Um,cu,Ep,Cc,pS,I5;const ha=class ha{constructor(e){N(this,Cc);N(this,no,null);N(this,au,!1);N(this,dc,null);N(this,Ob,null);N(this,lu,null);N(this,yl,null);N(this,Lb,!1);N(this,du,null);N(this,Ha,null);N(this,Eh,null);N(this,Um,null);N(this,cu,!1);R(this,Ha,e),R(this,cu,e._uiManager.useNewAltTextFlow),h(ha,Ep)||R(ha,Ep,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(e){ha._l10n??(ha._l10n=e)}async render(){const e=R(this,dc,document.createElement("button"));e.className="altText",e.tabIndex="0";const t=R(this,Ob,document.createElement("span"));e.append(t),h(this,cu)?(e.classList.add("new"),e.setAttribute("data-l10n-id",h(ha,Ep).missing),t.setAttribute("data-l10n-id",h(ha,Ep)["missing-label"])):(e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const r=h(this,Ha)._uiManager._signal;e.addEventListener("contextmenu",Hd,{signal:r}),e.addEventListener("pointerdown",o=>o.stopPropagation(),{signal:r});const i=o=>{o.preventDefault(),h(this,Ha)._uiManager.editAltText(h(this,Ha)),h(this,cu)&&h(this,Ha)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:h(this,Cc,pS)}})};return e.addEventListener("click",i,{capture:!0,signal:r}),e.addEventListener("keydown",o=>{o.target===e&&o.key==="Enter"&&(R(this,Lb,!0),i(o))},{signal:r}),await q(this,Cc,I5).call(this),e}finish(){h(this,dc)&&(h(this,dc).focus({focusVisible:h(this,Lb)}),R(this,Lb,!1))}isEmpty(){return h(this,cu)?h(this,no)===null:!h(this,no)&&!h(this,au)}hasData(){return h(this,cu)?h(this,no)!==null||!!h(this,Eh):this.isEmpty()}get guessedText(){return h(this,Eh)}async setGuessedText(e){h(this,no)===null&&(R(this,Eh,e),R(this,Um,await ha._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e})),q(this,Cc,I5).call(this))}toggleAltTextBadge(e=!1){var t;if(!h(this,cu)||h(this,no)){(t=h(this,du))==null||t.remove(),R(this,du,null);return}if(!h(this,du)){const r=R(this,du,document.createElement("div"));r.className="noAltTextBadge",h(this,Ha).div.append(r)}h(this,du).classList.toggle("hidden",!e)}serialize(e){let t=h(this,no);return!e&&h(this,Eh)===t&&(t=h(this,Um)),{altText:t,decorative:h(this,au),guessedText:h(this,Eh),textWithDisclaimer:h(this,Um)}}get data(){return{altText:h(this,no),decorative:h(this,au)}}set data({altText:e,decorative:t,guessedText:r,textWithDisclaimer:i,cancel:o=!1}){r&&(R(this,Eh,r),R(this,Um,i)),!(h(this,no)===e&&h(this,au)===t)&&(o||(R(this,no,e),R(this,au,t)),q(this,Cc,I5).call(this))}toggle(e=!1){h(this,dc)&&(!e&&h(this,yl)&&(clearTimeout(h(this,yl)),R(this,yl,null)),h(this,dc).disabled=!e)}shown(){h(this,Ha)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:h(this,Cc,pS)}})}destroy(){var e,t;(e=h(this,dc))==null||e.remove(),R(this,dc,null),R(this,Ob,null),R(this,lu,null),(t=h(this,du))==null||t.remove(),R(this,du,null)}};no=new WeakMap,au=new WeakMap,dc=new WeakMap,Ob=new WeakMap,lu=new WeakMap,yl=new WeakMap,Lb=new WeakMap,du=new WeakMap,Ha=new WeakMap,Eh=new WeakMap,Um=new WeakMap,cu=new WeakMap,Ep=new WeakMap,Cc=new WeakSet,pS=function(){return h(this,no)&&"added"||h(this,no)===null&&this.guessedText&&"review"||"missing"},I5=async function(){var i,o,a;const e=h(this,dc);if(!e)return;if(h(this,cu)){if(e.classList.toggle("done",!!h(this,no)),e.setAttribute("data-l10n-id",h(ha,Ep)[h(this,Cc,pS)]),(i=h(this,Ob))==null||i.setAttribute("data-l10n-id",h(ha,Ep)[`${h(this,Cc,pS)}-label`]),!h(this,no)){(o=h(this,lu))==null||o.remove();return}}else{if(!h(this,no)&&!h(this,au)){e.classList.remove("done"),(a=h(this,lu))==null||a.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let t=h(this,lu);if(!t){R(this,lu,t=document.createElement("span")),t.className="tooltip",t.setAttribute("role","tooltip"),t.id=`alt-text-tooltip-${h(this,Ha).id}`;const l=100,d=h(this,Ha)._uiManager._signal;d.addEventListener("abort",()=>{clearTimeout(h(this,yl)),R(this,yl,null)},{once:!0}),e.addEventListener("mouseenter",()=>{R(this,yl,setTimeout(()=>{R(this,yl,null),h(this,lu).classList.add("show"),h(this,Ha)._reportTelemetry({action:"alt_text_tooltip"})},l))},{signal:d}),e.addEventListener("mouseleave",()=>{var c;h(this,yl)&&(clearTimeout(h(this,yl)),R(this,yl,null)),(c=h(this,lu))==null||c.classList.remove("show")},{signal:d})}h(this,au)?t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(t.removeAttribute("data-l10n-id"),t.textContent=h(this,no)),t.parentNode||e.append(t);const r=h(this,Ha).getElementForAltText();r==null||r.setAttribute("aria-describedby",t.id)},N(ha,Ep,null),ve(ha,"_l10n",null);let vT=ha;var wo,gd,Hm,mi,xk,Pp,md,Rp,Bp,qm,bk,aI;class V2{constructor(e){N(this,bk);N(this,wo,null);N(this,gd,null);N(this,Hm,!1);N(this,mi,null);N(this,xk,null);N(this,Pp,null);N(this,md,null);N(this,Rp,null);N(this,Bp,!1);N(this,qm,null);R(this,mi,e)}renderForToolbar(){const e=R(this,gd,document.createElement("button"));return e.className="comment",q(this,bk,aI).call(this,e,!1)}renderForStandalone(){const e=R(this,wo,document.createElement("button"));e.className="annotationCommentButton";const t=h(this,mi).commentButtonPosition;if(t){const{style:r}=e;r.insetInlineEnd=`calc(${100*(h(this,mi)._uiManager.direction==="ltr"?1-t[0]:t[0])}% - var(--comment-button-dim))`,r.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;const i=h(this,mi).commentButtonColor;i&&(r.backgroundColor=i)}return q(this,bk,aI).call(this,e,!0)}focusButton(){setTimeout(()=>{var e;(e=h(this,wo)??h(this,gd))==null||e.focus()},0)}onUpdatedColor(){if(!h(this,wo))return;const e=h(this,mi).commentButtonColor;e&&(h(this,wo).style.backgroundColor=e),h(this,mi)._uiManager.updatePopupColor(h(this,mi))}get commentButtonWidth(){var e;return(((e=h(this,wo))==null?void 0:e.getBoundingClientRect().width)??0)/h(this,mi).parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(h(this,qm))return h(this,qm);if(!h(this,wo))return null;const{x:e,y:t,height:r}=h(this,wo).getBoundingClientRect(),{x:i,y:o,width:a,height:l}=h(this,mi).parent.boundingClientRect;return[(e-i)/a,(t+r-o)/l]}set commentPopupPositionInLayer(e){R(this,qm,e)}hasDefaultPopupPosition(){return h(this,qm)===null}removeStandaloneCommentButton(){var e;(e=h(this,wo))==null||e.remove(),R(this,wo,null)}removeToolbarCommentButton(){var e;(e=h(this,gd))==null||e.remove(),R(this,gd,null)}setCommentButtonStates({selected:e,hasPopup:t}){h(this,wo)&&(h(this,wo).classList.toggle("selected",e),h(this,wo).ariaExpanded=t)}edit(e){const t=this.commentPopupPositionInLayer;let r,i;if(t)[r,i]=t;else{[r,i]=h(this,mi).commentButtonPosition;const{width:u,height:f,x:p,y:g}=h(this,mi);r=p+r*u,i=g+i*f}const o=h(this,mi).parent.boundingClientRect,{x:a,y:l,width:d,height:c}=o;h(this,mi)._uiManager.editComment(h(this,mi),a+r*d,l+i*c,{...e,parentDimensions:o})}finish(){h(this,gd)&&(h(this,gd).focus({focusVisible:h(this,Hm)}),R(this,Hm,!1))}isDeleted(){return h(this,Bp)||h(this,md)===""}isEmpty(){return h(this,md)===null}hasBeenEdited(){return this.isDeleted()||h(this,md)!==h(this,xk)}serialize(){return this.data}get data(){return{text:h(this,md),richText:h(this,Pp),date:h(this,Rp),deleted:this.isDeleted()}}set data(e){if(e!==h(this,md)&&R(this,Pp,null),e===null){R(this,md,""),R(this,Bp,!0);return}R(this,md,e),R(this,Rp,new Date),R(this,Bp,!1)}restoreData({text:e,richText:t,date:r}){R(this,md,e),R(this,Pp,t),R(this,Rp,r),R(this,Bp,!1)}setInitialText(e,t=null){R(this,xk,e),this.data=e,R(this,Rp,null),R(this,Pp,t)}shown(){}destroy(){var e,t;(e=h(this,gd))==null||e.remove(),R(this,gd,null),(t=h(this,wo))==null||t.remove(),R(this,wo,null),R(this,md,""),R(this,Pp,null),R(this,Rp,null),R(this,mi,null),R(this,Hm,!1),R(this,Bp,!1)}}wo=new WeakMap,gd=new WeakMap,Hm=new WeakMap,mi=new WeakMap,xk=new WeakMap,Pp=new WeakMap,md=new WeakMap,Rp=new WeakMap,Bp=new WeakMap,qm=new WeakMap,bk=new WeakSet,aI=function(e,t){if(!h(this,mi)._uiManager.hasCommentManager())return null;e.tabIndex="0",e.ariaHasPopup="dialog",t?(e.ariaControls="commentPopup",e.setAttribute("data-l10n-id","pdfjs-show-comment-button")):(e.ariaControlsElements=[h(this,mi)._uiManager.getCommentDialogElement()],e.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const r=h(this,mi)._uiManager._signal;if(!(r instanceof AbortSignal)||r.aborted)return e;e.addEventListener("contextmenu",Hd,{signal:r}),t&&(e.addEventListener("focusin",o=>{h(this,mi)._focusEventsAllowed=!1,$i(o)},{capture:!0,signal:r}),e.addEventListener("focusout",o=>{h(this,mi)._focusEventsAllowed=!0,$i(o)},{capture:!0,signal:r})),e.addEventListener("pointerdown",o=>o.stopPropagation(),{signal:r});const i=o=>{o.preventDefault(),e===h(this,gd)?this.edit():h(this,mi).toggleComment(!0)};return e.addEventListener("click",i,{capture:!0,signal:r}),e.addEventListener("keydown",o=>{o.target===e&&o.key==="Enter"&&(R(this,Hm,!0),i(o))},{signal:r}),e.addEventListener("pointerenter",()=>{h(this,mi).toggleComment(!1,!0)},{signal:r}),e.addEventListener("pointerleave",()=>{h(this,mi).toggleComment(!1,!1)},{signal:r}),e};var Nb,Vm,vk,wk,Sk,jk,kk,Ph,Gm,Rh,Km,Bh,Ug,RV,BV,IV;const U3=class U3{constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:r=null,onPinchStart:i=null,onPinching:o=null,onPinchEnd:a=null,signal:l}){N(this,Ug);N(this,Nb);N(this,Vm,!1);N(this,vk,null);N(this,wk);N(this,Sk);N(this,jk);N(this,kk);N(this,Ph,null);N(this,Gm);N(this,Rh,null);N(this,Km);N(this,Bh,null);R(this,Nb,e),R(this,vk,r),R(this,wk,t),R(this,Sk,i),R(this,jk,o),R(this,kk,a),R(this,Km,new AbortController),R(this,Gm,AbortSignal.any([l,h(this,Km).signal])),e.addEventListener("touchstart",q(this,Ug,RV).bind(this),{passive:!1,signal:h(this,Gm)})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Lu.pixelRatio}destroy(){var e,t;(e=h(this,Km))==null||e.abort(),R(this,Km,null),(t=h(this,Ph))==null||t.abort(),R(this,Ph,null)}};Nb=new WeakMap,Vm=new WeakMap,vk=new WeakMap,wk=new WeakMap,Sk=new WeakMap,jk=new WeakMap,kk=new WeakMap,Ph=new WeakMap,Gm=new WeakMap,Rh=new WeakMap,Km=new WeakMap,Bh=new WeakMap,Ug=new WeakSet,RV=function(e){var i,o,a;if((i=h(this,wk))!=null&&i.call(this))return;if(e.touches.length===1){if(h(this,Ph))return;const l=R(this,Ph,new AbortController),d=AbortSignal.any([h(this,Gm),l.signal]),c=h(this,Nb),u={capture:!0,signal:d,passive:!1},f=p=>{var g;p.pointerType==="touch"&&((g=h(this,Ph))==null||g.abort(),R(this,Ph,null))};c.addEventListener("pointerdown",p=>{p.pointerType==="touch"&&($i(p),f(p))},u),c.addEventListener("pointerup",f,u),c.addEventListener("pointercancel",f,u);return}if(!h(this,Bh)){R(this,Bh,new AbortController);const l=AbortSignal.any([h(this,Gm),h(this,Bh).signal]),d=h(this,Nb),c={signal:l,capture:!1,passive:!1};d.addEventListener("touchmove",q(this,Ug,BV).bind(this),c);const u=q(this,Ug,IV).bind(this);d.addEventListener("touchend",u,c),d.addEventListener("touchcancel",u,c),c.capture=!0,d.addEventListener("pointerdown",$i,c),d.addEventListener("pointermove",$i,c),d.addEventListener("pointercancel",$i,c),d.addEventListener("pointerup",$i,c),(o=h(this,Sk))==null||o.call(this)}if($i(e),e.touches.length!==2||(a=h(this,vk))!=null&&a.call(this)){R(this,Rh,null);return}let[t,r]=e.touches;t.identifier>r.identifier&&([t,r]=[r,t]),R(this,Rh,{touch0X:t.screenX,touch0Y:t.screenY,touch1X:r.screenX,touch1Y:r.screenY})},BV=function(e){var _;if(!h(this,Rh)||e.touches.length!==2)return;$i(e);let[t,r]=e.touches;t.identifier>r.identifier&&([t,r]=[r,t]);const{screenX:i,screenY:o}=t,{screenX:a,screenY:l}=r,d=h(this,Rh),{touch0X:c,touch0Y:u,touch1X:f,touch1Y:p}=d,g=f-c,m=p-u,y=a-i,v=l-o,x=Math.hypot(y,v)||1,w=Math.hypot(g,m)||1;if(!h(this,Vm)&&Math.abs(w-x)<=U3.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(d.touch0X=i,d.touch0Y=o,d.touch1X=a,d.touch1Y=l,!h(this,Vm)){R(this,Vm,!0);return}const S=[(i+a)/2,(o+l)/2];(_=h(this,jk))==null||_.call(this,S,w,x)},IV=function(e){var t;e.touches.length>=2||(h(this,Bh)&&(h(this,Bh).abort(),R(this,Bh,null),(t=h(this,kk))==null||t.call(this)),h(this,Rh)&&($i(e),R(this,Rh,null),R(this,Vm,!1)))};let wT=U3;var Xm,cc,Pi,Xr,Ih,Wb,Ip,_k,So,Ym,Mh,yd,Mp,Ck,Qm,xl,Ak,$m,zh,uu,Ub,Hb,xd,Zm,Tk,BT,ln,lI,Fk,dI,M5,MV,zV,cI,z5,uI,OV,LV,NV,hI,WV,fI,UV,HV,qV,pI,gS;const En=class En{constructor(e){N(this,ln);N(this,Xm,null);N(this,cc,null);N(this,Pi,null);N(this,Xr,null);N(this,Ih,null);N(this,Wb,!1);N(this,Ip,null);N(this,_k,"");N(this,So,null);N(this,Ym,null);N(this,Mh,null);N(this,yd,null);N(this,Mp,null);N(this,Ck,"");N(this,Qm,!1);N(this,xl,null);N(this,Ak,!1);N(this,$m,!1);N(this,zh,!1);N(this,uu,null);N(this,Ub,0);N(this,Hb,0);N(this,xd,null);N(this,Zm,null);ve(this,"isSelected",!1);ve(this,"_isCopy",!1);ve(this,"_editToolbar",null);ve(this,"_initialOptions",Object.create(null));ve(this,"_initialData",null);ve(this,"_isVisible",!0);ve(this,"_uiManager",null);ve(this,"_focusEventsAllowed",!0);N(this,Tk,!1);N(this,BT,En._zIndex++);this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;const{rotation:t,rawDims:{pageWidth:r,pageHeight:i,pageX:o,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[r,i],this.pageTranslation=[o,a];const[l,d]=this.parentDimensions;this.x=e.x/l,this.y=e.y/d,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const e=En.prototype._resizeWithKeyboard,t=_0.TRANSLATE_SMALL,r=_0.TRANSLATE_BIG;return Cn(this,"_resizerKeyboardManager",new uC([[["ArrowLeft","mac+ArrowLeft"],e,{args:[-t,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e,{args:[-r,0]}],[["ArrowRight","mac+ArrowRight"],e,{args:[t,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e,{args:[r,0]}],[["ArrowUp","mac+ArrowUp"],e,{args:[0,-t]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e,{args:[0,-r]}],[["ArrowDown","mac+ArrowDown"],e,{args:[0,t]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e,{args:[0,r]}],[["Escape","mac+Escape"],En.prototype._stopResizingWithKeyboard]]))}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return Cn(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){const t=new cue({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(e,t){if(En._l10n??(En._l10n=e),En._l10nResizer||(En._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),En._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);En._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){Hr("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return h(this,Tk)}set _isDraggable(e){var t;R(this,Tk,e),(t=this.div)==null||t.classList.toggle("draggable",e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){const[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=h(this,BT)}setParent(e){var t;e!==null?(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions):(q(this,ln,gS).call(this),(t=h(this,yd))==null||t.remove(),R(this,yd,null)),this.parent=e}focusin(e){this._focusEventsAllowed&&(h(this,Qm)?R(this,Qm,!1):this.parent.setSelected(this))}focusout(e){var r;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const t=e.relatedTarget;t!=null&&t.closest(`#${this.id}`)||(e.preventDefault(),(r=this.parent)!=null&&r.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,r,i){const[o,a]=this.parentDimensions;[r,i]=this.screenToPageTranslation(r,i),this.x=(e+r)/o,this.y=(t+i)/a,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}const[r,i]=this.parentDimensions;this.setAt(e*r,t*i,this.width*r,this.height*i),this._onTranslated()}translate(e,t){q(this,ln,lI).call(this,this.parentDimensions,e,t)}translateInPage(e,t){h(this,xl)||R(this,xl,[this.x,this.y,this.width,this.height]),q(this,ln,lI).call(this,this.pageDimensions,e,t),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){h(this,xl)||R(this,xl,[this.x,this.y,this.width,this.height]);const{div:r,parentDimensions:[i,o]}=this;if(this.x+=e/i,this.y+=t/o,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:f,y:p}=this.div.getBoundingClientRect();this.parent.findNewParent(this,f,p)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:l}=this;const[d,c]=this.getBaseTranslation();a+=d,l+=c;const{style:u}=r;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*l).toFixed(2)}%`,this._onTranslating(a,l),r.scrollIntoView({block:"nearest"})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!h(this,xl)&&(h(this,xl)[0]!==this.x||h(this,xl)[1]!==this.y)}get _hasBeenResized(){return!!h(this,xl)&&(h(this,xl)[2]!==this.width||h(this,xl)[3]!==this.height)}getBaseTranslation(){const[e,t]=this.parentDimensions,{_borderLineWidth:r}=En,i=r/e,o=r/t;switch(this.rotation){case 90:return[-i,o];case 180:return[i,o];case 270:return[i,-o];default:return[-i,-o]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){const{div:{style:t},pageDimensions:[r,i]}=this;let{x:o,y:a,width:l,height:d}=this;if(l*=r,d*=i,o*=r,a*=i,this._mustFixPosition)switch(e){case 0:o=Bi(o,0,r-l),a=Bi(a,0,i-d);break;case 90:o=Bi(o,0,r-d),a=Bi(a,l,i);break;case 180:o=Bi(o,l,r),a=Bi(a,d,i);break;case 270:o=Bi(o,d,r),a=Bi(a,0,i-l);break}this.x=o/=r,this.y=a/=i;const[c,u]=this.getBaseTranslation();o+=c,a+=u,t.left=`${(100*o).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(e,t){var r;return q(r=En,Fk,dI).call(r,e,t,this.parentRotation)}pageTranslationToScreen(e,t){var r;return q(r=En,Fk,dI).call(r,e,t,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:e,pageDimensions:[t,r]}=this;return[t*e,r*e]}setDims(){const{div:{style:e},width:t,height:r}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*r).toFixed(2)}%`}getInitialTranslation(){return[0,0]}_onResized(){}static _round(e){return Math.round(e*1e4)/1e4}_onResizing(){}altTextFinish(){var e;(e=h(this,Pi))==null||e.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||h(this,$m))return this._editToolbar;this._editToolbar=new JB(this),this.div.append(this._editToolbar.render());const{toolbarButtons:e}=this;if(e)for(const[t,r]of e)await this._editToolbar.addButton(t,r);return this.hasComment||this._editToolbar.addButton("comment",this.addCommentButton()),this._editToolbar.addButton("delete"),this._editToolbar}addCommentButtonInToolbar(){var e;(e=this._editToolbar)==null||e.addButtonBefore("comment",this.addCommentButton(),".deleteButton")}removeCommentButtonFromToolbar(){var e;(e=this._editToolbar)==null||e.removeButton("comment")}removeEditToolbar(){var e,t;(e=this._editToolbar)==null||e.remove(),this._editToolbar=null,(t=h(this,Pi))==null||t.destroy()}addContainer(e){var r;const t=(r=this._editToolbar)==null?void 0:r.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return h(this,Pi)||(vT.initialize(En._l10n),R(this,Pi,new vT(this)),h(this,Xm)&&(h(this,Pi).data=h(this,Xm),R(this,Xm,null))),h(this,Pi)}get altTextData(){var e;return(e=h(this,Pi))==null?void 0:e.data}set altTextData(e){h(this,Pi)&&(h(this,Pi).data=e)}get guessedAltText(){var e;return(e=h(this,Pi))==null?void 0:e.guessedText}async setGuessedAltText(e){var t;await((t=h(this,Pi))==null?void 0:t.setGuessedText(e))}serializeAltText(e){var t;return(t=h(this,Pi))==null?void 0:t.serialize(e)}hasAltText(){return!!h(this,Pi)&&!h(this,Pi).isEmpty()}hasAltTextData(){var e;return((e=h(this,Pi))==null?void 0:e.hasData())??!1}focusCommentButton(){var e;(e=h(this,Xr))==null||e.focusButton()}addCommentButton(){return this.canAddComment?h(this,Xr)||R(this,Xr,new V2(this)):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(h(this,Ih)){this._uiManager.isEditingMode()&&h(this,Ih).classList.remove("hidden");return}this.hasComment&&(R(this,Ih,h(this,Xr).renderForStandalone()),this.div.append(h(this,Ih)))}}removeStandaloneCommentButton(){h(this,Xr).removeStandaloneCommentButton(),R(this,Ih,null)}hideStandaloneCommentButton(){var e;(e=h(this,Ih))==null||e.classList.add("hidden")}get comment(){if(!h(this,Xr))return null;const{data:{richText:e,text:t,date:r,deleted:i}}=h(this,Xr);return{text:t,richText:e,date:r,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){h(this,Xr)||R(this,Xr,new V2(this)),typeof e=="object"&&e!==null?h(this,Xr).restoreData(e):h(this,Xr).data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:r}){if(!t||(h(this,Xr)||R(this,Xr,new V2(this)),h(this,Xr).setInitialText(e,r),!this.annotationElementId))return;const i=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);i&&this.updateFromAnnotationLayer(i)}get hasEditedComment(){var e;return(e=h(this,Xr))==null?void 0:e.hasBeenEdited()}get hasDeletedComment(){var e;return(e=h(this,Xr))==null?void 0:e.isDeleted()}get hasComment(){return!!h(this,Xr)&&!h(this,Xr).isEmpty()&&!h(this,Xr).isDeleted()}async editComment(e){h(this,Xr)||R(this,Xr,new V2(this)),h(this,Xr).edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){h(this,Xr).setSelectedButton(e)}addComment(e){if(this.hasEditedComment){const[,,,i]=e.rect,[o]=this.pageDimensions,[a]=this.pageTranslation,l=a+o+1,d=i-100,c=l+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[l,d,c,i]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){h(this,Xr).data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){var a;const e=this.div=document.createElement("div");e.setAttribute("data-editor-rotation",(360-this.rotation)%360),e.className=this.name,e.setAttribute("id",this.id),e.tabIndex=h(this,Wb)?-1:0,e.setAttribute("role","application"),this.defaultL10nId&&e.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||e.classList.add("hidden"),this.setInForeground(),q(this,ln,fI).call(this);const[t,r]=this.parentDimensions;this.parentRotation%180!==0&&(e.style.maxWidth=`${(100*r/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/r).toFixed(2)}%`);const[i,o]=this.getInitialTranslation();return this.translate(i,o),xV(this,e,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(h(this,Zm)||R(this,Zm,new wT({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:q(this,ln,OV).bind(this),onPinching:q(this,ln,LV).bind(this),onPinchEnd:q(this,ln,NV).bind(this),signal:this._uiManager._signal}))),this.addStandaloneCommentButton(),(a=this._uiManager._editorUndoBar)==null||a.hide(),e}pointerdown(e){const{isMac:t}=Ds.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(R(this,Qm,!0),this._isDraggable){q(this,ln,WV).call(this,e);return}q(this,ln,hI).call(this,e)}_onStartDragging(){}_onStopDragging(){}moveInDOM(){h(this,uu)&&clearTimeout(h(this,uu)),R(this,uu,setTimeout(()=>{var e;R(this,uu,null),(e=this.parent)==null||e.moveEditorInDOM(this)},0))}_setParentAndPosition(e,t,r){e.changeParent(this),this.x=t,this.y=r,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,r=this.rotation){const i=this.parentScale,[o,a]=this.pageDimensions,[l,d]=this.pageTranslation,c=e/i,u=t/i,f=this.x*o,p=this.y*a,g=this.width*o,m=this.height*a;switch(r){case 0:return[f+c+l,a-p-u-m+d,f+c+g+l,a-p-u+d];case 90:return[f+u+l,a-p+c+d,f+u+m+l,a-p+c+g+d];case 180:return[f-c-g+l,a-p+u+d,f-c+l,a-p+u+m+d];case 270:return[f-u-m+l,a-p-c-g+d,f-u+l,a-p-c+d];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(e,t){const[r,i,o,a]=e,l=o-r,d=a-i;switch(this.rotation){case 0:return[r,t-a,l,d];case 90:return[r,t-i,d,l];case 180:return[o,t-i,l,d];case 270:return[o,t-a,d,l];default:throw new Error("Invalid rotation")}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&En._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){var e;(e=h(this,Xr))==null||e.onUpdatedColor()}getData(){const{comment:{text:e,color:t,date:r,opacity:i,deleted:o,richText:a},uid:l,pageIndex:d,creationDate:c,modificationDate:u}=this;return{id:l,pageIndex:d,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:r||u,popupRef:!o,color:t,opacity:i}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return this.isInEditMode()?!1:(this.parent.setEditingState(!1),R(this,$m,!0),!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),R(this,$m,!1),!0):!1}isInEditMode(){return h(this,$m)}shouldGetKeyboardEvents(){return h(this,zh)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:e,left:t,bottom:r,right:i}=this.getClientDimensions(),{innerHeight:o,innerWidth:a}=window;return t0&&e0}rebuild(){q(this,ln,fI).call(this)}rotate(e){}resize(){}serializeDeleted(){var e;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((e=this._initialData)==null?void 0:e.popupRef)||""}}serialize(e=!1,t=null){var r;return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:((r=this._initialData)==null?void 0:r.popupRef)||""}}static async deserialize(e,t,r){const i=new this.prototype.constructor({parent:t,id:r.getId(),uiManager:r,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});i.rotation=e.rotation,R(i,Xm,e.accessibilityData),i._isCopy=e.isCopy||!1;const[o,a]=i.pageDimensions,[l,d,c,u]=i.getRectInCurrentCoords(e.rect,a);return i.x=l/o,i.y=d/a,i.width=c/o,i.height=u/a,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var e,t,r;if((e=h(this,Mp))==null||e.abort(),R(this,Mp,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),h(this,uu)&&(clearTimeout(h(this,uu)),R(this,uu,null)),q(this,ln,gS).call(this),this.removeEditToolbar(),h(this,xd)){for(const i of h(this,xd).values())clearTimeout(i);R(this,xd,null)}this.parent=null,(t=h(this,Zm))==null||t.destroy(),R(this,Zm,null),(r=h(this,yd))==null||r.remove(),R(this,yd,null)}get isResizable(){return!1}makeResizable(){this.isResizable&&(q(this,ln,MV).call(this),h(this,So).classList.remove("hidden"))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction==="ltr"?[1,0]:[0,0]}get commentButtonPositionInPage(){const{commentButtonPosition:[e,t]}=this,[r,i,o,a]=this.getPDFRect();return[En._round(r+(o-r)*e),En._round(i+(a-i)*(1-t))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return h(this,Xr).commentPopupPositionInLayer}set commentPopupPosition(e){h(this,Xr).commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return h(this,Xr).hasDefaultPopupPosition()}get commentButtonWidth(){return h(this,Xr).commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){var t;(t=h(this,Xr))==null||t.setCommentButtonStates(e)}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),R(this,Mh,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const t=h(this,So).children;if(!h(this,cc)){R(this,cc,Array.from(t));const a=q(this,ln,UV).bind(this),l=q(this,ln,HV).bind(this),d=this._uiManager._signal;for(const c of h(this,cc)){const u=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",a,{signal:d}),c.addEventListener("blur",l,{signal:d}),c.addEventListener("focus",q(this,ln,qV).bind(this,u),{signal:d}),c.setAttribute("data-l10n-id",En._l10nResizer[u])}}const r=h(this,cc)[0];let i=0;for(const a of t){if(a===r)break;i++}const o=(360-this.rotation+this.parentRotation)%360/90*(h(this,cc).length/4);if(o!==i){if(oi)for(let l=0;l{var i,o;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((o=this._editToolbar)==null||o.show())});return}(t=this._editToolbar)==null||t.show(),(r=h(this,Pi))==null||r.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>{var e;return(e=this.div)==null?void 0:e.focus({preventScroll:!0})},0)}unselect(){var e,t,r,i,o;this.isSelected&&(this.isSelected=!1,(e=h(this,So))==null||e.classList.add("hidden"),(t=this.div)==null||t.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(o=h(this,Pi))==null||o.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!=="BUTTON"&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return h(this,Ak)}set isEditing(e){R(this,Ak,e),this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(e,t=!1){if(t){h(this,xd)||R(this,xd,new Map);const{action:r}=e;let i=h(this,xd).get(r);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(e),h(this,xd).delete(r),h(this,xd).size===0&&R(this,xd,null)},En._telemetryTimeout),h(this,xd).set(r,i);return}e.type||(e.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:e}})}show(e=this._isVisible){this.div.classList.toggle("hidden",!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),R(this,Wb,!1)}disable(){this.div&&(this.div.tabIndex=-1),R(this,Wb,!0)}updateFakeAnnotationElement(e){if(!h(this,yd)&&!this.deleted){R(this,yd,e.addFakeAnnotation(this));return}if(this.deleted){h(this,yd).remove(),R(this,yd,null);return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&h(this,yd).updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(".annotationContent");if(!t)t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),e.container.prepend(t);else if(t.nodeName==="CANVAS"){const r=t;t=document.createElement("div"),t.classList.add("annotationContent",this.editorType),r.before(t)}return t}resetAnnotationElement(e){const{firstElementChild:t}=e.container;(t==null?void 0:t.nodeName)==="DIV"&&t.classList.contains("annotationContent")&&t.remove()}};Xm=new WeakMap,cc=new WeakMap,Pi=new WeakMap,Xr=new WeakMap,Ih=new WeakMap,Wb=new WeakMap,Ip=new WeakMap,_k=new WeakMap,So=new WeakMap,Ym=new WeakMap,Mh=new WeakMap,yd=new WeakMap,Mp=new WeakMap,Ck=new WeakMap,Qm=new WeakMap,xl=new WeakMap,Ak=new WeakMap,$m=new WeakMap,zh=new WeakMap,uu=new WeakMap,Ub=new WeakMap,Hb=new WeakMap,xd=new WeakMap,Zm=new WeakMap,Tk=new WeakMap,BT=new WeakMap,ln=new WeakSet,lI=function([e,t],r,i){[r,i]=this.screenToPageTranslation(r,i),this.x+=r/e,this.y+=i/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()},Fk=new WeakSet,dI=function(e,t,r){switch(r){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}},M5=function(e){switch(e){case 90:{const[t,r]=this.pageDimensions;return[0,-t/r,r/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,r]=this.pageDimensions;return[0,t/r,-r/t,0]}default:return[1,0,0,1]}},MV=function(){if(h(this,So))return;R(this,So,document.createElement("div")),h(this,So).classList.add("resizers");const e=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],t=this._uiManager._signal;for(const r of e){const i=document.createElement("div");h(this,So).append(i),i.classList.add("resizer",r),i.setAttribute("data-resizer-name",r),i.addEventListener("pointerdown",q(this,ln,zV).bind(this,r),{signal:t}),i.addEventListener("contextmenu",Hd,{signal:t}),i.tabIndex=-1}this.div.prepend(h(this,So))},zV=function(e,t){var u;t.preventDefault();const{isMac:r}=Ds.platform;if(t.button!==0||t.ctrlKey&&r)return;(u=h(this,Pi))==null||u.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,R(this,Ym,[t.screenX,t.screenY]);const o=new AbortController,a=this._uiManager.combinedSignal(o);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",q(this,ln,uI).bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener("touchmove",$i,{passive:!1,signal:a}),window.addEventListener("contextmenu",Hd,{signal:a}),R(this,Mh,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const l=this.parent.div.style.cursor,d=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;const c=()=>{var f;o.abort(),this.parent.togglePointerEvents(!0),(f=h(this,Pi))==null||f.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=l,this.div.style.cursor=d,q(this,ln,z5).call(this)};window.addEventListener("pointerup",c,{signal:a}),window.addEventListener("blur",c,{signal:a})},cI=function(e,t,r,i){this.width=r,this.height=i,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()},z5=function(){if(!h(this,Mh))return;const{savedX:e,savedY:t,savedWidth:r,savedHeight:i}=h(this,Mh);R(this,Mh,null);const o=this.x,a=this.y,l=this.width,d=this.height;o===e&&a===t&&l===r&&d===i||this.addCommands({cmd:q(this,ln,cI).bind(this,o,a,l,d),undo:q(this,ln,cI).bind(this,e,t,r,i),mustExec:!0})},uI=function(e,t){const[r,i]=this.parentDimensions,o=this.x,a=this.y,l=this.width,d=this.height,c=En.MIN_SIZE/r,u=En.MIN_SIZE/i,f=q(this,ln,M5).call(this,this.rotation),p=(M,I)=>[f[0]*M+f[2]*I,f[1]*M+f[3]*I],g=q(this,ln,M5).call(this,360-this.rotation),m=(M,I)=>[g[0]*M+g[2]*I,g[1]*M+g[3]*I];let y,v,x=!1,w=!1;switch(e){case"topLeft":x=!0,y=(M,I)=>[0,0],v=(M,I)=>[M,I];break;case"topMiddle":y=(M,I)=>[M/2,0],v=(M,I)=>[M/2,I];break;case"topRight":x=!0,y=(M,I)=>[M,0],v=(M,I)=>[0,I];break;case"middleRight":w=!0,y=(M,I)=>[M,I/2],v=(M,I)=>[0,I/2];break;case"bottomRight":x=!0,y=(M,I)=>[M,I],v=(M,I)=>[0,0];break;case"bottomMiddle":y=(M,I)=>[M/2,I],v=(M,I)=>[M/2,0];break;case"bottomLeft":x=!0,y=(M,I)=>[0,I],v=(M,I)=>[M,0];break;case"middleLeft":w=!0,y=(M,I)=>[0,I/2],v=(M,I)=>[M,I/2];break}const S=y(l,d),_=v(l,d);let b=p(..._);const C=En._round(o+b[0]),T=En._round(a+b[1]);let F=1,A=1,D,P;if(t.fromKeyboard)({deltaX:D,deltaY:P}=t);else{const{screenX:M,screenY:I}=t,[H,z]=h(this,Ym);[D,P]=this.screenToPageTranslation(M-H,I-z),h(this,Ym)[0]=M,h(this,Ym)[1]=I}if([D,P]=m(D/r,P/i),x){const M=Math.hypot(l,d);F=A=Math.max(Math.min(Math.hypot(_[0]-S[0]-D,_[1]-S[1]-P)/M,1/l,1/d),c/l,u/d)}else w?F=Bi(Math.abs(_[0]-S[0]-D),c,1)/l:A=Bi(Math.abs(_[1]-S[1]-P),u,1)/d;const L=En._round(l*F),W=En._round(d*A);b=p(...v(L,W));const O=C-b[0],U=T-b[1];h(this,xl)||R(this,xl,[this.x,this.y,this.width,this.height]),this.width=L,this.height=W,this.x=O,this.y=U,this.setDims(),this.fixAndSetPosition(),this._onResizing()},OV=function(){var e;R(this,Mh,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height}),(e=h(this,Pi))==null||e.toggle(!1),this.parent.togglePointerEvents(!1)},LV=function(e,t,r){let o=.7*(r/t)+1-.7;if(o===1)return;const a=q(this,ln,M5).call(this,this.rotation),l=(C,T)=>[a[0]*C+a[2]*T,a[1]*C+a[3]*T],[d,c]=this.parentDimensions,u=this.x,f=this.y,p=this.width,g=this.height,m=En.MIN_SIZE/d,y=En.MIN_SIZE/c;o=Math.max(Math.min(o,1/p,1/g),m/p,y/g);const v=En._round(p*o),x=En._round(g*o);if(v===p&&x===g)return;h(this,xl)||R(this,xl,[u,f,p,g]);const w=l(p/2,g/2),S=En._round(u+w[0]),_=En._round(f+w[1]),b=l(v/2,x/2);this.x=S-b[0],this.y=_-b[1],this.width=v,this.height=x,this.setDims(),this.fixAndSetPosition(),this._onResizing()},NV=function(){var e;(e=h(this,Pi))==null||e.toggle(!0),this.parent.togglePointerEvents(!0),q(this,ln,z5).call(this)},hI=function(e){const{isMac:t}=Ds.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)},WV=function(e){const{isSelected:t}=this;this._uiManager.setUpDragSession();let r=!1;const i=new AbortController,o=this._uiManager.combinedSignal(i),a={capture:!0,passive:!1,signal:o},l=c=>{i.abort(),R(this,Ip,null),R(this,Qm,!1),this._uiManager.endDragSession()||q(this,ln,hI).call(this,c),r&&this._onStopDragging()};t&&(R(this,Ub,e.clientX),R(this,Hb,e.clientY),R(this,Ip,e.pointerId),R(this,_k,e.pointerType),window.addEventListener("pointermove",c=>{r||(r=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:u,clientY:f,pointerId:p}=c;if(p!==h(this,Ip)){$i(c);return}const[g,m]=this.screenToPageTranslation(u-h(this,Ub),f-h(this,Hb));R(this,Ub,u),R(this,Hb,f),this._uiManager.dragSelectedEditors(g,m)},a),window.addEventListener("touchmove",$i,a),window.addEventListener("pointerdown",c=>{c.pointerType===h(this,_k)&&(h(this,Zm)||c.isPrimary)&&l(c),$i(c)},a));const d=c=>{if(!h(this,Ip)||h(this,Ip)===c.pointerId){l(c);return}$i(c)};window.addEventListener("pointerup",d,{signal:o}),window.addEventListener("blur",d,{signal:o})},fI=function(){if(h(this,Mp)||!this.div)return;R(this,Mp,new AbortController);const e=this._uiManager.combinedSignal(h(this,Mp));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})},UV=function(e){En._resizerKeyboardManager.exec(this,e)},HV=function(e){var t;h(this,zh)&&((t=e.relatedTarget)==null?void 0:t.parentNode)!==h(this,So)&&q(this,ln,gS).call(this)},qV=function(e){R(this,Ck,h(this,zh)?e:"")},pI=function(e){if(h(this,cc))for(const t of h(this,cc))t.tabIndex=e},gS=function(){R(this,zh,!1),q(this,ln,pI).call(this,-1),q(this,ln,z5).call(this)},N(En,Fk),ve(En,"_l10n",null),ve(En,"_l10nResizer",null),ve(En,"_borderLineWidth",-1),ve(En,"_colorManager",new nI),ve(En,"_zIndex",1),ve(En,"_telemetryTimeout",1e3);let xi=En;class cue extends xi{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const mN=3285377520,rd=4294901760,Xc=65535;class gI{constructor(e){this.h1=e?e&4294967295:mN,this.h2=e?e&4294967295:mN}update(e){let t,r;if(typeof e=="string"){t=new Uint8Array(e.length*2),r=0;for(let y=0,v=e.length;y>>8,t[r++]=x&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),r=t.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=r>>2,o=r-i*4,a=new Uint32Array(t.buffer,0,i);let l=0,d=0,c=this.h1,u=this.h2;const f=3432918353,p=461845907,g=f&Xc,m=p&Xc;for(let y=0;y>>17,l=l*p&rd|l*m&Xc,c^=l,c=c<<13|c>>>19,c=c*5+3864292196):(d=a[y],d=d*f&rd|d*g&Xc,d=d<<15|d>>>17,d=d*p&rd|d*m&Xc,u^=d,u=u<<13|u>>>19,u=u*5+3864292196);switch(l=0,o){case 3:l^=t[i*4+2]<<16;case 2:l^=t[i*4+1]<<8;case 1:l^=t[i*4],l=l*f&rd|l*g&Xc,l=l<<15|l>>>17,l=l*p&rd|l*m&Xc,i&1?c^=l:u^=l}this.h1=c,this.h2=u}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&rd|e*36045&Xc,t=t*4283543511&rd|((t<<16|e>>>16)*2950163797&rd)>>>16,e^=t>>>1,e=e*444984403&rd|e*60499&Xc,t=t*3301882366&rd|((t<<16|e>>>16)*3120437893&rd)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}const Xj=Object.freeze({map:null,hash:"",transfer:void 0});var Jm,ey,Oh,jo,IT,VV;class I3{constructor(){N(this,IT);N(this,Jm,!1);N(this,ey,null);N(this,Oh,null);N(this,jo,new Map);ve(this,"onSetModified",null);ve(this,"onResetModified",null);ve(this,"onAnnotationEditor",null)}getValue(e,t){const r=h(this,jo).get(e);return r===void 0?t:Object.assign(t,r)}getRawValue(e){return h(this,jo).get(e)}remove(e){var r;const t=h(this,jo).get(e);t!==void 0&&(t instanceof xi&&h(this,Oh).delete(t.annotationElementId),h(this,jo).delete(e),h(this,jo).size===0&&this.resetModified(),!h(this,jo).values().some(i=>i instanceof xi)&&((r=this.onAnnotationEditor)==null||r.call(this,null)))}setValue(e,t){var o;const r=h(this,jo).get(e);let i=!1;if(r!==void 0)for(const[a,l]of Object.entries(t))r[a]!==l&&(i=!0,r[a]=l);else i=!0,h(this,jo).set(e,t);i&&q(this,IT,VV).call(this),t instanceof xi&&((h(this,Oh)||R(this,Oh,new Map)).set(t.annotationElementId,t),(o=this.onAnnotationEditor)==null||o.call(this,t.constructor._type))}has(e){return h(this,jo).has(e)}get size(){return h(this,jo).size}resetModified(){var e;h(this,Jm)&&(R(this,Jm,!1),(e=this.onResetModified)==null||e.call(this))}get print(){return new GV(this)}get serializable(){if(h(this,jo).size===0)return Xj;const e=new Map,t=new gI,r=[],i=Object.create(null);let o=!1;for(const[a,l]of h(this,jo)){const d=l instanceof xi?l.serialize(!1,i):l;l.page&&(l.pageIndex=l.page._pageIndex,delete l.page),d&&(e.set(a,d),t.update(`${a}:${JSON.stringify(d)}`),o||(o=!!d.bitmap))}if(o)for(const a of e.values())a.bitmap&&r.push(a.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:r}:Xj}get editorStats(){let e=null;const t=new Map;let r=0,i=0;for(const o of h(this,jo).values()){if(!(o instanceof xi)){o.popup&&(o.popup.deleted?i+=1:r+=1);continue}o.isCommentDeleted?i+=1:o.hasEditedComment&&(r+=1);const a=o.telemetryFinalData;if(!a)continue;const{type:l}=a;t.has(l)||t.set(l,Object.getPrototypeOf(o).constructor),e||(e=Object.create(null));const d=e[l]||(e[l]=new Map);for(const[c,u]of Object.entries(a)){if(c==="type")continue;const f=d.getOrInsertComputed(c,D3);f.set(u,(f.get(u)??0)+1)}}if((i>0||r>0)&&(e||(e=Object.create(null)),e.comments={deleted:i,edited:r}),!e)return null;for(const[o,a]of t)e[o]=a.computeTelemetryFinalData(e[o]);return e}resetModifiedIds(){R(this,ey,null)}updateEditor(e,t){var i;const r=(i=h(this,Oh))==null?void 0:i.get(e);return r?(r.updateFromAnnotationLayer(t),!0):!1}getEditor(e){var t;return((t=h(this,Oh))==null?void 0:t.get(e))||null}get modifiedIds(){if(h(this,ey))return h(this,ey);const e=[];if(h(this,Oh))for(const r of h(this,Oh).values())r.serialize()&&e.push(r.annotationElementId);let t="";if(e.length){const r=new gI;r.update(e.join(",")),t=r.hexdigest()}return R(this,ey,{ids:new Set(e),hash:t})}[Symbol.iterator](){return h(this,jo).entries()}}Jm=new WeakMap,ey=new WeakMap,Oh=new WeakMap,jo=new WeakMap,IT=new WeakSet,VV=function(){var e;h(this,Jm)||(R(this,Jm,!0),(e=this.onSetModified)==null||e.call(this))};var Dk;class GV extends I3{constructor(t){super();N(this,Dk,Xj);const{serializable:r}=t;if(r===Xj)return;const{map:i,hash:o,transfer:a}=r,l=structuredClone(i,a?{transfer:a}:null);R(this,Dk,{map:l,hash:o,transfer:[]})}get print(){Hr("Should not call PrintAnnotationStorage.print")}get serializable(){return h(this,Dk)}get modifiedIds(){return Cn(this,"modifiedIds",{ids:new Set,hash:""})}}Dk=new WeakMap;const xx="__forcedDependency",{floor:yN,ceil:xN}=Math;function bN(n,e,t,r,i,o){n[e*4+0]=Math.min(n[e*4+0],t),n[e*4+1]=Math.min(n[e*4+1],r),n[e*4+2]=Math.max(n[e*4+2],i),n[e*4+3]=Math.max(n[e*4+3],o)}const mI=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];var qb,zp;class uue{constructor(e,t){N(this,qb);N(this,zp);R(this,qb,e),R(this,zp,t)}get length(){return h(this,qb).length}isEmpty(e){return h(this,qb)[e]===mI}minX(e){return h(this,zp)[e*4+0]/256}minY(e){return h(this,zp)[e*4+1]/256}maxX(e){return(h(this,zp)[e*4+2]+1)/256}maxY(e){return(h(this,zp)[e*4+3]+1)/256}}qb=new WeakMap,zp=new WeakMap;const vN=(n,e)=>n==null?void 0:n.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));var Lh,Wr,Si,ty,ny,ry,Zo,Ek,yI;class hue{constructor(e,t){N(this,Ek);N(this,Lh,[[1,0,0,1,0,0]]);N(this,Wr,[-1/0,-1/0,1/0,1/0]);N(this,Si,new Float64Array(hf));ve(this,"_pendingBBoxIdx",-1);N(this,ty);N(this,ny);N(this,ry);N(this,Zo);ve(this,"_savesStack",[]);ve(this,"_markedContentStack",[]);R(this,ty,e.width),R(this,ny,e.height),q(this,Ek,yI).call(this,t)}growOperationsCount(e){e>=h(this,Zo).length&&q(this,Ek,yI).call(this,e,h(this,Zo))}get clipBox(){return h(this,Wr)}save(e){return R(this,Wr,{__proto__:h(this,Wr)}),this._savesStack.push(e),this}restore(e,t){const r=Object.getPrototypeOf(h(this,Wr));if(r===null)return this;R(this,Wr,r);const i=this._savesStack.pop();return i!==void 0&&(t==null||t(i,e),h(this,Zo)[e]=h(this,Zo)[i]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){const r=this._savesStack.pop();return r!==void 0&&(t==null||t(r,e),h(this,Zo)[e]=h(this,Zo)[r]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){const r=this._markedContentStack.pop();return r!==void 0&&(t==null||t(r,e),h(this,Zo)[e]=h(this,Zo)[r]),this}pushBaseTransform(e){return h(this,Lh).push(yt.multiplyByDOMMatrix(h(this,Lh).at(-1),e.getTransform())),this}popBaseTransform(){return h(this,Lh).length>1&&h(this,Lh).pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,h(this,Si).set(hf,0)),this}recordClipBox(e,t,r,i,o,a){const l=yt.multiplyByDOMMatrix(h(this,Lh).at(-1),t.getTransform()),d=hf.slice();yt.axialAlignedBoundingBox([r,o,i,a],l,d);const c=yt.intersect(h(this,Wr),d);return c?(h(this,Wr)[0]=c[0],h(this,Wr)[1]=c[1],h(this,Wr)[2]=c[2],h(this,Wr)[3]=c[3]):(h(this,Wr)[0]=h(this,Wr)[1]=1/0,h(this,Wr)[2]=h(this,Wr)[3]=-1/0),this}recordBBox(e,t,r,i,o,a){const l=h(this,Wr);if(l[0]===1/0)return this;const d=yt.multiplyByDOMMatrix(h(this,Lh).at(-1),t.getTransform());if(l[0]===-1/0)return yt.axialAlignedBoundingBox([r,o,i,a],d,h(this,Si)),this;const c=hf.slice();return yt.axialAlignedBoundingBox([r,o,i,a],d,c),h(this,Si)[0]=Bi(c[0],l[0],h(this,Si)[0]),h(this,Si)[1]=Bi(c[1],l[1],h(this,Si)[1]),h(this,Si)[2]=Bi(c[2],h(this,Si)[2],l[2]),h(this,Si)[3]=Bi(c[3],h(this,Si)[3],l[3]),this}recordFullPageBBox(e){return h(this,Si)[0]=Math.max(0,h(this,Wr)[0]),h(this,Si)[1]=Math.max(0,h(this,Wr)[1]),h(this,Si)[2]=Math.min(h(this,ty),h(this,Wr)[2]),h(this,Si)[3]=Math.min(h(this,ny),h(this,Wr)[3]),this}recordOperation(e,t=!1,r){if(this._pendingBBoxIdx!==e)return this;const i=yN(h(this,Si)[0]*256/h(this,ty)),o=yN(h(this,Si)[1]*256/h(this,ny)),a=xN(h(this,Si)[2]*256/h(this,ty)),l=xN(h(this,Si)[3]*256/h(this,ny));if(bN(h(this,ry),e,i,o,a,l),r)for(const d of r)for(const c of d)c!==e&&bN(h(this,ry),c,i,o,a,l);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,h(this,Wr)[0]=Math.max(h(this,Wr)[0],h(this,Si)[0]),h(this,Wr)[1]=Math.max(h(this,Wr)[1],h(this,Si)[1]),h(this,Wr)[2]=Math.min(h(this,Wr)[2],h(this,Si)[2]),h(this,Wr)[3]=Math.min(h(this,Wr)[3],h(this,Si)[3])),this}take(){return new uue(h(this,Zo),h(this,ry))}takeDebugMetadata(){throw new Error("Unreachable")}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,r){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,r,i=1,o=0,a=0,l){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}}Lh=new WeakMap,Wr=new WeakMap,Si=new WeakMap,ty=new WeakMap,ny=new WeakMap,ry=new WeakMap,Zo=new WeakMap,Ek=new WeakSet,yI=function(e,t){const r=new ArrayBuffer(e*4);R(this,ry,new Uint8ClampedArray(r)),R(this,Zo,new Uint32Array(r)),t&&t.length>0?(h(this,Zo).set(t),h(this,Zo).fill(mI,t.length)):h(this,Zo).fill(mI)};var qa,Va,iy,uc,Vb,Op,Lp,ri;class fue{constructor(e,t=!1){N(this,qa,{__proto__:null});N(this,Va,{__proto__:null,transform:[],moveText:[],sameLineText:[],[xx]:[]});N(this,iy,new Map);N(this,uc,new Set);N(this,Vb,new Map);N(this,Op);N(this,Lp);N(this,ri);R(this,ri,e),t&&(R(this,Op,new Map),R(this,Lp,(r,i)=>{vN(h(this,Op),i).dependencies.add(r)}))}get clipBox(){return h(this,ri).clipBox}growOperationsCount(e){h(this,ri).growOperationsCount(e)}save(e){return R(this,qa,{__proto__:h(this,qa)}),R(this,Va,{__proto__:h(this,Va),transform:{__proto__:h(this,Va).transform},moveText:{__proto__:h(this,Va).moveText},sameLineText:{__proto__:h(this,Va).sameLineText},[xx]:{__proto__:h(this,Va)[xx]}}),h(this,ri).save(e),this}restore(e){h(this,ri).restore(e,h(this,Lp));const t=Object.getPrototypeOf(h(this,qa));return t===null?this:(R(this,qa,t),R(this,Va,Object.getPrototypeOf(h(this,Va))),this)}recordOpenMarker(e){return h(this,ri).recordOpenMarker(e,h(this,Lp)),this}getOpenMarker(){return h(this,ri).getOpenMarker()}recordCloseMarker(e){return h(this,ri).recordCloseMarker(e,h(this,Lp)),this}beginMarkedContent(e){return h(this,ri).beginMarkedContent(e),this}endMarkedContent(e){return h(this,ri).endMarkedContent(e,h(this,Lp)),this}pushBaseTransform(e){return h(this,ri).pushBaseTransform(e),this}popBaseTransform(){return h(this,ri).popBaseTransform(),this}recordSimpleData(e,t){return h(this,qa)[e]=t,this}recordIncrementalData(e,t){return h(this,Va)[e].push(t),this}resetIncrementalData(e,t){return h(this,Va)[e].length=0,this}recordNamedData(e,t){return h(this,iy).set(e,t),this}recordSimpleDataFromNamed(e,t,r){h(this,qa)[e]=h(this,iy).get(t)??r}recordFutureForcedDependency(e,t){return this.recordIncrementalData(xx,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(const t of e)t in h(this,qa)&&this.recordFutureForcedDependency(t,h(this,qa)[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const e of h(this,uc))this.recordFutureForcedDependency(xx,e);return this}resetBBox(e){return h(this,ri).resetBBox(e),this}recordClipBox(e,t,r,i,o,a){return h(this,ri).recordClipBox(e,t,r,i,o,a),this}recordBBox(e,t,r,i,o,a){return h(this,ri).recordBBox(e,t,r,i,o,a),this}recordCharacterBBox(e,t,r,i=1,o=0,a=0,l){const d=r.bbox;let c,u;if(d&&(c=d[2]!==d[0]&&d[3]!==d[1]&&h(this,Vb).get(r),c!==!1&&(u=[0,0,0,0],yt.axialAlignedBoundingBox(d,r.fontMatrix,u),(i!==1||o!==0||a!==0)&&yt.scaleMinMax([i,0,0,-i,o,a],u),c)))return this.recordBBox(e,t,u[0],u[2],u[1],u[3]);if(!l)return this.recordFullPageBBox(e);const f=l();return d&&u&&c===void 0&&(c=u[0]<=o-f.actualBoundingBoxLeft&&u[2]>=o+f.actualBoundingBoxRight&&u[1]<=a-f.actualBoundingBoxAscent&&u[3]>=a+f.actualBoundingBoxDescent,h(this,Vb).set(r,c),c)?this.recordBBox(e,t,u[0],u[2],u[1],u[3]):this.recordBBox(e,t,o-f.actualBoundingBoxLeft,o+f.actualBoundingBoxRight,a-f.actualBoundingBoxAscent,a+f.actualBoundingBoxDescent)}recordFullPageBBox(e){return h(this,ri).recordFullPageBBox(e),this}getSimpleIndex(e){return h(this,qa)[e]}recordDependencies(e,t){const r=h(this,uc),i=h(this,qa),o=h(this,Va);for(const a of t)a in h(this,qa)?r.add(i[a]):a in o&&o[a].forEach(r.add,r);return this}recordNamedDependency(e,t){return h(this,iy).has(t)&&h(this,uc).add(h(this,iy).get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[xx]),h(this,Op)){const i=vN(h(this,Op),e),{dependencies:o}=i;h(this,uc).forEach(o.add,o),h(this,ri)._savesStack.forEach(o.add,o),h(this,ri)._markedContentStack.forEach(o.add,o),o.delete(e),i.isRenderingOperation=!0}const r=!t&&e===h(this,ri)._pendingBBoxIdx;return h(this,ri).recordOperation(e,t,[h(this,uc),h(this,ri)._savesStack,h(this,ri)._markedContentStack]),r&&h(this,uc).clear(),this}recordShowTextOperation(e,t=!1){const r=Array.from(h(this,uc));this.recordOperation(e,t),this.recordIncrementalData("sameLineText",e);for(const i of r)this.recordIncrementalData("sameLineText",i);return this}bboxToClipBoxDropOperation(e,t=!1){const r=!t&&e===h(this,ri)._pendingBBoxIdx;return h(this,ri).bboxToClipBoxDropOperation(e),r&&h(this,uc).clear(),this}take(){return h(this,Vb).clear(),h(this,ri).take()}takeDebugMetadata(){return h(this,Op)}}qa=new WeakMap,Va=new WeakMap,iy=new WeakMap,uc=new WeakMap,Vb=new WeakMap,Op=new WeakMap,Lp=new WeakMap,ri=new WeakMap;var ii,ls,hc,Gb,Kb;const H3=class H3{constructor(e,t,r){N(this,ii);N(this,ls);N(this,hc);N(this,Gb,0);N(this,Kb,0);if(e instanceof H3&&h(e,hc)===!!r)return e;R(this,ii,e),R(this,ls,t),R(this,hc,!!r)}get clipBox(){return h(this,ii).clipBox}growOperationsCount(){throw new Error("Unreachable")}save(e){return Gi(this,Kb)._++,h(this,ii).save(h(this,ls)),this}restore(e){return h(this,Kb)>0&&(h(this,ii).restore(h(this,ls)),Gi(this,Kb)._--),this}recordOpenMarker(e){return Gi(this,Gb)._++,this}getOpenMarker(){return h(this,Gb)>0?h(this,ls):h(this,ii).getOpenMarker()}recordCloseMarker(e){return Gi(this,Gb)._--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return h(this,ii).pushBaseTransform(e),this}popBaseTransform(){return h(this,ii).popBaseTransform(),this}recordSimpleData(e,t){return h(this,ii).recordSimpleData(e,h(this,ls)),this}recordIncrementalData(e,t){return h(this,ii).recordIncrementalData(e,h(this,ls)),this}resetIncrementalData(e,t){return h(this,ii).resetIncrementalData(e,h(this,ls)),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,r){return h(this,ii).recordSimpleDataFromNamed(e,t,h(this,ls)),this}recordFutureForcedDependency(e,t){return h(this,ii).recordFutureForcedDependency(e,h(this,ls)),this}inheritSimpleDataAsFutureForcedDependencies(e){return h(this,ii).inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return h(this,ii).inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return h(this,hc)||h(this,ii).resetBBox(h(this,ls)),this}recordClipBox(e,t,r,i,o,a){return h(this,hc)||h(this,ii).recordClipBox(h(this,ls),t,r,i,o,a),this}recordBBox(e,t,r,i,o,a){return h(this,hc)||h(this,ii).recordBBox(h(this,ls),t,r,i,o,a),this}recordCharacterBBox(e,t,r,i,o,a,l){return h(this,hc)||h(this,ii).recordCharacterBBox(h(this,ls),t,r,i,o,a,l),this}recordFullPageBBox(e){return h(this,hc)||h(this,ii).recordFullPageBBox(h(this,ls)),this}getSimpleIndex(e){return h(this,ii).getSimpleIndex(e)}recordDependencies(e,t){return h(this,ii).recordDependencies(h(this,ls),t),this}recordNamedDependency(e,t){return h(this,ii).recordNamedDependency(h(this,ls),t),this}recordOperation(e){return h(this,ii).recordOperation(h(this,ls),!0),this}recordShowTextOperation(e){return h(this,ii).recordShowTextOperation(h(this,ls),!0),this}bboxToClipBoxDropOperation(e){return h(this,hc)||h(this,ii).bboxToClipBoxDropOperation(h(this,ls),!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}};ii=new WeakMap,ls=new WeakMap,hc=new WeakMap,Gb=new WeakMap,Kb=new WeakMap;let Yj=H3;const id={stroke:["path","transform","filter","strokeColor","strokeAlpha","lineWidth","lineCap","lineJoin","miterLimit","dash"],fill:["path","transform","filter","fillColor","fillAlpha","globalCompositeOperation","SMask"],imageXObject:["transform","SMask","filter","fillAlpha","strokeAlpha","globalCompositeOperation"],rawFillPath:["filter","fillColor","fillAlpha"],showText:["transform","leading","charSpacing","wordSpacing","hScale","textRise","moveText","textMatrix","font","fontObj","filter","fillColor","textRenderingMode","SMask","fillAlpha","strokeAlpha","globalCompositeOperation","sameLineText"],transform:["transform"],transformAndFill:["transform","fillColor"]};var sy,oy,ay,ly,dy,Pk;const sj=class sj{constructor(e){N(this,sy);N(this,oy);N(this,ay,4);N(this,ly,0);N(this,dy,new(h(sj,Pk))(h(this,ay)*6));R(this,sy,e.width),R(this,oy,e.height)}record(e,t,r,i){if(h(this,ly)===h(this,ay)){R(this,ay,h(this,ay)*2);const l=new(h(sj,Pk))(h(this,ay)*6);l.set(h(this,dy)),R(this,dy,l)}const o=yt.domMatrixToTransform(e.getTransform());let a;if(i[0]!==1/0){const l=hf.slice();yt.axialAlignedBoundingBox([0,-r,t,0],o,l);const d=yt.intersect(i,l);if(!d)return;const[c,u,f,p]=d;if(c!==l[0]||u!==l[1]||f!==l[2]||p!==l[3]){const g=Math.atan2(o[1],o[0]),m=Math.abs(Math.sin(g)),y=Math.abs(Math.cos(g));if(m<1e-6||y<1e-6||Math.abs(m-y)<1e-6)a=[c,u,c,p,f,u];else{const v=f-c,x=p-u,w=m*m,S=y*y,_=y*m,b=S-w,C=(x*S-v*_)/b,T=(x*_-v*w)/b;a=[c+T,u,c,u+C,f,p-C]}}}a||(a=[0,-r,0,0,t,-r],yt.applyTransform(a,o,0),yt.applyTransform(a,o,2),yt.applyTransform(a,o,4)),a[0]/=h(this,sy),a[1]/=h(this,oy),a[2]/=h(this,sy),a[3]/=h(this,oy),a[4]/=h(this,sy),a[5]/=h(this,oy),h(this,dy).set(a,h(this,ly)*6),Gi(this,ly)._++}take(){return h(this,dy).subarray(0,h(this,ly)*6)}};sy=new WeakMap,oy=new WeakMap,ay=new WeakMap,ly=new WeakMap,dy=new WeakMap,Pk=new WeakMap,N(sj,Pk,Ds.isFloat16ArraySupported?Float16Array:Float32Array);let xI=sj;var Xb;class pue{constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){N(this,Xb,new Set);this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(const e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),h(this,Xb).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:r}){if(!(!e||h(this,Xb).has(e.loadedName))){if(Zi(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:i,src:o,style:a}=e,l=new FontFace(i,o,a);this.addNativeFontFace(l);try{await l.load(),h(this,Xb).add(i),r==null||r(e)}catch{Bn(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}Hr("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){const r=e.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(i){throw Bn(`Failed to load font '${r.family}': '${i}'.`),e.disableFontFace=!0,i}}return}const t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(r=>{const i=this._queueLoadingCallback(r);this._prepareFontLoadEvent(e,i)})}}get isFontLoadingAPISupported(){var t;const e=!!((t=this._document)!=null&&t.fonts);return Cn(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){return Cn(this,"isSyncFontLoadingSupported",zl||Ds.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(Zi(!i.done,"completeRequest() cannot be called twice."),i.done=!0;r.length>0&&r[0].done;){const o=r.shift();setTimeout(o.callback,0)}}const{loadingRequests:r}=this,i={done:!1,complete:t,callback:e};return r.push(i),i}get _loadTestFont(){const e=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return Cn(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,t){function r(b,C){return b.charCodeAt(C)<<24|b.charCodeAt(C+1)<<16|b.charCodeAt(C+2)<<8|b.charCodeAt(C+3)&255}function i(b){return String.fromCharCode(b>>24&255,b>>16&255,b>>8&255,b&255)}function o(b,C,T,F){const A=b.substring(0,C),D=b.substring(C+T);return A+F+D}let a,l;const d=this._document.createElement("canvas");d.width=1,d.height=1;const c=d.getContext("2d");let u=0;function f(b,C){if(++u>30){Bn("Load test font never loaded."),C();return}if(c.font="30px "+b,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(f.bind(null,b,C))}const p=`lt${Date.now()}${this.loadTestFontId++}`;let g=this._loadTestFont;g=o(g,976,p.length,p);const y=16,v=1482184792;let x=r(g,y);for(a=0,l=p.length-3;a{_.remove(),t.complete()})}}Xb=new WeakMap;var si;class gue{constructor(e,t=null,r,i){ve(this,"compiledGlyphs",Object.create(null));N(this,si);R(this,si,e),this._inspectFont=t,r&&(this.charProcOperatorList=r),i&&Object.assign(this,i)}createNativeFontFace(){var t;if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{const r={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(r.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,r)}return(t=this._inspectFont)==null||t.call(this,this),e}createFontFaceRule(){var r;if(!this.data||this.disableFontFace)return null;const e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`;let t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${e}}`}return(r=this._inspectFont)==null||r.call(this,this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];const r=this.loadedName+"_path_"+t;let i;try{i=e.get(r)}catch(a){Bn(`getPathGenerator - ignoring character: "${a}".`)}const o=hV(i==null?void 0:i.path);return this.fontExtraProperties||e.delete(r),this.compiledGlyphs[t]=o}get black(){return h(this,si).black}get bold(){return h(this,si).bold}get disableFontFace(){return h(this,si).disableFontFace}set disableFontFace(e){Cn(this,"disableFontFace",!!e)}get fontExtraProperties(){return h(this,si).fontExtraProperties}get isInvalidPDFjsFont(){return h(this,si).isInvalidPDFjsFont}get isType3Font(){return h(this,si).isType3Font}get italic(){return h(this,si).italic}get missingFile(){return h(this,si).missingFile}get remeasure(){return h(this,si).remeasure}get vertical(){return h(this,si).vertical}get ascent(){return h(this,si).ascent}get defaultWidth(){return h(this,si).defaultWidth}get descent(){return h(this,si).descent}get bbox(){return h(this,si).bbox}get fontMatrix(){return h(this,si).fontMatrix}get fallbackName(){return h(this,si).fallbackName}get loadedName(){return h(this,si).loadedName}get mimetype(){return h(this,si).mimetype}get name(){return h(this,si).name}get data(){return h(this,si).data}clearData(){h(this,si).clearData()}get cssFontInfo(){return h(this,si).cssFontInfo}get systemFontInfo(){return h(this,si).systemFontInfo}get defaultVMetrics(){return h(this,si).defaultVMetrics}}si=new WeakMap;class KV{}ve(KV,"strings",["fontFamily","fontWeight","italicAngle"]);class XV{}ve(XV,"strings",["css","loadedName","baseFontName","src"]);const Xo=class Xo{};ve(Xo,"bools",["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"]),ve(Xo,"numbers",["ascent","defaultWidth","descent"]),ve(Xo,"strings",["fallbackName","loadedName","mimetype","name"]),ve(Xo,"OFFSET_NUMBERS",Math.ceil(Xo.bools.length*2/8)),ve(Xo,"OFFSET_BBOX",Xo.OFFSET_NUMBERS+Xo.numbers.length*8),ve(Xo,"OFFSET_FONT_MATRIX",Xo.OFFSET_BBOX+1+2*4),ve(Xo,"OFFSET_DEFAULT_VMETRICS",Xo.OFFSET_FONT_MATRIX+1+8*6),ve(Xo,"OFFSET_STRINGS",Xo.OFFSET_DEFAULT_VMETRICS+1+2*3);let pl=Xo;class Sa{}ve(Sa,"KIND",0),ve(Sa,"HAS_BBOX",1),ve(Sa,"HAS_BACKGROUND",2),ve(Sa,"SHADING_TYPE",3),ve(Sa,"N_COORD",4),ve(Sa,"N_COLOR",8),ve(Sa,"N_STOP",12),ve(Sa,"N_FIGURES",16);var Rk,MT,Yb,Qb,O5;class mue{constructor(e){N(this,Qb);N(this,Rk);N(this,MT,new TextDecoder);N(this,Yb);R(this,Rk,e),R(this,Yb,new DataView(e))}get fontFamily(){return q(this,Qb,O5).call(this,0)}get fontWeight(){return q(this,Qb,O5).call(this,1)}get italicAngle(){return q(this,Qb,O5).call(this,2)}}Rk=new WeakMap,MT=new WeakMap,Yb=new WeakMap,Qb=new WeakSet,O5=function(e){Zi(e>r&3;return i===0?void 0:i===2},L5=function(e){return Zi(e0){y=hf.slice();for(let v=0,x=c.length;vtypeof n=="object"&&Number.isInteger(n==null?void 0:n.num)&&n.num>=0&&Number.isInteger(n==null?void 0:n.gen)&&n.gen>=0,jue=n=>typeof n=="object"&&typeof(n==null?void 0:n.name)=="string",kue=$ce.bind(null,vI,jue);var Nh,OT;class _ue{constructor(){N(this,Nh,new Map);N(this,OT,Promise.resolve())}postMessage(e,t){const r={data:structuredClone(e,t?{transfer:t}:null)};h(this,OT).then(()=>{for(const[i]of h(this,Nh))i.call(this,r)})}addEventListener(e,t,r=null){let i=null;if((r==null?void 0:r.signal)instanceof AbortSignal){const{signal:o}=r;if(o.aborted){Bn("LoopbackPort - cannot use an `aborted` signal.");return}const a=()=>this.removeEventListener(e,t);i=()=>o.removeEventListener("abort",a),o.addEventListener("abort",a)}h(this,Nh).set(t,i)}removeEventListener(e,t){const r=h(this,Nh).get(t);r==null||r(),h(this,Nh).delete(t)}terminate(){for(const[,e]of h(this,Nh))e==null||e();h(this,Nh).clear()}}Nh=new WeakMap,OT=new WeakMap;const K2={DATA:1,ERROR:2},_s={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function wN(){}function La(n){if(n instanceof Ng||n instanceof XB||n instanceof dN||n instanceof xT||n instanceof LP)return n;switch(n instanceof Error||typeof n=="object"&&n!==null||Hr('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),n.name){case"AbortException":return new Ng(n.message);case"InvalidPDFException":return new XB(n.message);case"PasswordException":return new dN(n.message,n.code);case"ResponseException":return new xT(n.message,n.status,n.missing);case"UnknownErrorException":return new LP(n.message,n.details)}return new LP(n.message,n.toString())}var Jb,zd,YV,QV,$V,W5;class xS{constructor(e,t,r){N(this,zd);N(this,Jb,new AbortController);this.sourceName=e,this.targetName=t,this.comObj=r,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),r.addEventListener("message",q(this,zd,YV).bind(this),{signal:h(this,Jb).signal})}on(e,t){const r=this.actionHandler;if(r[e])throw new Error(`There is already an actionName called "${e}"`);r[e]=t}send(e,t,r){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},r)}sendWithPromise(e,t,r){const i=this.callbackId++,o=Promise.withResolvers();this.callbackCapabilities[i]=o;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:i,data:t},r)}catch(a){o.reject(a)}return o.promise}sendWithStream(e,t,r,i){const o=this.streamId++,a=this.sourceName,l=this.targetName,d=this.comObj;return new ReadableStream({start:c=>{const u=Promise.withResolvers();return this.streamControllers[o]={controller:c,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},d.postMessage({sourceName:a,targetName:l,action:e,streamId:o,data:t,desiredSize:c.desiredSize},i),u.promise},pull:c=>{const u=Promise.withResolvers();return this.streamControllers[o].pullCall=u,d.postMessage({sourceName:a,targetName:l,stream:_s.PULL,streamId:o,desiredSize:c.desiredSize}),u.promise},cancel:c=>{Zi(c instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[o].cancelCall=u,this.streamControllers[o].isClosed=!0,d.postMessage({sourceName:a,targetName:l,stream:_s.CANCEL,streamId:o,reason:La(c)}),u.promise}},r)}destroy(){var e;(e=h(this,Jb))==null||e.abort(),R(this,Jb,null)}}Jb=new WeakMap,zd=new WeakSet,YV=function({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){q(this,zd,$V).call(this,e);return}if(e.callback){const r=e.callbackId,i=this.callbackCapabilities[r];if(!i)throw new Error(`Cannot resolve callback ${r}`);if(delete this.callbackCapabilities[r],e.callback===K2.DATA)i.resolve(e.data);else if(e.callback===K2.ERROR)i.reject(La(e.reason));else throw new Error("Unexpected callback case");return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const r=this.sourceName,i=e.sourceName,o=this.comObj;Promise.try(t,e.data).then(function(a){o.postMessage({sourceName:r,targetName:i,callback:K2.DATA,callbackId:e.callbackId,data:a})},function(a){o.postMessage({sourceName:r,targetName:i,callback:K2.ERROR,callbackId:e.callbackId,reason:La(a)})});return}if(e.streamId){q(this,zd,QV).call(this,e);return}t(e.data)},QV=function(e){const t=e.streamId,r=this.sourceName,i=e.sourceName,o=this.comObj,a=this,l=this.actionHandler[e.action],d={enqueue(c,u=1,f){if(this.isCancelled)return;const p=this.desiredSize;this.desiredSize-=u,p>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),o.postMessage({sourceName:r,targetName:i,stream:_s.ENQUEUE,streamId:t,chunk:c},f)},close(){this.isCancelled||(this.isCancelled=!0,o.postMessage({sourceName:r,targetName:i,stream:_s.CLOSE,streamId:t}),delete a.streamSinks[t])},error(c){Zi(c instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,o.postMessage({sourceName:r,targetName:i,stream:_s.ERROR,streamId:t,reason:La(c)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};d.sinkCapability.resolve(),d.ready=d.sinkCapability.promise,this.streamSinks[t]=d,Promise.try(l,e.data,d).then(function(){o.postMessage({sourceName:r,targetName:i,stream:_s.START_COMPLETE,streamId:t,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:_s.START_COMPLETE,streamId:t,reason:La(c)})})},$V=function(e){const t=e.streamId,r=this.sourceName,i=e.sourceName,o=this.comObj,a=this.streamControllers[t],l=this.streamSinks[t];switch(e.stream){case _s.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(La(e.reason));break;case _s.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(La(e.reason));break;case _s.PULL:if(!l){o.postMessage({sourceName:r,targetName:i,stream:_s.PULL_COMPLETE,streamId:t,success:!0});break}l.desiredSize<=0&&e.desiredSize>0&&l.sinkCapability.resolve(),l.desiredSize=e.desiredSize,Promise.try(l.onPull||wN).then(function(){o.postMessage({sourceName:r,targetName:i,stream:_s.PULL_COMPLETE,streamId:t,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:_s.PULL_COMPLETE,streamId:t,reason:La(c)})});break;case _s.ENQUEUE:if(Zi(a,"enqueue should have stream controller"),a.isClosed)break;a.controller.enqueue(e.chunk);break;case _s.CLOSE:if(Zi(a,"close should have stream controller"),a.isClosed)break;a.isClosed=!0,a.controller.close(),q(this,zd,W5).call(this,a,t);break;case _s.ERROR:Zi(a,"error should have stream controller"),a.controller.error(La(e.reason)),q(this,zd,W5).call(this,a,t);break;case _s.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(La(e.reason)),q(this,zd,W5).call(this,a,t);break;case _s.CANCEL:if(!l)break;const d=La(e.reason);Promise.try(l.onCancel||wN,d).then(function(){o.postMessage({sourceName:r,targetName:i,stream:_s.CANCEL_COMPLETE,streamId:t,success:!0})},function(c){o.postMessage({sourceName:r,targetName:i,stream:_s.CANCEL_COMPLETE,streamId:t,reason:La(c)})}),l.sinkCapability.reject(d),l.isCancelled=!0,delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}},W5=async function(e,t){var r,i,o;await Promise.allSettled([(r=e.startCall)==null?void 0:r.promise,(i=e.pullCall)==null?void 0:i.promise,(o=e.cancelCall)==null?void 0:o.promise]),delete this.streamControllers[t]};var LT;class ZV{constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:r=null}){N(this,LT,Object.freeze({cMapUrl:"CMap",standardFontDataUrl:"font",wasmUrl:"wasm"}));this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=r}async fetch({kind:e,filename:t}){switch(e){case"cMapUrl":case"standardFontDataUrl":case"wasmUrl":break;default:Hr(`Not implemented: ${e}`)}const r=this[e];if(!r)throw new Error(`Ensure that the \`${e}\` API parameter is provided.`);const i=`${r}${t}`;return this._fetch(i,e).catch(o=>{throw new Error(`Unable to load ${h(this,LT)[e]} data at: ${i}`)})}async _fetch(e,t){Hr("Abstract method `_fetch` called.")}}LT=new WeakMap;class SN extends ZV{async _fetch(e,t){const r=t==="cMapUrl"&&!e.endsWith(".bcmap")?"text":"bytes",i=await E3(e,r);return i instanceof Uint8Array?i:rD(i)}}var Bk;class JV{constructor({enableHWA:e=!1}){N(this,Bk,!1);R(this,Bk,e)}create(e,t){if(e<=0||t<=0)throw new Error("Invalid canvas size");const r=this._createCanvas(e,t);return{canvas:r,context:r.getContext("2d",{willReadFrequently:!h(this,Bk)})}}reset({canvas:e},t,r){if(!e)throw new Error("Canvas is not specified");if(t<=0||r<=0)throw new Error("Invalid canvas size");e.width=t,e.height=r}destroy(e){const{canvas:t}=e;if(!t)throw new Error("Canvas is not specified");t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){Hr("Abstract method `_createCanvas` called.")}}Bk=new WeakMap;class Cue extends JV{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){const r=this._document.createElement("canvas");return r.width=e,r.height=t,r}}class eG{addFilter(e){return"none"}addHCMFilter(e,t){return"none"}addAlphaFilter(e){return"none"}addLuminosityFilter(e){return"none"}addHighlightHCMFilter(e,t,r,i,o){return"none"}destroy(e=!1){}}var hy,ev,Wh,Uh,Jo,fy,py,zt,Ko,bS,kx,U5,_x,tG,wI,Cx,vS,wS,SI,SS;class Aue extends eG{constructor({docId:t,ownerDocument:r=globalThis.document}){super();N(this,zt);N(this,hy);N(this,ev);N(this,Wh);N(this,Uh);N(this,Jo);N(this,fy);N(this,py,0);R(this,Uh,t),R(this,Jo,r)}addFilter(t){if(!t)return"none";let r=h(this,zt,Ko).get(t);if(r)return r;const[i,o,a]=q(this,zt,U5).call(this,t),l=t.length===1?i:`${i}${o}${a}`;if(r=h(this,zt,Ko).get(l),r)return h(this,zt,Ko).set(t,r),r;const d=`g_${h(this,Uh)}_transfer_map_${Gi(this,py)._++}`,c=q(this,zt,_x).call(this,d);h(this,zt,Ko).set(t,c),h(this,zt,Ko).set(l,c);const u=q(this,zt,Cx).call(this,d);return q(this,zt,wS).call(this,i,o,a,u),c}addHCMFilter(t,r){var m;const i=`${t}-${r}`,o="base";let a=h(this,zt,bS).get(o);if((a==null?void 0:a.key)===i||(a?((m=a.filter)==null||m.remove(),a.key=i,a.url="none",a.filter=null):(a={key:i,url:"none",filter:null},h(this,zt,bS).set(o,a)),!t||!r))return a.url;const l=q(this,zt,SS).call(this,t);t=yt.makeHexColor(...l);const d=q(this,zt,SS).call(this,r);if(r=yt.makeHexColor(...d),h(this,zt,kx).style.color="",t==="#000000"&&r==="#ffffff"||t===r)return a.url;const c=new Array(256);for(let y=0;y<=255;y++){const v=y/255;c[y]=v<=.03928?v/12.92:((v+.055)/1.055)**2.4}const u=c.join(","),f=`g_${h(this,Uh)}_hcm_filter`,p=a.filter=q(this,zt,Cx).call(this,f);q(this,zt,wS).call(this,u,u,u,p),q(this,zt,wI).call(this,p);const g=(y,v)=>{const x=l[y]/255,w=d[y]/255,S=new Array(v+1);for(let _=0;_<=v;_++)S[_]=x+_/v*(w-x);return S.join(",")};return q(this,zt,wS).call(this,g(0,5),g(1,5),g(2,5),p),a.url=q(this,zt,_x).call(this,f),a.url}addAlphaFilter(t){let r=h(this,zt,Ko).get(t);if(r)return r;const[i]=q(this,zt,U5).call(this,[t]),o=`alpha_${i}`;if(r=h(this,zt,Ko).get(o),r)return h(this,zt,Ko).set(t,r),r;const a=`g_${h(this,Uh)}_alpha_map_${Gi(this,py)._++}`,l=q(this,zt,_x).call(this,a);h(this,zt,Ko).set(t,l),h(this,zt,Ko).set(o,l);const d=q(this,zt,Cx).call(this,a);return q(this,zt,SI).call(this,i,d),l}addLuminosityFilter(t){let r=h(this,zt,Ko).get(t||"luminosity");if(r)return r;let i,o;if(t?([i]=q(this,zt,U5).call(this,[t]),o=`luminosity_${i}`):o="luminosity",r=h(this,zt,Ko).get(o),r)return h(this,zt,Ko).set(t,r),r;const a=`g_${h(this,Uh)}_luminosity_map_${Gi(this,py)._++}`,l=q(this,zt,_x).call(this,a);h(this,zt,Ko).set(t,l),h(this,zt,Ko).set(o,l);const d=q(this,zt,Cx).call(this,a);return q(this,zt,tG).call(this,d),t&&q(this,zt,SI).call(this,i,d),l}addHighlightHCMFilter(t,r,i,o,a){var w;const l=`${r}-${i}-${o}-${a}`;let d=h(this,zt,bS).get(t);if((d==null?void 0:d.key)===l||(d?((w=d.filter)==null||w.remove(),d.key=l,d.url="none",d.filter=null):(d={key:l,url:"none",filter:null},h(this,zt,bS).set(t,d)),!r||!i))return d.url;const[c,u]=[r,i].map(q(this,zt,SS).bind(this));let f=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),p=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[g,m]=[o,a].map(q(this,zt,SS).bind(this));p{const C=new Array(256),T=(p-f)/b,F=S/255,A=(_-S)/(255*b);let D=0;for(let P=0;P<=b;P++){const L=Math.round(f+P*T),W=F+P*A;for(let O=D;O<=L;O++)C[O]=W;D=L+1}for(let P=D;P<256;P++)C[P]=C[D-1];return C.join(",")},v=`g_${h(this,Uh)}_hcm_${t}_filter`,x=d.filter=q(this,zt,Cx).call(this,v);return q(this,zt,wI).call(this,x),q(this,zt,wS).call(this,y(g[0],m[0],5),y(g[1],m[1],5),y(g[2],m[2],5),x),d.url=q(this,zt,_x).call(this,v),d.url}destroy(t=!1){var r,i,o,a;t&&((r=h(this,fy))!=null&&r.size)||((i=h(this,Wh))==null||i.parentNode.parentNode.remove(),R(this,Wh,null),(o=h(this,ev))==null||o.clear(),R(this,ev,null),(a=h(this,fy))==null||a.clear(),R(this,fy,null),R(this,py,0))}}hy=new WeakMap,ev=new WeakMap,Wh=new WeakMap,Uh=new WeakMap,Jo=new WeakMap,fy=new WeakMap,py=new WeakMap,zt=new WeakSet,Ko=function(){return h(this,ev)||R(this,ev,new Map)},bS=function(){return h(this,fy)||R(this,fy,new Map)},kx=function(){if(!h(this,Wh)){const t=h(this,Jo).createElement("div"),{style:r}=t;r.visibility="hidden",r.contain="strict",r.width=r.height=0,r.position="absolute",r.top=r.left=0,r.zIndex=-1;const i=h(this,Jo).createElementNS(hh,"svg");i.setAttribute("width",0),i.setAttribute("height",0),R(this,Wh,h(this,Jo).createElementNS(hh,"defs")),t.append(i),i.append(h(this,Wh)),h(this,Jo).body.append(t)}return h(this,Wh)},U5=function(t){if(t.length===1){const c=t[0],u=new Array(256);for(let p=0;p<256;p++)u[p]=c[p]/255;const f=u.join(",");return[f,f,f]}const[r,i,o]=t,a=new Array(256),l=new Array(256),d=new Array(256);for(let c=0;c<256;c++)a[c]=r[c]/255,l[c]=i[c]/255,d[c]=o[c]/255;return[a.join(","),l.join(","),d.join(",")]},_x=function(t){if(h(this,hy)===void 0){R(this,hy,"");const r=h(this,Jo).URL;r!==h(this,Jo).baseURI&&(iD(r)?Bn('#createUrl: ignore "data:"-URL for performance reasons.'):R(this,hy,lV(r,"")))}return`url(${h(this,hy)}#${t})`},tG=function(t){const r=h(this,Jo).createElementNS(hh,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(r)},wI=function(t){const r=h(this,Jo).createElementNS(hh,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(r)},Cx=function(t){const r=h(this,Jo).createElementNS(hh,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",t),h(this,zt,kx).append(r),r},vS=function(t,r,i){const o=h(this,Jo).createElementNS(hh,r);o.setAttribute("type","discrete"),o.setAttribute("tableValues",i),t.append(o)},wS=function(t,r,i,o){const a=h(this,Jo).createElementNS(hh,"feComponentTransfer");o.append(a),q(this,zt,vS).call(this,a,"feFuncR",t),q(this,zt,vS).call(this,a,"feFuncG",r),q(this,zt,vS).call(this,a,"feFuncB",i)},SI=function(t,r){const i=h(this,Jo).createElementNS(hh,"feComponentTransfer");r.append(i),q(this,zt,vS).call(this,i,"feFuncA",t)},SS=function(t){return h(this,zt,kx).style.color=t,cC(getComputedStyle(h(this,zt,kx)).getPropertyValue("color"))};zl&&Bn("Please use the `legacy` build in Node.js environments.");async function Tue(n){const t=await process.getBuiltinModule("fs/promises").readFile(n);return new Uint8Array(t)}class Fue extends eG{}class Due extends JV{_createCanvas(e,t){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(e,t)}}class Eue extends ZV{async _fetch(e,t){return Tue(e)}}const Pue=` -struct Uniforms { - offsetX : f32, - offsetY : f32, - scaleX : f32, - scaleY : f32, - paddedWidth : f32, - paddedHeight : f32, - borderSize : f32, - _pad : f32, -}; - -@group(0) @binding(0) var u : Uniforms; - -struct VertexInput { - @location(0) position : vec2, - @location(1) color : vec4, -}; - -struct VertexOutput { - @builtin(position) position : vec4, - @location(0) color : vec3, -}; - -@vertex -fn vs_main(in : VertexInput) -> VertexOutput { - var out : VertexOutput; - let cx = (in.position.x + u.offsetX) * u.scaleX; - let cy = (in.position.y + u.offsetY) * u.scaleY; - out.position = vec4( - ((cx + u.borderSize) / u.paddedWidth) * 2.0 - 1.0, - 1.0 - ((cy + u.borderSize) / u.paddedHeight) * 2.0, - 0.0, - 1.0 - ); - out.color = in.color.rgb; - return out; -} - -@fragment -fn fs_main(in : VertexOutput) -> @location(0) vec4 { - return vec4(in.color, 1.0); -} -`;var NT,Hh,gy,tv,WT,nG;class Rue{constructor(){N(this,WT);N(this,NT,null);N(this,Hh,null);N(this,gy,null);N(this,tv,null)}init(){return h(this,NT)||R(this,NT,q(this,WT,nG).call(this))}get isReady(){return h(this,Hh)!==null}loadMeshShader(){if(!h(this,Hh)||h(this,gy))return;const e=h(this,Hh).createShaderModule({code:Pue});R(this,gy,h(this,Hh).createRenderPipeline({layout:"auto",vertex:{module:e,entryPoint:"vs_main",buffers:[{arrayStride:2*4,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"unorm8x4"}]}]},fragment:{module:e,entryPoint:"fs_main",targets:[{format:h(this,tv)}]},primitive:{topology:"triangle-list"}}))}draw(e,t,r,i,o,a,l,d){this.loadMeshShader();const c=h(this,Hh),{offsetX:u,offsetY:f,scaleX:p,scaleY:g}=i,m=c.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&c.queue.writeBuffer(m,0,e);const y=c.createBuffer({size:Math.max(t.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});t.byteLength>0&&c.queue.writeBuffer(y,0,t);const v=c.createBuffer({size:8*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});c.queue.writeBuffer(v,0,new Float32Array([u,f,p,g,a,l,d,0]));const x=c.createBindGroup({layout:h(this,gy).getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:v}}]}),w=new OffscreenCanvas(a,l),S=w.getContext("webgpu");S.configure({device:c,format:h(this,tv),alphaMode:o?"opaque":"premultiplied"});const _=o?{r:o[0]/255,g:o[1]/255,b:o[2]/255,a:1}:{r:0,g:0,b:0,a:0},b=c.createCommandEncoder(),C=b.beginRenderPass({colorAttachments:[{view:S.getCurrentTexture().createView(),clearValue:_,loadOp:"clear",storeOp:"store"}]});return r>0&&(C.setPipeline(h(this,gy)),C.setBindGroup(0,x),C.setVertexBuffer(0,m),C.setVertexBuffer(1,y),C.draw(r)),C.end(),c.queue.submit([b.finish()]),m.destroy(),y.destroy(),v.destroy(),w.transferToImageBitmap()}}NT=new WeakMap,Hh=new WeakMap,gy=new WeakMap,tv=new WeakMap,WT=new WeakSet,nG=async function(){var e;if(!((e=globalThis.navigator)!=null&&e.gpu))return!1;try{const t=await navigator.gpu.requestAdapter();return t?(R(this,tv,navigator.gpu.getPreferredCanvasFormat()),R(this,Hh,await t.requestDevice()),!0):!1}catch{return!1}};const sD=new Rue;function Bue(){return sD.init()}function Iue(){return sD.isReady}function Mue(){sD.loadMeshShader()}function zue(n,e,t,r,i,o,a,l){return sD.draw(n,e,t,r,i,o,a,l)}const To={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function H5(n,e){if(!e)return;const t=e[2]-e[0],r=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],t,r),n.clip(i)}class M3{isModifyingCurrentTransform(){return!1}getPattern(){Hr("Abstract method `getPattern` called.")}}class Oue extends M3{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}isOriginBased(){return this._p0[0]===0&&this._p0[1]===0&&(!this.isRadial()||this._p1[0]===0&&this._p1[1]===0)}isRadial(){return this._type==="radial"}areConic(){if(!this.isRadial())return!1;const e=Math.hypot(this._p0[0]-this._p1[0],this._p0[1]-this._p1[1]);return e+this._r1>this._r0&&e+this._r0>this._r1}_createGradient(e,t=null){let r,i=this._p0,o=this._p1;if(t&&(i=i.slice(),o=o.slice(),yt.applyTransform(i,t),yt.applyTransform(o,t)),this._type==="axial")r=e.createLinearGradient(i[0],i[1],o[0],o[1]);else if(this._type==="radial"){let a=this._r0,l=this._r1;if(t){const d=new Float32Array(2);yt.singularValueDecompose2dScale(t,d),a*=d[0],l*=d[0]}r=e.createRadialGradient(i[0],i[1],a,o[0],o[1],l)}for(const a of this._colorStops)r.addColorStop(a[0],a[1]);return r}_createReversedGradient(e,t=null){let r=this._p1,i=this._p0;t&&(r=r.slice(),i=i.slice(),yt.applyTransform(r,t),yt.applyTransform(i,t));let o=this._r1,a=this._r0;if(t){const c=new Float32Array(2);yt.singularValueDecompose2dScale(t,c),o*=c[0],a*=c[0]}const l=e.createRadialGradient(r[0],r[1],o,i[0],i[1],a),d=this._colorStops.map(([c,u])=>[1-c,u]).reverse();for(const[c,u]of d)l.addColorStop(c,u);return l}getPattern(e,t,r,i){let o;if(i===To.STROKE||i===To.FILL){if(this.isOriginBased()){let p=yt.transform(r,t.baseTransform);this.matrix&&(p=yt.transform(p,this.matrix));const g=.001,m=Math.hypot(p[0],p[1]),y=Math.hypot(p[2],p[3]),v=(p[0]*p[2]+p[1]*p[3])/(m*y);if(Math.abs(v)d[r*2+1]&&(p=t,t=r,r=p,p=o,o=a,a=p),d[r*2+1]>d[i*2+1]&&(p=r,r=i,i=p,p=a,a=l,l=p),d[t*2+1]>d[r*2+1]&&(p=t,t=r,r=p,p=o,o=a,a=p);const g=(d[t*2]+e.offsetX)*e.scaleX,m=(d[t*2+1]+e.offsetY)*e.scaleY,y=(d[r*2]+e.offsetX)*e.scaleX,v=(d[r*2+1]+e.offsetY)*e.scaleY,x=(d[i*2]+e.offsetX)*e.scaleX,w=(d[i*2+1]+e.offsetY)*e.scaleY;if(m>=w)return;const S=c[o*4],_=c[o*4+1],b=c[o*4+2],C=c[a*4],T=c[a*4+1],F=c[a*4+2],A=c[l*4],D=c[l*4+1],P=c[l*4+2],L=Math.round(m),W=Math.round(w);let O,U,M,I,H,z,G,te;for(let re=L;re<=W;re++){if(rew?ke=1:v===w?ke=0:ke=(v-re)/(v-w),O=y-(y-x)*ke,U=C-(C-A)*ke,M=T-(T-D)*ke,I=F-(F-P)*ke}let me;rew?me=1:me=(m-re)/(m-w),H=g-(g-x)*me,z=S-(S-A)*me,G=_-(_-D)*me,te=b-(b-P)*me;const J=Math.round(Math.min(O,H)),ne=Math.round(Math.max(O,H));let ye=f*re+J*4;for(let ke=J;ke<=ne;ke++)me=(O-ke)/(O-H),me<0?me=0:me>1&&(me=1),u[ye++]=U-(U-z)*me|0,u[ye++]=M-(M-G)*me|0,u[ye++]=I-(I-te)*me|0,u[ye++]=255}}class Nue extends M3{constructor(e){super(),this._posData=e[2],this._colData=e[3],this._vertexCount=e[4],this._bounds=e[5],this._bbox=e[6],this._background=e[7],this.matrix=null,Mue()}_createMeshCanvas(e,t,r){const l=Math.floor(this._bounds[0]),d=Math.floor(this._bounds[1]),c=Math.ceil(this._bounds[2])-l,u=Math.ceil(this._bounds[3])-d,f=Math.min(Math.ceil(Math.abs(c*e[0]*1.1)),3e3)||1,p=Math.min(Math.ceil(Math.abs(u*e[1]*1.1)),3e3)||1,g=c?c/f:1,m=u?u/p:1,y={coords:this._posData,colors:this._colData,offsetX:-l,offsetY:-d,scaleX:1/g,scaleY:1/m},v=f+2*2,x=p+2*2,w=r.create(v,x);if(Iue()&&this._vertexCount>48)w.context.drawImage(zue(this._posData,this._colData,this._vertexCount,y,t,v,x,2),0,0);else{const S=w.context.createImageData(f,p);if(t){const _=S.data;for(let b=0,C=_.length;bc+1e-6||t>u+1e-6)return null;const f=Math.floor((r-l)/c)+1,p=Math.ceil((r+e-o)/c)-1,g=Math.floor((i-d)/u)+1,m=Math.ceil((i+t-a)/u)-1;return p<=f&&m<=g?[f,g]:null}updatePatternDims(e,t){const r=yt.inverseTransform(this.patternBaseMatrix),i=[e[0],e[1]],o=[e[2],e[3]];yt.applyTransform(i,r),yt.applyTransform(o,r),t[0]=Math.abs(o[0]-i[0]),t[1]=Math.abs(o[1]-i[1]),t[2]=Math.min(i[0],o[0]),t[3]=Math.min(i[1],o[1])}_renderTileCanvas(e,t,r,i){var p,g;const[o,a,l,d]=this.bbox,c=e.canvasFactory.create(r.size,i.size),u=c.context,f=this.canvasGraphicsFactory.createCanvasGraphics(u,t);return f.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(f,this.paintType,this.color),u.translate(-r.scale*o,-i.scale*a),f.transform(0,r.scale,0,0,i.scale,0,0),u.save(),(p=f.dependencyTracker)==null||p.save(),this.clipBbox(f,o,a,l,d),f.baseTransform=ji(f.ctx),f.executeOperatorList(this.operatorList),f.endDrawing(),(g=f.dependencyTracker)==null||g.restore(),u.restore(),c}_getCombinedScales(){const e=new Float32Array(2);yt.singularValueDecompose2dScale(this.matrix,e);const[t,r]=e;return yt.singularValueDecompose2dScale(this.baseTransform,e),[t*e[0],r*e[1]]}drawPattern(e,t,r=!1,[i,o],a){const[l,d,c,u]=this.bbox,f=e.dependencyTracker;if(f&&(e.dependencyTracker=new Yj(f,a)),e.save(),r?e.ctx.clip(t,"evenodd"):e.ctx.clip(t),e.ctx.setTransform(...this.patternBaseMatrix),e.ctx.translate(i*this.xstep,o*this.ystep),this.needsIsolation||e.ctx.globalAlpha!==1||e.ctx.globalCompositeOperation!=="source-over"||e.inSMaskMode){const p=c-l,g=u-d,[m,y]=this._getCombinedScales(),v=this.getSizeAndScale(p,this.ctx.canvas.width,m),x=this.getSizeAndScale(g,this.ctx.canvas.height,y),w=this._renderTileCanvas(e,a,v,x);e.ctx.drawImage(w.canvas,l,d,p,g),e.canvasFactory.destroy(w)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,l,d,c,u),e.baseTransformStack.push(e.baseTransform),e.baseTransform=ji(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();e.restore(),f&&(e.dependencyTracker=f)}createPatternCanvas(e,t){const[r,i,o,a]=this.bbox,l=o-r,d=a-i;let{xstep:c,ystep:u}=this;c=Math.abs(c),u=Math.abs(u),nD("TilingType: "+this.tilingType);const[f,p]=this._getCombinedScales();let g=l,m=d,y=!1,v=!1;Math.ceil(c*f)>=Math.ceil(l*f)?g=c:y=!0,Math.ceil(u*p)>=Math.ceil(d*p)?m=u:v=!0;const x=this.getSizeAndScale(g,this.ctx.canvas.width,f),w=this.getSizeAndScale(m,this.ctx.canvas.height,p),S=this._renderTileCanvas(e,t,x,w);if(y||v){const _=S.canvas;y&&(g=c),v&&(m=u);const b=this.getSizeAndScale(g,this.ctx.canvas.width,f),C=this.getSizeAndScale(m,this.ctx.canvas.height,p),T=b.size,F=C.size,A=e.canvasFactory.create(T,F),D=A.context,P=y?Math.floor(l/c):0,L=v?Math.floor(d/u):0;for(let W=0;W<=P;W++)for(let O=0;O<=L;O++)D.drawImage(_,T*W,F*O,T,F,0,0,T,F);return e.canvasFactory.destroy(S),{canvas:A.canvas,canvasEntry:A,scaleX:b.scale,scaleY:C.scale,offsetX:r,offsetY:i}}return{canvas:S.canvas,canvasEntry:S,scaleX:x.scale,scaleY:w.scale,offsetX:r,offsetY:i}}getSizeAndScale(e,t,r){const i=Math.max(UT.MAX_PATTERN_SIZE,t);let o=Math.ceil(e*r);return o>=i?o=i:r=o/e,{scale:r,size:o}}clipBbox(e,t,r,i,o){const a=i-t,l=o-r,d=new Path2D;d.rect(t,r,a,l),yt.axialAlignedBoundingBox([t,r,i,o],ji(e.ctx),e.current.minMax),e.ctx.clip(d),e.current.updateClipFromPath()}setFillAndStrokeStyleToContext(e,t,r){const i=e.ctx,o=e.current;switch(o.patternFill=o.patternStroke=!1,t){case jN.COLORED:const{fillStyle:a,strokeStyle:l}=this.ctx;i.fillStyle=o.fillColor=a,i.strokeStyle=o.strokeColor=l;break;case jN.UNCOLORED:i.fillStyle=i.strokeStyle=r,o.fillColor=o.strokeColor=r;break;default:throw new Gce(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,r,i,o){const a=i!==To.SHADING?yt.transform(r,this.patternBaseMatrix):r,l=this.createPatternCanvas(t,o);let d=new DOMMatrix(a);d=d.translate(l.offsetX,l.offsetY),d=d.scale(1/l.scaleX,1/l.scaleY);const c=e.createPattern(l.canvas,"repeat");return t.canvasFactory.destroy(l.canvasEntry),c.setTransform(d),c}};ve(UT,"MAX_PATTERN_SIZE",3e3);let ij=UT;function Hue({src:n,srcPos:e=0,dest:t,width:r,height:i,nonBlackColor:o=4294967295,inverseDecode:a=!1}){const l=Ds.isLittleEndian?4278190080:255,[d,c]=a?[o,l]:[l,o],u=r>>3,f=r&7,p=d^c,g=n.length;t=new Uint32Array(t.buffer);let m=0;for(let y=0;y>7&1)&p,t[m+1]=d^-(w>>6&1)&p,t[m+2]=d^-(w>>5&1)&p,t[m+3]=d^-(w>>4&1)&p,t[m+4]=d^-(w>>3&1)&p,t[m+5]=d^-(w>>2&1)&p,t[m+6]=d^-(w>>1&1)&p,t[m+7]=d^-(w&1)&p}if(f===0)continue;const v=e>7-x&1)&p}return{srcPos:e,destPos:m}}const kN=16,_N=100,que=15,CN=10,Xa=16,WP=new DOMMatrix,Ol=new Float32Array(2);function Vue(n,e){if(n._removeMirroring)throw new Error("Context is already forwarding operations.");n.__originalSave=n.save,n.__originalRestore=n.restore,n.__originalRotate=n.rotate,n.__originalScale=n.scale,n.__originalTranslate=n.translate,n.__originalTransform=n.transform,n.__originalSetTransform=n.setTransform,n.__originalResetTransform=n.resetTransform,n.__originalClip=n.clip,n.__originalMoveTo=n.moveTo,n.__originalLineTo=n.lineTo,n.__originalBezierCurveTo=n.bezierCurveTo,n.__originalRect=n.rect,n.__originalClosePath=n.closePath,n.__originalBeginPath=n.beginPath,n._removeMirroring=()=>{n.save=n.__originalSave,n.restore=n.__originalRestore,n.rotate=n.__originalRotate,n.scale=n.__originalScale,n.translate=n.__originalTranslate,n.transform=n.__originalTransform,n.setTransform=n.__originalSetTransform,n.resetTransform=n.__originalResetTransform,n.clip=n.__originalClip,n.moveTo=n.__originalMoveTo,n.lineTo=n.__originalLineTo,n.bezierCurveTo=n.__originalBezierCurveTo,n.rect=n.__originalRect,n.closePath=n.__originalClosePath,n.beginPath=n.__originalBeginPath,delete n._removeMirroring},n.save=function(){e.save(),this.__originalSave()},n.restore=function(){e.restore(),this.__originalRestore()},n.translate=function(t,r){e.translate(t,r),this.__originalTranslate(t,r)},n.scale=function(t,r){e.scale(t,r),this.__originalScale(t,r)},n.transform=function(t,r,i,o,a,l){e.transform(t,r,i,o,a,l),this.__originalTransform(t,r,i,o,a,l)},n.setTransform=function(t,r,i,o,a,l){r===void 0?(e.setTransform(t),this.__originalSetTransform(t)):(e.setTransform(t,r,i,o,a,l),this.__originalSetTransform(t,r,i,o,a,l))},n.resetTransform=function(){e.resetTransform(),this.__originalResetTransform()},n.rotate=function(t){e.rotate(t),this.__originalRotate(t)},n.clip=function(t){e.clip(t),this.__originalClip(t)},n.moveTo=function(t,r){e.moveTo(t,r),this.__originalMoveTo(t,r)},n.lineTo=function(t,r){e.lineTo(t,r),this.__originalLineTo(t,r)},n.bezierCurveTo=function(t,r,i,o,a,l){e.bezierCurveTo(t,r,i,o,a,l),this.__originalBezierCurveTo(t,r,i,o,a,l)},n.rect=function(t,r,i,o){e.rect(t,r,i,o),this.__originalRect(t,r,i,o)},n.closePath=function(){e.closePath(),this.__originalClosePath()},n.beginPath=function(){e.beginPath(),this.__originalBeginPath()}}function X2(n,e,t,r,i,o,a,l,d,c){const[u,f,p,g,m,y]=ji(n);if(f===0&&p===0){const w=a*u+m,S=Math.round(w),_=l*g+y,b=Math.round(_),C=(a+d)*u+m,T=Math.abs(Math.round(C)-S)||1,F=(l+c)*g+y,A=Math.abs(Math.round(F)-b)||1;return n.setTransform(Math.sign(u),0,0,Math.sign(g),S,b),n.drawImage(e,t,r,i,o,0,0,T,A),n.setTransform(u,f,p,g,m,y),[T,A]}if(u===0&&g===0){const w=l*p+m,S=Math.round(w),_=a*f+y,b=Math.round(_),C=(l+c)*p+m,T=Math.abs(Math.round(C)-S)||1,F=(a+d)*f+y,A=Math.abs(Math.round(F)-b)||1;return n.setTransform(0,Math.sign(f),Math.sign(p),0,S,b),n.drawImage(e,t,r,i,o,0,0,A,T),n.setTransform(u,f,p,g,m,y),[A,T]}n.drawImage(e,t,r,i,o,a,l,d,c);const v=Math.hypot(u,f),x=Math.hypot(p,g);return[v*d,x*c]}class AN{constructor(e,t){ve(this,"alphaIsShape",!1);ve(this,"fontSize",0);ve(this,"fontSizeScale",1);ve(this,"textMatrix",null);ve(this,"textMatrixScale",1);ve(this,"fontMatrix",GB);ve(this,"leading",0);ve(this,"x",0);ve(this,"y",0);ve(this,"lineX",0);ve(this,"lineY",0);ve(this,"charSpacing",0);ve(this,"wordSpacing",0);ve(this,"textHScale",1);ve(this,"textRenderingMode",Rs.FILL);ve(this,"textRise",0);ve(this,"fillColor","#000000");ve(this,"strokeColor","#000000");ve(this,"tilingPatternDims",null);ve(this,"patternFill",!1);ve(this,"patternStroke",!1);ve(this,"fillAlpha",1);ve(this,"strokeAlpha",1);ve(this,"lineWidth",1);ve(this,"activeSMask",null);ve(this,"transferMaps","none");ve(this,"minMax",_m.slice());this.clipBox=new Float32Array([0,0,e,t])}clone(){var t;const e=Object.create(this);return e.clipBox=this.clipBox.slice(),e.minMax=this.minMax.slice(),e.tilingPatternDims=(t=this.tilingPatternDims)==null?void 0:t.slice(),e}getPathBoundingBox(e=To.FILL,t=null){const r=this.minMax.slice();if(e===To.STROKE){t||Hr("Stroke bounding box must include transform."),yt.singularValueDecompose2dScale(t,Ol);const i=Ol[0]*this.lineWidth/2,o=Ol[1]*this.lineWidth/2;r[0]-=i,r[1]-=o,r[2]+=i,r[3]+=o}return r}updateClipFromPath(){const e=yt.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minMax[0]===1/0}startNewPathAndClipBox(e){this.clipBox.set(e,0),this.minMax.set(_m,0)}getClippedPathBoundingBox(e=To.FILL,t=null){return yt.intersect(this.clipBox,this.getPathBoundingBox(e,t))}}function TN(n,e){if(e instanceof ImageData){n.putImageData(e,0,0);return}const t=e.height,r=e.width,i=t%Xa,o=(t-i)/Xa,a=i===0?o:o+1,l=n.createImageData(r,Xa);let d=0,c;const u=e.data,f=l.data;let p,g,m,y;if(e.kind===E5.GRAYSCALE_1BPP){const v=u.byteLength,x=new Uint32Array(f.buffer,0,f.byteLength>>2),w=x.length,S=r+7>>3,_=4294967295,b=Ds.isLittleEndian?4278190080:255;for(p=0;pS?r:C*8-7,A=F&-8;let D=0,P=0;for(;T>=1}for(;c=o&&(m=i,y=r*m),c=0,g=y;g--;)f[c++]=u[d++],f[c++]=u[d++],f[c++]=u[d++],f[c++]=255;n.putImageData(l,0,p*Xa)}else throw new Error(`bad image kind: ${e.kind}`)}function FN(n,e){if(e.bitmap){n.drawImage(e.bitmap,0,0);return}const t=e.height,r=e.width,i=t%Xa,o=(t-i)/Xa,a=i===0?o:o+1,l=n.createImageData(r,Xa);let d=0;const c=e.data,u=l.data;for(let f=0;fCN&&typeof r=="function",f=u?Date.now()+que:0;let p=0;const g=this.commonObjs,m=this.objs;let y,v;for(;;){if(i!==void 0){if(d===i.nextBreakPoint)return i.breakIt(d,r),d;if(i.shouldSkip(d)){if(++d===c)return d;continue}}if(!o||o(d))if(y=l[d],v=a[d]??null,y!==Sh.dependency)v===null?this[y](d):this[y](d,...v);else for(const w of v){(x=this.dependencyTracker)==null||x.recordNamedData(w,d);const S=w.startsWith("g_")?g:m;if(!S.has(w))return S.get(w,r),d}if(d++,d===c)return d;if(u&&++p>CN){if(Date.now()>f)return r(),d;p=0}}}endDrawing(){q(this,Pc,jI).call(this);for(const e of this.smaskGroupCanvases)this.canvasFactory.destroy(e);this.smaskGroupCanvases.length=0,this._clearPreparedSMask(),this.tempSMask=null,this.smaskStack.length=0,this.cachedPatterns.clear();for(const e of this._cachedBitmapsMap.values()){for(const t of e.values())typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),q(this,Pc,kI).call(this)}_scaleImage(e,t){const r=e.width??e.displayWidth,i=e.height??e.displayHeight,o=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),l=[];let d=o,c=a,u=r,f=i;for(;d>2&&u>1||c>2&&f>1;){let x=u,w=f;d>2&&u>1&&(x=Math.ceil(u/2),d/=u/x),c>2&&f>1&&(w=Math.ceil(f/2),c/=f/w),l.push({newWidth:x,newHeight:w}),u=x,f=w}if(l.length===0)return{img:e,paintWidth:r,paintHeight:i,tmpCanvas:null};if(l.length===1){const{newWidth:x,newHeight:w}=l[0],S=this.canvasFactory.create(x,w);return S.context.drawImage(e,0,0,r,i,0,0,x,w),{img:S.canvas,paintWidth:x,paintHeight:w,tmpCanvas:S}}let p=this.canvasFactory.create(1,1),g=this.canvasFactory.create(1,1),m=r,y=i,v=e;for(const{newWidth:x,newHeight:w}of l)this.canvasFactory.reset(g,x,w),g.context.drawImage(v,0,0,m,y,0,0,x,w),[p,g]=[g,p],v=p.canvas,m=x,y=w;return this.canvasFactory.destroy(g),{img:p.canvas,paintWidth:m,paintHeight:y,tmpCanvas:p}}_createMaskCanvas(e,t){var P,L;const r=this.ctx,{width:i,height:o}=t,a=this.current.fillColor,l=this.current.patternFill,d=ji(r);let c,u,f,p;if((t.bitmap||t.data)&&t.count>1){const W=t.bitmap||t.data.buffer;u=JSON.stringify(l?d:[d.slice(0,4),a]),c=this._cachedBitmapsMap.getOrInsertComputed(W,D3);const O=c.get(u);if(O&&!l){const U=Math.round(Math.min(d[0],d[2])+d[4]),M=Math.round(Math.min(d[1],d[3])+d[5]);return(P=this.dependencyTracker)==null||P.recordDependencies(e,id.transformAndFill),{canvas:O,offsetX:U,offsetY:M}}f=O}f||(p=this.canvasFactory.create(i,o),FN(p.context,t));let g=yt.transform(d,[1/i,0,0,-1/o,0,0]);g=yt.transform(g,[1,0,0,1,0,-o]);const m=_m.slice();yt.axialAlignedBoundingBox([0,0,i,o],g,m);const[y,v,x,w]=m,S=Math.round(x-y)||1,_=Math.round(w-v)||1,b=this.canvasFactory.create(S,_),C=b.context,T=y,F=v;C.translate(-T,-F),C.transform(...g);let A=null;if(!f){const W=this._scaleImage(p.canvas,Kc(C));f=W.img,A=W.tmpCanvas,f!==p.canvas&&(this.canvasFactory.destroy(p),p=null),c&&l&&(c.set(u,f),A=null,p=null)}C.imageSmoothingEnabled=DN(ji(C),t.interpolate),X2(C,f,0,0,f.width,f.height,0,0,i,o),A&&this.canvasFactory.destroy(A),p&&this.canvasFactory.destroy(p),C.globalCompositeOperation="source-in";const D=yt.transform(Kc(C),[1,0,0,1,-T,-F]);return C.fillStyle=l?a.getPattern(r,this,D,To.FILL,e):a,C.fillRect(0,0,i,o),c&&!l&&c.set(u,b.canvas),(L=this.dependencyTracker)==null||L.recordDependencies(e,id.transformAndFill),{canvas:b.canvas,canvasEntry:c&&!l?null:b,offsetX:Math.round(T),offsetY:Math.round(F)}}setLineWidth(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("lineWidth",e),t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("lineCap",e),this.ctx.lineCap=Gue[t]}setLineJoin(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("lineJoin",e),this.ctx.lineJoin=Kue[t]}setMiterLimit(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("miterLimit",e),this.ctx.miterLimit=t}setDash(e,t,r){var o;(o=this.dependencyTracker)==null||o.recordSimpleData("dash",e);const i=this.ctx;i.setLineDash!==void 0&&(i.setLineDash(t),i.lineDashOffset=r)}setRenderingIntent(e,t){}setFlatness(e,t){}setGState(e,t){var r,i,o,a,l;for(const[d,c]of t)switch(d){case"LW":this.setLineWidth(e,c);break;case"LC":this.setLineCap(e,c);break;case"LJ":this.setLineJoin(e,c);break;case"ML":this.setMiterLimit(e,c);break;case"D":this.setDash(e,c[0],c[1]);break;case"RI":this.setRenderingIntent(e,c);break;case"FL":this.setFlatness(e,c);break;case"Font":this.setFont(e,c[0],c[1]);break;case"CA":(r=this.dependencyTracker)==null||r.recordSimpleData("strokeAlpha",e),this.current.strokeAlpha=c;break;case"ca":(i=this.dependencyTracker)==null||i.recordSimpleData("fillAlpha",e),this.ctx.globalAlpha=this.current.fillAlpha=c;break;case"BM":(o=this.dependencyTracker)==null||o.recordSimpleData("globalCompositeOperation",e),this.ctx.globalCompositeOperation=c;break;case"SMask":(a=this.dependencyTracker)==null||a.recordSimpleData("SMask",e),this.current.activeSMask=c?this.tempSMask:null,this.current.activeSMask&&(this.current.activeSMask.blendMode=this.ctx.globalCompositeOperation),this.tempSMask=null,this.checkSMaskState(e);break;case"TR":(l=this.dependencyTracker)==null||l.recordSimpleData("filter",e),this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(c);break}}get inSMaskMode(){return!!this.suspendedCtx}_clearPreparedSMask(){this.smaskPreparedEntry&&(this.canvasFactory.destroy(this.smaskPreparedEntry),this.smaskPreparedEntry=null),this.smaskPreparedFor=null,this.smaskPreparedOffsetX=0,this.smaskPreparedOffsetY=0}_ensurePreparedSMask(e,t,r){e!==this.smaskPreparedFor&&(this._clearPreparedSMask(),this._prepareSMaskCanvas(e,t,r))}checkSMaskState(e){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode(e):!this.current.activeSMask&&t?this.endSMaskMode():this.current.activeSMask&&t&&this._ensurePreparedSMask(this.current.activeSMask,this.ctx.canvas.width,this.ctx.canvas.height)}_prepareSMaskCanvas(e,t,r){const{canvas:i,subtype:o,backdrop:a,transferMap:l}=e,d=o==="Luminosity"||o==="Alpha"&&l;if(!a&&!d){this.smaskPreparedFor=e;return}let c,u,f;if(a&&d){const p=this.canvasFactory.create(t,r),g=p.context;g.drawImage(i,e.offsetX,e.offsetY),g.globalCompositeOperation="destination-atop",g.fillStyle=a,g.fillRect(0,0,t,r),g.globalCompositeOperation="source-over",c=this.canvasFactory.create(t,r);const m=c.context;m.filter=o==="Alpha"?this.filterFactory.addAlphaFilter(l):this.filterFactory.addLuminosityFilter(l),m.drawImage(p.canvas,0,0),m.filter="none",this.canvasFactory.destroy(p),u=f=0}else if(d){c=this.canvasFactory.create(i.width,i.height);const p=c.context;p.filter=o==="Alpha"?this.filterFactory.addAlphaFilter(l):this.filterFactory.addLuminosityFilter(l),p.drawImage(i,0,0),p.filter="none",{offsetX:u,offsetY:f}=e}else{c=this.canvasFactory.create(t,r);const p=c.context;p.drawImage(i,e.offsetX,e.offsetY),p.globalCompositeOperation="destination-atop",p.fillStyle=a,p.fillRect(0,0,t,r),p.globalCompositeOperation="source-over",u=f=0}this.smaskPreparedEntry=c,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=u,this.smaskPreparedOffsetY=f}beginSMaskMode(e){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const{width:t,height:r}=this.ctx.canvas,i=this.canvasFactory.create(t,r);this.smaskScratchCanvas=i,this.suspendedCtx=this.ctx;const o=this.ctx=i.context;o.setTransform(this.suspendedCtx.getTransform()),qw(this.suspendedCtx,o),Vue(o,this.suspendedCtx),this._ensurePreparedSMask(this.current.activeSMask,t,r),this.setGState(e,[["BM","source-over"]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),qw(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null,this.canvasFactory.destroy(this.smaskScratchCanvas),this.smaskScratchCanvas=null,this._clearPreparedSMask()}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const t=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,t,this.ctx,e),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(e[0],e[1],e[2]-e[0],e[3]-e[1]),this.ctx.restore()}composeSMask(e,t,r,i){const o=i[0],a=i[1],l=i[2]-o,d=i[3]-a;if(l===0||d===0)return;const c=this.smaskPreparedEntry;if(c){const u=o-this.smaskPreparedOffsetX,f=a-this.smaskPreparedOffsetY;r.save(),r.globalAlpha=1,r.setTransform(1,0,0,1,0,0);const p=new Path2D;p.rect(o,a,l,d),r.clip(p),r.globalCompositeOperation="destination-in",r.drawImage(c.canvas,u,f,l,d,o,a,l,d),r.restore()}else this.genericComposeSMask(t.context,r,l,d,o,a,t.offsetX,t.offsetY);e.save(),e.globalAlpha=1,e.globalCompositeOperation=t.blendMode||"source-over",e.setTransform(1,0,0,1,0,0),e.drawImage(r.canvas,o,a,l,d,o,a,l,d),e.restore()}genericComposeSMask(e,t,r,i,o,a,l,d){const c=e.canvas,u=o-l,f=a-d;t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const p=new Path2D;p.rect(o,a,r,i),t.clip(p),t.globalCompositeOperation="destination-in",t.drawImage(c,u,f,r,i,o,a,r,i),t.restore()}save(e){var r;this.inSMaskMode&&qw(this.ctx,this.suspendedCtx),this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone(),(r=this.dependencyTracker)==null||r.save(e)}restore(e){var t;if((t=this.dependencyTracker)==null||t.restore(e),this.stateStack.length===0){this.inSMaskMode&&this.endSMaskMode();return}this.current=this.stateStack.pop(),this.ctx.restore(),this.inSMaskMode&&(qw(this.suspendedCtx,this.ctx),this.ctx.setTransform(this.suspendedCtx.getTransform())),this.checkSMaskState(e),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}transform(e,t,r,i,o,a,l){var d;(d=this.dependencyTracker)==null||d.recordIncrementalData("transform",e),this.ctx.transform(t,r,i,o,a,l),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,r,i){let[o]=r;if(!i){o||(o=r[0]=new Path2D),t!==Sh.stroke&&t!==Sh.closeStroke&&(this.current.tilingPatternDims=null),this[t](e,o);return}if(this.dependencyTracker!==null){const l=t===Sh.stroke?this.current.lineWidth/2:0;this.dependencyTracker.resetBBox(e).recordBBox(e,this.ctx,i[0]-l,i[2]+l,i[1]-l,i[3]+l).recordDependencies(e,["transform"])}o instanceof Path2D||(o=r[0]=hV(o)),yt.axialAlignedBoundingBox(i,ji(this.ctx),this.current.minMax);const a=this.current.tilingPatternDims;if(a&&t!==Sh.stroke&&t!==Sh.closeStroke&&this.current.fillColor instanceof ij){const l=yt.intersect(this.current.clipBox,this.current.minMax);l?this.current.fillColor.updatePatternDims(l,a):this.current.tilingPatternDims=null}this[t](e,o),this._pathStartIdx=e}closePath(e){this.ctx.closePath()}stroke(e,t,r=!0){var a;const i=this.ctx,o=this.current.strokeColor;if(i.globalAlpha=this.current.strokeAlpha,this.contentVisible)if(typeof o=="object"&&(o!=null&&o.getPattern)){const l=o.isModifyingCurrentTransform()?i.getTransform():null;if(i.save(),i.strokeStyle=o.getPattern(i,this,Kc(i),To.STROKE,e),l){const d=new Path2D;d.addPath(t,i.getTransform().invertSelf().multiplySelf(l)),t=d}this.rescaleAndStroke(t,!1),i.restore()}else this.rescaleAndStroke(t,!0);(a=this.dependencyTracker)==null||a.recordDependencies(e,id.stroke),r&&this.consumePath(e,t,this.current.getClippedPathBoundingBox(To.STROKE,ji(this.ctx))),i.globalAlpha=this.current.fillAlpha}closeStroke(e,t){this.stroke(e,t)}fill(e,t,r=!0){var c,u,f;const i=this.ctx,o=this.current.fillColor,a=this.current.patternFill;let l=!1;const d=this.current.getClippedPathBoundingBox();if((c=this.dependencyTracker)==null||c.recordDependencies(e,id.fill),a){const p=this.current.tilingPatternDims,g=p&&o.canSkipPatternCanvas(p);if(g){o.drawPattern(this,t,this.pendingEOFill,g,e),this.pendingEOFill=!1,r&&this.consumePath(e,t,d),this.current.tilingPatternDims=null;return}const m=o.isModifyingCurrentTransform()?i.getTransform():null;if((u=this.dependencyTracker)==null||u.save(e),i.save(),i.fillStyle=o.getPattern(i,this,Kc(i),To.FILL,e),m){const y=new Path2D;y.addPath(t,i.getTransform().invertSelf().multiplySelf(m)),t=y}l=!0}this.contentVisible&&d!==null&&(this.pendingEOFill?(i.fill(t,"evenodd"),this.pendingEOFill=!1):i.fill(t)),l&&(i.restore(),(f=this.dependencyTracker)==null||f.restore(e)),r&&this.consumePath(e,t,d)}eoFill(e,t){this.pendingEOFill=!0,this.fill(e,t)}fillStroke(e,t){this.fill(e,t,!1),this.stroke(e,t,!1),this.consumePath(e,t)}eoFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}closeFillStroke(e,t){this.fillStroke(e,t)}closeEOFillStroke(e,t){this.pendingEOFill=!0,this.fillStroke(e,t)}endPath(e,t){this.consumePath(e,t)}rawFillPath(e,t){var r;this.ctx.fill(t),(r=this.dependencyTracker)==null||r.recordDependencies(e,id.rawFillPath).recordOperation(e)}clip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=Xue}eoClip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=EN}beginText(e){var t;this.current.textMatrix=null,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,(t=this.dependencyTracker)==null||t.recordOpenMarker(e).resetIncrementalData("sameLineText").resetIncrementalData("moveText",e)}endText(e){const t=this.pendingTextPaths,r=this.ctx;if(this.dependencyTracker){const{dependencyTracker:i}=this;t!==void 0&&i.recordFutureForcedDependency("textClip",i.getOpenMarker()).recordFutureForcedDependency("textClip",e),i.recordCloseMarker(e)}if(t!==void 0){const i=new Path2D,o=r.getTransform().invertSelf();for(const{transform:a,x:l,y:d,fontSize:c,path:u}of t)u&&i.addPath(u,new DOMMatrix(a).preMultiplySelf(o).translate(l,d).scale(c,-c));r.clip(i)}delete this.pendingTextPaths}setCharSpacing(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("charSpacing",e),this.current.charSpacing=t}setWordSpacing(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("wordSpacing",e),this.current.wordSpacing=t}setHScale(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("hScale",e),this.current.textHScale=t/100}setLeading(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("leading",e),this.current.leading=-t}setFont(e,t,r){var f,p;(f=this.dependencyTracker)==null||f.recordSimpleData("font",e).recordSimpleDataFromNamed("fontObj",t,e);const i=this.commonObjs.get(t),o=this.current;if(!i)throw new Error(`Can't find font for ${t}`);if(o.fontMatrix=i.fontMatrix||GB,(o.fontMatrix[0]===0||o.fontMatrix[3]===0)&&Bn("Invalid font matrix for font "+t),r<0?(r=-r,o.fontDirection=-1):o.fontDirection=1,this.current.font=i,this.current.fontSize=r,i.isType3Font)return;const a=i.loadedName||"sans-serif",l=((p=i.systemFontInfo)==null?void 0:p.css)||`"${a}", ${i.fallbackName}`;let d="normal";i.black?d="900":i.bold&&(d="bold");const c=i.italic?"italic":"normal";let u=r;r_N&&(u=_N),this.current.fontSizeScale=r/u,this.ctx.font=`${c} ${d} ${u}px ${l}`}setTextRenderingMode(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("textRenderingMode",e),this.current.textRenderingMode=t}setTextRise(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("textRise",e),this.current.textRise=t}moveText(e,t,r){var i;(i=this.dependencyTracker)==null||i.resetIncrementalData("sameLineText").recordIncrementalData("moveText",e),this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=r}setLeadingMoveText(e,t,r){this.setLeading(e,-r),this.moveText(e,t,r)}setTextMatrix(e,t){var i;(i=this.dependencyTracker)==null||i.resetIncrementalData("sameLineText").recordSimpleData("textMatrix",e);const{current:r}=this;r.textMatrix=t,r.textMatrixScale=Math.hypot(t[0],t[1]),r.x=r.lineX=0,r.y=r.lineY=0}nextLine(e){var t;this.moveText(e,0,this.current.leading),(t=this.dependencyTracker)==null||t.recordIncrementalData("moveText",this.dependencyTracker.getSimpleIndex("leading")??e)}paintChar(e,t,r,i,o,a){var x,w,S,_;const l=this.ctx,d=this.current,c=d.font,u=d.textRenderingMode,f=d.fontSize/d.fontSizeScale,p=u&Rs.FILL_STROKE_MASK,g=!!(u&Rs.ADD_TO_PATH_FLAG),m=d.patternFill&&!c.missingFile,y=d.patternStroke&&!c.missingFile;let v;if((c.disableFontFace||g||m||y)&&!c.missingFile&&(v=c.getPathGenerator(this.commonObjs,t)),v&&(c.disableFontFace||m||y)){l.save(),l.translate(r,i),l.scale(f,-f),(x=this.dependencyTracker)==null||x.recordCharacterBBox(e,l,c);let b;if(p===Rs.FILL||p===Rs.FILL_STROKE)if(o){b=l.getTransform(),l.setTransform(...o);const C=q(this,Pc,_I).call(this,v,b,o);l.fill(C)}else l.fill(v);if(p===Rs.STROKE||p===Rs.FILL_STROKE)if(a){b||(b=l.getTransform()),l.setTransform(...a);const{a:C,b:T,c:F,d:A}=b,D=yt.inverseTransform(a),P=yt.transform([C,T,F,A,0,0],D);yt.singularValueDecompose2dScale(P,Ol),l.lineWidth*=Math.max(Ol[0],Ol[1])/f,l.stroke(q(this,Pc,_I).call(this,v,b,a))}else l.lineWidth/=f,l.stroke(v);l.restore()}else(p===Rs.FILL||p===Rs.FILL_STROKE)&&(l.fillText(t,r,i),(w=this.dependencyTracker)==null||w.recordCharacterBBox(e,l,c,f,r,i,()=>l.measureText(t))),(p===Rs.STROKE||p===Rs.FILL_STROKE)&&(this.dependencyTracker&&((S=this.dependencyTracker)==null||S.recordCharacterBBox(e,l,c,f,r,i,()=>l.measureText(t)).recordDependencies(e,id.stroke)),l.strokeText(t,r,i));g&&((this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:ji(l),x:r,y:i,fontSize:f,path:v}),(_=this.dependencyTracker)==null||_.recordCharacterBBox(e,l,c,f,r,i))}get isFontSubpixelAAEnabled(){const e=this.canvasFactory.create(10,10),t=e.context;t.scale(1.5,1),t.fillText("I",0,10);const r=t.getImageData(0,0,10,10).data;this.canvasFactory.destroy(e);let i=!1;for(let o=3;o0&&r[o]<255){i=!0;break}return Cn(this,"isFontSubpixelAAEnabled",i)}showText(e,t){var P,L,W,O;this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,id.showText).resetBBox(e),this.current.textRenderingMode&Rs.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",e).inheritPendingDependenciesAsFutureForcedDependencies());const r=this.current,i=r.font;if(i.isType3Font){this.showType3Text(e,t),(P=this.dependencyTracker)==null||P.recordShowTextOperation(e);return}const o=r.fontSize;if(o===0){(L=this.dependencyTracker)==null||L.recordOperation(e);return}const a=this.ctx,l=r.fontSizeScale,d=r.charSpacing,c=r.wordSpacing,u=r.fontDirection,f=r.textHScale*u,p=t.length,g=i.vertical,m=g?1:-1,y=i.defaultVMetrics,v=o*r.fontMatrix[0],x=r.textRenderingMode===Rs.FILL&&!i.disableFontFace&&!r.patternFill;a.save(),r.textMatrix&&a.transform(...r.textMatrix),a.translate(r.x,r.y+r.textRise),u>0?a.scale(f,-1):a.scale(f,1);let w,S;const _=r.textRenderingMode&Rs.FILL_STROKE_MASK,b=_===Rs.FILL||_===Rs.FILL_STROKE,C=_===Rs.STROKE||_===Rs.FILL_STROKE;let T=r.lineWidth;const F=r.textMatrixScale;if(F===0||T===0?C&&(T=this.getSinglePixelWidth()):T/=F,l!==1&&(a.scale(l,l),T/=l),a.lineWidth=T,b&&r.patternFill){a.save();const U=r.fillColor.getPattern(a,this,Kc(a),To.FILL,e);w=ji(a),a.restore(),a.fillStyle=U}if(C&&r.patternStroke){a.save();const U=r.strokeColor.getPattern(a,this,Kc(a),To.STROKE,e);S=ji(a),a.restore(),a.strokeStyle=U}if(i.isInvalidPDFjsFont){const U=[];let M=0;for(const H of t)U.push(H.unicode),M+=H.width;const I=U.join("");if(a.fillText(I,0,0),this.dependencyTracker!==null){const H=a.measureText(I);this.dependencyTracker.recordBBox(e,this.ctx,-H.actualBoundingBoxLeft,H.actualBoundingBoxRight,-H.actualBoundingBoxAscent,H.actualBoundingBoxDescent).recordShowTextOperation(e)}r.x+=M*v*f,a.restore(),this.compose();return}let A=0,D;for(D=0;D0){me=a.measureText(H);const ne=me.width*1e3/o*l;if(reme??a.measureText(H));else if(this.paintChar(e,H,G,te,w,S),z){const ne=G+o*z.offset.x/l,ye=te-o*z.offset.y/l;this.paintChar(e,z.fontChar,ne,ye,w,S)}}const J=g?re*v-I*u:re*v+I*u;A+=J,M&&a.restore()}g?r.y-=A:r.x+=A*f,a.restore(),this.compose(),(O=this.dependencyTracker)==null||O.recordShowTextOperation(e)}showType3Text(e,t){const r=this.ctx,i=this.current,o=i.font,a=i.fontSize,l=i.fontDirection,d=o.vertical?1:-1,c=i.charSpacing,u=i.wordSpacing,f=i.textHScale*l,p=i.fontMatrix||GB,g=t.length,m=i.textRenderingMode===Rs.INVISIBLE;let y,v,x,w;if(m||a===0)return;this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,r.save(),i.textMatrix&&r.transform(...i.textMatrix),r.translate(i.x,i.y+i.textRise),r.scale(f,l);const S=this.dependencyTracker;for(this.dependencyTracker=S?new Yj(S,e):null,y=0;ynew q3(a,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new Yj(this.dependencyTracker,l,!0):null)};r=new ij(t,this.ctx,o,i)}else r=this._getPattern(e,t[1],t[2]);return r}setStrokeColorN(e,...t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("strokeColor",e),this.current.strokeColor=this.getColorN_Pattern(e,t),this.current.patternStroke=!0}setFillColorN(e,...t){var i;(i=this.dependencyTracker)==null||i.recordSimpleData("fillColor",e);const r=this.current.fillColor=this.getColorN_Pattern(e,t);this.current.patternFill=!0,this.current.tilingPatternDims=r instanceof ij?[0,0,0,0]:null}setStrokeRGBColor(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor=t,this.current.patternStroke=!1}setStrokeTransparent(e){var t;(t=this.dependencyTracker)==null||t.recordSimpleData("strokeColor",e),this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(e,t){var r;(r=this.dependencyTracker)==null||r.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor=t,this.current.patternFill=!1,this.current.tilingPatternDims=null}setFillTransparent(e){var t;(t=this.dependencyTracker)==null||t.recordSimpleData("fillColor",e),this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1,this.current.tilingPatternDims=null}_getPattern(e,t,r=null){let i;return this.cachedPatterns.has(t)?i=this.cachedPatterns.get(t):(i=Uue(this.getObject(e,t)),this.cachedPatterns.set(t,i)),r&&(i.matrix=r),i}shadingFill(e,t){var a;if(!this.contentVisible)return;const r=this.ctx;this.save(e);const i=this._getPattern(e,t);r.fillStyle=i.getPattern(r,this,Kc(r),To.SHADING,e);const o=Kc(r);if(o){const{width:l,height:d}=r.canvas,c=_m.slice();yt.axialAlignedBoundingBox([0,0,l,d],o,c);const[u,f,p,g]=c;this.ctx.fillRect(u,f,p-u,g-f)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);(a=this.dependencyTracker)==null||a.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,id.transform).recordDependencies(e,id.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e)}beginInlineImage(){Hr("Should not call beginInlineImage")}beginImageData(){Hr("Should not call beginImageData")}paintFormXObjectBegin(e,t,r){var i;if(this.contentVisible&&(this.save(e),this.baseTransformStack.push(this.baseTransform),t&&this.transform(e,...t),this.baseTransform=ji(this.ctx),r)){yt.axialAlignedBoundingBox(r,this.baseTransform,this.current.minMax);const[o,a,l,d]=r,c=new Path2D;c.rect(o,a,l-o,d-a),this.ctx.clip(c),(i=this.dependencyTracker)==null||i.recordClipBox(e,this.ctx,o,l,a,d),this.endPath(e)}}paintFormXObjectEnd(e){this.contentVisible&&(this.restore(e),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e,t){var m;if(!this.contentVisible)return;this.save(e);const{inSMaskMode:r}=this;r&&(this.endSMaskMode(),this.current.activeSMask=null);const i=this.ctx;if(t.isolated||nD("TODO: Support non-isolated groups."),t.knockout&&Bn("Knockout groups not supported."),!t.needsIsolation&&i.globalAlpha===1&&i.globalCompositeOperation==="source-over"&&!r){if(t.bbox){let y=new Path2D;const[v,x,w,S]=t.bbox;if(y.rect(v,x,w-v,S-x),t.matrix){const _=new Path2D;_.addPath(y,new DOMMatrix(t.matrix)),y=_}i.clip(y)}this.groupStack.push(null),this.groupLevel++;return}const o=ji(i);t.matrix&&i.transform(...t.matrix);const a=[0,0,i.canvas.width,i.canvas.height];let l;t.bbox?(l=_m.slice(),yt.axialAlignedBoundingBox(t.bbox,ji(i),l),l=yt.intersect(l,a)||[0,0,0,0]):l=a;const d=Math.floor(l[0]),c=Math.floor(l[1]),u=Math.max(Math.ceil(l[2])-d,1),f=Math.max(Math.ceil(l[3])-c,1);this.current.startNewPathAndClipBox([0,0,u,f]);const p=this.canvasFactory.create(u,f);t.smask&&this.smaskGroupCanvases.push(p);const g=p.context;if(g.translate(-d,-c),g.transform(...o),!t.isolated&&!t.smask&&r&&t.needsIsolation&&(g.save(),g.setTransform(1,0,0,1,0,0),g.drawImage(i.canvas,-d,-c),g.restore()),t.bbox){let y=new Path2D;const[v,x,w,S]=t.bbox;if(y.rect(v,x,w-v,S-x),t.matrix){const _=new Path2D;_.addPath(y,new DOMMatrix(t.matrix)),y=_}g.clip(y)}t.smask&&this.smaskStack.push({canvas:p.canvas,context:g,offsetX:d,offsetY:c,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null}),(!t.smask||this.dependencyTracker)&&(i.setTransform(1,0,0,1,0,0),i.translate(d,c),i.save()),qw(i,g),this.ctx=g,(m=this.dependencyTracker)==null||m.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(e,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),this.groupLevel++}endGroup(e,t){var o;if(!this.contentVisible)return;this.groupLevel--;const r=this.ctx,i=this.groupStack.pop();if(i===null){this.restore(e);return}if(this.ctx=i,this.ctx.imageSmoothingEnabled=!1,(o=this.dependencyTracker)==null||o.popBaseTransform(),t.smask)this.tempSMask=this.smaskStack.pop(),this.restore(e),this.dependencyTracker&&(this.ctx.restore(),this.inSMaskMode&&this.ctx.setTransform(this.suspendedCtx.getTransform()));else{this.ctx.restore();const a=ji(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...a);const l=_m.slice();yt.axialAlignedBoundingBox([0,0,r.canvas.width,r.canvas.height],a,l),this.ctx.drawImage(r.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy({canvas:r.canvas,context:r}),this.compose(l)}}beginAnnotation(e,t,r,i,o,a){if(q(this,Pc,jI).call(this),Y2(this.ctx),this.ctx.save(),this.save(e),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),r){const l=r[2]-r[0],d=r[3]-r[1];if(a&&this.annotationCanvasMap){i=i.slice(),i[4]-=r[0],i[5]-=r[1],r=r.slice(),r[0]=r[1]=0,r[2]=l,r[3]=d,yt.singularValueDecompose2dScale(ji(this.ctx),Ol);const{viewportScale:c}=this,u=Math.ceil(l*this.outputScaleX*c),f=Math.ceil(d*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,f);const{canvas:p,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(Ol[0],0,0,-Ol[1],0,d*Ol[1]),Y2(this.ctx)}else{Y2(this.ctx),this.endPath(e);const c=new Path2D;c.rect(r[0],r[1],l,d),this.ctx.clip(c)}}this.current=new AN(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...i),this.transform(e,...o),this.baseTransform=ji(this.ctx)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),q(this,Pc,kI).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas),this.baseTransform=this.baseTransformStack.pop()}paintImageMaskXObject(e,t){var l;if(!this.contentVisible)return;const r=t.count;t=this.getObject(e,t.data,t),t.count=r;const i=this.ctx,o=this._createMaskCanvas(e,t),a=o.canvas;i.save(),i.setTransform(1,0,0,1,0,0),i.drawImage(a,o.offsetX,o.offsetY),(l=this.dependencyTracker)==null||l.resetBBox(e).recordBBox(e,this.ctx,o.offsetX,o.offsetX+a.width,o.offsetY,o.offsetY+a.height).recordOperation(e),i.restore(),o.canvasEntry&&this.canvasFactory.destroy(o.canvasEntry),this.compose()}paintImageMaskXObjectRepeat(e,t,r,i=0,o=0,a,l){var f,p,g;if(!this.contentVisible)return;t=this.getObject(e,t.data,t);const d=this.ctx;d.save();const c=ji(d);d.transform(r,i,o,a,0,0);const u=this._createMaskCanvas(e,t);d.setTransform(1,0,0,1,u.offsetX-c[4],u.offsetY-c[5]),(f=this.dependencyTracker)==null||f.resetBBox(e);for(let m=0,y=l.length;mf?u/f:1,l=c>f?c/f:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=l}return this._cachedScaleForStroking}rescaleAndStroke(e,t){const{ctx:r,current:{lineWidth:i}}=this,[o,a]=this.getScaleForStroking();if(o===a){r.lineWidth=(i||1)*o,r.stroke(e);return}const l=r.getLineDash();t&&r.save(),r.scale(o,a),WP.a=1/o,WP.d=1/a;const d=new Path2D;if(d.addPath(e,WP),l.length>0){const c=Math.max(o,a);r.setLineDash(l.map(u=>u/c)),r.lineDashOffset/=c}r.lineWidth=i||1,r.stroke(d),t&&r.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};Pc=new WeakSet,jI=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(this.transparentCanvasEntry),this.transparentCanvas=null,this.transparentCanvasEntry=null)},kI=function(){if(this.pageColors){const e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!=="none"){const t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}},_I=function(e,t,r){const i=new Path2D;return i.addPath(e,new DOMMatrix(r).invertSelf().multiplySelf(t)),i};let db=q3;for(const n in Sh)db.prototype[n]!==void 0&&(db.prototype[Sh[n]]=db.prototype[n]);var Ik,Mk;class oD{constructor(e,t,r){N(this,Ik,null);N(this,Mk,null);ve(this,"_fullReader",null);ve(this,"_rangeReaders",new Set);ve(this,"_source",null);this._source=e,R(this,Ik,t),R(this,Mk,r)}get _progressiveDataLength(){var e;return((e=this._fullReader)==null?void 0:e._loaded)??0}getFullReader(){return Zi(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new(h(this,Ik))(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const r=new(h(this,Mk))(this,e,t);return this._rangeReaders.add(r),r}cancelAllRequests(e){var t;(t=this._fullReader)==null||t.cancel(e);for(const r of new Set(this._rangeReaders))r.cancel(e)}}Ik=new WeakMap,Mk=new WeakMap;class aD{constructor(e){ve(this,"onProgress",null);ve(this,"_contentLength",0);ve(this,"_filename",null);ve(this,"_headersCapability",Promise.withResolvers());ve(this,"_isRangeSupported",!1);ve(this,"_isStreamingSupported",!1);ve(this,"_loaded",0);ve(this,"_stream",null);this._stream=e}_callOnProgress(){var e;(e=this.onProgress)==null||e.call(this,{loaded:this._loaded,total:this._contentLength})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){Hr("Abstract method `read` called")}cancel(e){Hr("Abstract method `cancel` called")}}class lD{constructor(e,t,r){ve(this,"_stream",null);this._stream=e}async read(){Hr("Abstract method `read` called")}cancel(e){Hr("Abstract method `cancel` called")}}function Yue(n){let e=!0,t=r("filename\\*","i").exec(n);if(t){t=t[1];let u=l(t);return u=unescape(u),u=d(u),u=c(u),o(u)}if(t=a(n),t){const u=c(t);return o(u)}if(t=r("filename","i").exec(n),t){t=t[1];let u=l(t);return u=c(u),o(u)}function r(u,f){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',f)}function i(u,f){if(u){if(!/^[\x00-\xFF]+$/.test(f))return f;try{const p=new TextDecoder(u,{fatal:!0}),g=rD(f);f=p.decode(g),e=!1}catch{}}return f}function o(u){return e&&/[\x80-\xff]/.test(u)&&(u=i("utf-8",u),e&&(u=i("iso-8859-1",u))),u}function a(u){const f=[];let p;const g=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(p=g.exec(u))!==null;){let[,y,v,x]=p;if(y=parseInt(y,10),y in f){if(y===0)break;continue}f[y]=[v,x]}const m=[];for(let y=0;y{t._responseOrigin=dD(c.url),lG(c.status,a),this._reader=c.body.getReader();const u=c.headers,{contentLength:f,isRangeSupported:p}=iG({responseHeaders:u,isHttp:!0,rangeChunkSize:o,disableRange:r});this._contentLength=f,this._isRangeSupported=p,this._filename=sG(u),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Ng("Streaming is disabled.")),this._headersCapability.resolve()}).catch(this._headersCapability.reject)}async read(){await this._headersCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:uD(t),done:!1})}cancel(t){var r;(r=this._reader)==null||r.cancel(t),this._abortController.abort()}}class Zue extends lD{constructor(t,r,i){super(t,r,i);ve(this,"_abortController",new AbortController);ve(this,"_readCapability",Promise.withResolvers());ve(this,"_reader",null);const{url:o,withCredentials:a}=t._source,l=new Headers(t.headers);l.append("Range",`bytes=${r}-${i-1}`),aG(o,l,a,this._abortController).then(d=>{const c=dD(d.url);oG(c,t._responseOrigin),lG(d.status,o),this._reader=d.body.getReader(),this._readCapability.resolve()}).catch(this._readCapability.reject)}async read(){await this._readCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:{value:uD(t),done:!1}}cancel(t){var r;(r=this._reader)==null||r.cancel(t),this._abortController.abort()}}function PN(n){return n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function hD(){for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}var HT,dG;class Jue extends oD{constructor(t){super(t,ehe,the);N(this,HT);ve(this,"_progressiveDone",!1);ve(this,"_queuedChunks",[]);const{pdfDataRangeTransport:r}=t,{initialData:i,progressiveDone:o}=r;if((i==null?void 0:i.length)>0){const l=PN(i);this._queuedChunks.push(l)}this._progressiveDone=o;const a=l=>{var d;switch(l.type){case"range":case"progressiveRead":q(this,HT,dG).call(this,l.begin,l.chunk);break;case"progressiveDone":(d=this._fullReader)==null||d.progressiveDone(),this._progressiveDone=!0;break}};r.transportReady(a)}getFullReader(){const t=super.getFullReader();return this._queuedChunks=null,t}getRangeReader(t,r){const i=super.getRangeReader(t,r);return i&&(i.onDone=()=>this._rangeReaders.delete(i),this._source.pdfDataRangeTransport.requestDataRange(t,r)),i}cancelAllRequests(t){super.cancelAllRequests(t),this._source.pdfDataRangeTransport.abort()}}HT=new WeakSet,dG=function(t,r){const i=PN(r);if(t===void 0)this._fullReader?this._fullReader._enqueue(i):this._queuedChunks.push(i);else{const o=this._rangeReaders.keys().find(a=>a._begin===t);Zi(o,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),o._enqueue(i)}};var zk;class ehe extends aD{constructor(t){super(t);N(this,zk,hD.bind(this));ve(this,"_done",!1);ve(this,"_queuedChunks",null);ve(this,"_requests",[]);const{pdfDataRangeTransport:r,disableRange:i,disableStream:o}=t._source,{length:a,contentDispositionFilename:l}=r;this._queuedChunks=t._queuedChunks||[];for(const c of this._queuedChunks)this._loaded+=c.byteLength;this._done=t._progressiveDone,this._contentLength=a,this._isStreamingSupported=!o,this._isRangeSupported=!i,R3(l)&&(this._filename=l),this._headersCapability.resolve();const d=this._loaded;Promise.resolve().then(()=>{d>0&&this._loaded===d&&this._callOnProgress()})}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength,this._callOnProgress())}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,h(this,zk).call(this)}progressiveDone(){this._done||(this._done=!0),this._queuedChunks.length===0&&h(this,zk).call(this)}}zk=new WeakMap;var Ok;class the extends lD{constructor(t,r,i){super(t,r,i);N(this,Ok,hD.bind(this));ve(this,"onDone",null);ve(this,"_begin",-1);ve(this,"_done",!1);ve(this,"_queuedChunk",null);ve(this,"_requests",[]);this._begin=r}_enqueue(t){var r;this._done||(this._requests.length===0?this._queuedChunk=t:(this._requests.shift().resolve({value:t,done:!1}),h(this,Ok).call(this)),this._done=!0,(r=this.onDone)==null||r.call(this))}async read(){if(this._queuedChunk){const r=this._queuedChunk;return this._queuedChunk=null,{value:r,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){var r;this._done=!0,h(this,Ok).call(this),(r=this.onDone)==null||r.call(this)}}Ok=new WeakMap;const UP=200,RN=206;function nhe(n){return typeof n!="string"?n:rD(n).buffer}var fu,d1,cG,uG;class rhe extends oD{constructor(t){super(t,ihe,she);N(this,d1);N(this,fu,new WeakMap);ve(this,"_responseOrigin",null);const{httpHeaders:r,url:i}=t;this.url=i,this.isHttp=/https?:/.test(i.protocol),this.headers=rG(this.isHttp,r)}_request(t){const r=new XMLHttpRequest,i={validateStatus:null,onHeadersReceived:t.onHeadersReceived,onDone:t.onDone,onError:t.onError,onProgress:t.onProgress};h(this,fu).set(r,i),r.open("GET",this.url),r.withCredentials=this._source.withCredentials;for(const[o,a]of this.headers)r.setRequestHeader(o,a);return this.isHttp&&"begin"in t&&"end"in t?(r.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.validateStatus=o=>o===RN||o===UP):i.validateStatus=o=>o===UP,r.responseType="arraybuffer",Zi(t.onError,"Expected `onError` callback to be provided."),r.onerror=()=>t.onError(r.status),r.onreadystatechange=q(this,d1,uG).bind(this,r),r.onprogress=q(this,d1,cG).bind(this,r),r.send(null),r}_abortRequest(t){h(this,fu).has(t)&&(h(this,fu).delete(t),t.abort())}getRangeReader(t,r){const i=super.getRangeReader(t,r);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}}fu=new WeakMap,d1=new WeakSet,cG=function(t,r){var o;const i=h(this,fu).get(t);(o=i==null?void 0:i.onProgress)==null||o.call(i,r)},uG=function(t,r){const i=h(this,fu).get(t);if(!i||(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),t.readyState!==4)||!h(this,fu).has(t))return;if(h(this,fu).delete(t),t.status===0&&this.isHttp){i.onError(t.status);return}const o=t.status||UP;if(!i.validateStatus(o)){i.onError(t.status);return}const a=nhe(t.response);if(o===RN){const l=t.getResponseHeader("Content-Range");/bytes (\d+)-(\d+)\/(\d+)/.test(l)?i.onDone(a):(Bn('Missing or invalid "Content-Range" header.'),i.onError(0))}else a?i.onDone(a):i.onError(t.status)};var Lk,Nu,hG,fG,pG,gG;class ihe extends aD{constructor(t){super(t);N(this,Nu);N(this,Lk,hD.bind(this));ve(this,"_cachedChunks",[]);ve(this,"_done",!1);ve(this,"_requests",[]);ve(this,"_storedError",null);this._fullRequestXhr=t._request({onHeadersReceived:q(this,Nu,hG).bind(this),onDone:q(this,Nu,fG).bind(this),onError:q(this,Nu,pG).bind(this),onProgress:q(this,Nu,gG).bind(this)})}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t),h(this,Lk).call(this),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}Lk=new WeakMap,Nu=new WeakSet,hG=function(){const t=this._stream,{disableRange:r,rangeChunkSize:i}=t._source,o=this._fullRequestXhr;t._responseOrigin=dD(o.responseURL);const a=o.getAllResponseHeaders(),l=new Headers(a?a.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(u=>{const[f,...p]=u.split(": ");return[f,p.join(": ")]}):[]),{contentLength:d,isRangeSupported:c}=iG({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:i,disableRange:r});this._contentLength=d,this._isRangeSupported=c,this._filename=sG(l),this._isRangeSupported&&t._abortRequest(o),this._headersCapability.resolve()},fG=function(t){this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._cachedChunks.push(t),this._done=!0,this._cachedChunks.length===0&&h(this,Lk).call(this)},pG=function(t){this._storedError=cD(t,this._stream.url),this._headersCapability.reject(this._storedError);for(const r of this._requests)r.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0},gG=function(t){var r;(r=this.onProgress)==null||r.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})};var Nk,Ff,mG,yG,CI;class she extends lD{constructor(t,r,i){super(t,r,i);N(this,Ff);N(this,Nk,hD.bind(this));ve(this,"onClosed",null);ve(this,"_done",!1);ve(this,"_queuedChunk",null);ve(this,"_requests",[]);ve(this,"_storedError",null);this._requestXhr=t._request({begin:r,end:i,onHeadersReceived:q(this,Ff,mG).bind(this),onDone:q(this,Ff,yG).bind(this),onError:q(this,Ff,CI).bind(this),onProgress:null})}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const r=this._queuedChunk;return this._queuedChunk=null,{value:r,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){var r;this._done=!0,h(this,Nk).call(this),this._stream._abortRequest(this._requestXhr),(r=this.onClosed)==null||r.call(this)}}Nk=new WeakMap,Ff=new WeakSet,mG=function(){var r;const t=dD((r=this._requestXhr)==null?void 0:r.responseURL);try{oG(t,this._stream._responseOrigin)}catch(i){this._storedError=i,q(this,Ff,CI).call(this,0)}},yG=function(t){var r;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,h(this,Nk).call(this),(r=this.onClosed)==null||r.call(this)},CI=function(t){this._storedError??(this._storedError=cD(t,this._stream.url));for(const r of this._requests)r.reject(this._storedError);this._requests.length=0,this._queuedChunk=null};function xG(n,e=null){const t=process.getBuiltinModule("fs"),{Readable:r}=process.getBuiltinModule("stream"),i=t.createReadStream(n,e);return r.toWeb(i)}class ohe extends oD{constructor(e){super(e,ahe,lhe);const{url:t}=e;Zi(t.protocol==="file:","PDFNodeStream only supports file:// URLs.")}}class ahe extends aD{constructor(t){super(t);ve(this,"_reader",null);const{disableRange:r,disableStream:i,rangeChunkSize:o,url:a}=t._source;this._isStreamingSupported=!i,process.getBuiltinModule("fs/promises").lstat(a).then(d=>{const c=xG(a);this._reader=c.getReader();const{size:u}=d;this._contentLength=u,this._isRangeSupported=!r&&u>2*o,!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new Ng("Streaming is disabled.")),this._headersCapability.resolve()}).catch(d=>{d.code==="ENOENT"&&(d=cD(0,a)),this._headersCapability.reject(d)})}async read(){await this._headersCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:(this._loaded+=t.byteLength,this._callOnProgress(),{value:uD(t),done:!1})}cancel(t){var r;(r=this._reader)==null||r.cancel(t)}}class lhe extends lD{constructor(t,r,i){super(t,r,i);ve(this,"_readCapability",Promise.withResolvers());ve(this,"_reader",null);const{url:o}=t._source;try{const a=xG(o,{start:r,end:i-1});this._reader=a.getReader(),this._readCapability.resolve()}catch(a){this._readCapability.reject(a)}}async read(){await this._readCapability.promise;const{value:t,done:r}=await this._reader.read();return r?{value:t,done:r}:{value:uD(t),done:!1}}cancel(t){var r;(r=this._reader)==null||r.cancel(t)}}function dhe(n){return rj(n)?Que:zl?ohe:rhe}var Wk,Uk;class Bu{static get workerPort(){return h(this,Wk)}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw new Error("Invalid `workerPort` type.");R(this,Wk,e)}static get workerSrc(){return h(this,Uk)}static set workerSrc(e){if(typeof e!="string")throw new Error("Invalid `workerSrc` type.");R(this,Uk,e)}}Wk=new WeakMap,Uk=new WeakMap,N(Bu,Wk,null),N(Bu,Uk,"");var nv,Hk;class che{constructor({parsedData:e,rawData:t}){N(this,nv);N(this,Hk);R(this,nv,e),R(this,Hk,t)}getRaw(){return h(this,Hk)}get(e){return h(this,nv).get(e)??null}[Symbol.iterator](){return h(this,nv).entries()}}nv=new WeakMap,Hk=new WeakMap;const Ax=Symbol("INTERNAL");var qk,Vk,Gk,rv;class uhe{constructor(e,{name:t,intent:r,usage:i,rbGroups:o}){N(this,qk,!1);N(this,Vk,!1);N(this,Gk,!1);N(this,rv,!0);R(this,qk,!!(e&Rl.DISPLAY)),R(this,Vk,!!(e&Rl.PRINT)),this.name=t,this.intent=r,this.usage=i,this.rbGroups=o}get visible(){if(h(this,Gk))return h(this,rv);if(!h(this,rv))return!1;const{print:e,view:t}=this.usage;return h(this,qk)?(t==null?void 0:t.viewState)!=="OFF":h(this,Vk)?(e==null?void 0:e.printState)!=="OFF":!0}_setVisible(e,t,r=!1){e!==Ax&&Hr("Internal method `_setVisible` called."),R(this,Gk,r),R(this,rv,t)}}qk=new WeakMap,Vk=new WeakMap,Gk=new WeakMap,rv=new WeakMap;var Np,oi,iv,sv,Kk,AI;class hhe{constructor(e,t=Rl.DISPLAY){N(this,Kk);N(this,Np,null);N(this,oi,new Map);N(this,iv,null);N(this,sv,null);if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,R(this,sv,e.order);for(const r of e.groups)h(this,oi).set(r.id,new uhe(t,r));if(e.baseState==="OFF")for(const r of h(this,oi).values())r._setVisible(Ax,!1);for(const r of e.on)h(this,oi).get(r)._setVisible(Ax,!0);for(const r of e.off)h(this,oi).get(r)._setVisible(Ax,!1);R(this,iv,this.getHash())}}isVisible(e){if(h(this,oi).size===0)return!0;if(!e)return nD("Optional content group not defined."),!0;if(e.type==="OCG")return h(this,oi).has(e.id)?h(this,oi).get(e.id).visible:(Bn(`Optional content group not found: ${e.id}`),!0);if(e.type==="OCMD"){if(e.expression)return q(this,Kk,AI).call(this,e.expression);if(!e.policy||e.policy==="AnyOn"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(h(this,oi).get(t).visible)return!0}return!1}else if(e.policy==="AllOn"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(!h(this,oi).get(t).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(!h(this,oi).get(t).visible)return!0}return!1}else if(e.policy==="AllOff"){for(const t of e.ids){if(!h(this,oi).has(t))return Bn(`Optional content group not found: ${t}`),!0;if(h(this,oi).get(t).visible)return!1}return!0}return Bn(`Unknown optional content policy ${e.policy}.`),!0}return Bn(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,r=!0){var o;const i=h(this,oi).get(e);if(!i){Bn(`Optional content group not found: ${e}`);return}if(r&&t&&i.rbGroups.length)for(const a of i.rbGroups)for(const l of a)l!==e&&((o=h(this,oi).get(l))==null||o._setVisible(Ax,!1,!0));i._setVisible(Ax,!!t,!0),R(this,Np,null)}setOCGState({state:e,preserveRB:t}){let r;for(const i of e){switch(i){case"ON":case"OFF":case"Toggle":r=i;continue}const o=h(this,oi).get(i);if(o)switch(r){case"ON":this.setVisibility(i,!0,t);break;case"OFF":this.setVisibility(i,!1,t);break;case"Toggle":this.setVisibility(i,!o.visible,t);break}}R(this,Np,null)}get hasInitialVisibility(){return h(this,iv)===null||this.getHash()===h(this,iv)}getOrder(){return h(this,oi).size?h(this,sv)?h(this,sv).slice():[...h(this,oi).keys()]:null}getGroup(e){return h(this,oi).get(e)||null}getHash(){if(h(this,Np)!==null)return h(this,Np);const e=new gI;for(const[t,r]of h(this,oi))e.update(`${t}:${r.visible}`);return R(this,Np,e.hexdigest())}[Symbol.iterator](){return h(this,oi).entries()}}Np=new WeakMap,oi=new WeakMap,iv=new WeakMap,sv=new WeakMap,Kk=new WeakSet,AI=function(e){const t=e.length;if(t<2)return!0;const r=e[0];for(let i=1;ip===g+1)&&R(this,bs,null)}deletePages(e){q(this,ra,jS).call(this);const t=h(this,bs),r=q(this,ra,kS).call(this);R(this,pu,{pageNumberToId:t.slice(),pagesNumber:h(this,ko),prevPageNumbers:h(this,pc).slice()});const i=h(this,ko)-e.length;R(this,ko,i);const o=R(this,bs,new Uint32Array(i));R(this,pc,new Int32Array(i));let a=0,l=0;for(const d of e){const c=d-1;c!==a&&(o.set(t.subarray(a,c),l),l+=c-a),a=c+1}ah(this,bs)[t-1])})}cancelCopy(){R(this,my,null)}pastePages(e){q(this,ra,jS).call(this);const t=h(this,bs),r=q(this,ra,kS).call(this),{pageNumbers:i,pageIds:o}=h(this,my),a=h(this,ko)+i.length;R(this,ko,a);const l=R(this,bs,new Uint32Array(a));R(this,pc,new Int32Array(a)),l.set(t.subarray(0,e),0),l.set(o,e),l.set(t.subarray(e),e+i.length),q(this,ra,q5).call(this,r,null,e,i),R(this,my,null)}hasBeenAltered(){return h(this,bs)!==null}getPageMappingForSaving(e=null){e??(e=q(this,ra,kS).call(this));let t=0;for(const i of e.values())t=Math.max(t,i.length);const r=new Array(t);for(let i=0;ia[0]-l[0]);for(let a=0,l=i.length;ar-i);const t=new Map;for(let r=0,i=e.length;r=r&&c({...Promise.withResolvers(),data:Tx});var bd;class bG{constructor(){N(this,bd,new Map)}get(e,t=null){if(t){const i=h(this,bd).getOrInsertComputed(e,BN);return i.promise.then(()=>t(i.data)),null}const r=h(this,bd).get(e);if(!r||r.data===Tx)throw new Error(`Requesting object that isn't resolved yet ${e}.`);return r.data}has(e){const t=h(this,bd).get(e);return!!t&&t.data!==Tx}delete(e){const t=h(this,bd).get(e);return!t||t.data===Tx?!1:(h(this,bd).delete(e),!0)}resolve(e,t=null){const r=h(this,bd).getOrInsertComputed(e,BN);if(r.data!==Tx)throw new Error(`Object already resolved ${e}.`);r.data=t,r.resolve()}clear(){var e;for(const{data:t}of h(this,bd).values())(e=t==null?void 0:t.bitmap)==null||e.close();h(this,bd).clear()}*[Symbol.iterator](){for(const[e,{data:t}]of h(this,bd))t!==Tx&&(yield[e,t])}}bd=new WeakMap;const phe=1e5,IN=30;var o7,Wp,ga,Xk,Yk,ov,yy,qh,Qk,$k,xy,Zk,av,Up,lv,Jk,dv,by,e_,t_,cv,vy,n_,uv,hv,Df,vG,wG,TI,Kl,V5,FI,SG,jG;const vo=class vo{constructor({textContentSource:e,images:t,container:r,viewport:i}){N(this,Df);N(this,Wp,Promise.withResolvers());N(this,ga,null);N(this,Xk,!1);N(this,Yk,!!((o7=globalThis.FontInspector)!=null&&o7.enabled));N(this,ov,null);N(this,yy,null);N(this,qh,null);N(this,Qk,0);N(this,$k,0);N(this,xy,null);N(this,Zk,null);N(this,av,0);N(this,Up,0);N(this,lv,Object.create(null));N(this,Jk,[]);N(this,dv,null);N(this,by,[]);N(this,e_,new WeakMap);N(this,t_,null);var c;if(e instanceof ReadableStream)R(this,dv,e);else if(typeof e=="object")R(this,dv,new ReadableStream({start(u){u.enqueue(e),u.close()}}));else throw new Error('No "textContentSource" parameter specified.');R(this,ga,R(this,Zk,r)),R(this,ov,t),R(this,Up,i.scale*Lu.pixelRatio),R(this,av,i.rotation),R(this,qh,{div:null,properties:null,ctx:null});const{pageWidth:o,pageHeight:a,pageX:l,pageY:d}=i.rawDims;R(this,t_,[1,0,0,-1,-l,d+a]),R(this,$k,o),R(this,Qk,a),q(c=vo,Kl,SG).call(c),r.style.setProperty("--min-font-size",h(vo,uv)),k0(r,i),h(this,Wp).promise.finally(()=>{h(vo,hv).delete(this),R(this,qh,null),R(this,lv,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:e,isFirefox:t}=Ds.platform;return Cn(this,"fontFamilyMap",new Map([["sans-serif",`${e&&t?"Calibri, ":""}sans-serif`],["monospace",`${e&&t?"Lucida Console, ":""}monospace`]]))}render(){h(this,ov)&&h(this,ga).append(h(this,ov).render());const e=()=>{h(this,xy).read().then(({value:t,done:r})=>{if(r){h(this,Wp).resolve();return}h(this,yy)??R(this,yy,t.lang),Object.assign(h(this,lv),t.styles),q(this,Df,vG).call(this,t.items),e()},h(this,Wp).reject)};return R(this,xy,h(this,dv).getReader()),h(vo,hv).add(this),e(),h(this,Wp).promise}update({viewport:e,onBefore:t=null}){var o;const r=e.scale*Lu.pixelRatio,i=e.rotation;if(i!==h(this,av)&&(t==null||t(),R(this,av,i),k0(h(this,Zk),{rotation:i})),r!==h(this,Up)){t==null||t(),R(this,Up,r);const a={div:null,properties:null,ctx:q(o=vo,Kl,V5).call(o,h(this,yy))};for(const l of h(this,by))a.properties=h(this,e_).get(l),a.div=l,q(this,Df,TI).call(this,a)}}cancel(){var t;const e=new Ng("TextLayer task cancelled.");(t=h(this,xy))==null||t.cancel(e).catch(()=>{}),R(this,xy,null),h(this,Wp).reject(e)}get textDivs(){return h(this,by)}get textContentItemsStr(){return h(this,Jk)}static cleanup(){if(!(h(this,hv).size>0)){h(this,cv).clear();for(const{canvas:e}of h(this,vy).values())e.remove();h(this,vy).clear()}}};Wp=new WeakMap,ga=new WeakMap,Xk=new WeakMap,Yk=new WeakMap,ov=new WeakMap,yy=new WeakMap,qh=new WeakMap,Qk=new WeakMap,$k=new WeakMap,xy=new WeakMap,Zk=new WeakMap,av=new WeakMap,Up=new WeakMap,lv=new WeakMap,Jk=new WeakMap,dv=new WeakMap,by=new WeakMap,e_=new WeakMap,t_=new WeakMap,cv=new WeakMap,vy=new WeakMap,n_=new WeakMap,uv=new WeakMap,hv=new WeakMap,Df=new WeakSet,vG=function(e){var i,o;if(h(this,Xk))return;(o=h(this,qh)).ctx??(o.ctx=q(i=vo,Kl,V5).call(i,h(this,yy)));const t=h(this,by),r=h(this,Jk);for(const a of e){if(t.length>phe){Bn("Ignoring additional textDivs for performance reasons."),R(this,Xk,!0);return}if(a.str===void 0){if(a.type==="beginMarkedContentProps"||a.type==="beginMarkedContent"){const l=h(this,ga);R(this,ga,document.createElement("span")),h(this,ga).classList.add("markedContent"),a.id&&h(this,ga).setAttribute("id",`${a.id}`),a.tag==="Artifact"&&(h(this,ga).ariaHidden=!0),l.append(h(this,ga))}else a.type==="endMarkedContent"&&R(this,ga,h(this,ga).parentNode);continue}r.push(a.str),q(this,Df,wG).call(this,a)}},wG=function(e){var m;const t=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};h(this,by).push(t);const i=yt.transform(h(this,t_),e.transform);let o=Math.atan2(i[1],i[0]);const a=h(this,lv)[e.fontName];a.vertical&&(o+=Math.PI/2);let l=h(this,Yk)&&a.fontSubstitution||a.fontFamily;l=vo.fontFamilyMap.get(l)||l;const d=Math.hypot(i[2],i[3]),c=d*q(m=vo,Kl,jG).call(m,l,a,h(this,yy));let u,f;o===0?(u=i[4],f=i[5]-c):(u=i[4]+c*Math.sin(o),f=i[5]-c*Math.cos(o));const p=t.style;p.left=`${(100*u/h(this,$k)).toFixed(2)}%`,p.top=`${(100*f/h(this,Qk)).toFixed(2)}%`,p.setProperty("--font-height",`${d.toFixed(2)}px`),p.fontFamily=l,r.fontSize=d,t.setAttribute("role","presentation"),t.textContent=e.str,t.dir=e.dir,h(this,Yk)&&(t.dataset.fontName=a.fontSubstitutionLoadedName||e.fontName),o!==0&&(r.angle=o*(180/Math.PI));let g=!1;if(e.str.length>1)g=!0;else if(e.str!==" "&&e.transform[0]!==e.transform[3]){const y=Math.abs(e.transform[0]),v=Math.abs(e.transform[3]);y!==v&&Math.max(y,v)/Math.min(y,v)>1.5&&(g=!0)}if(g&&(r.canvasWidth=a.vertical?e.height:e.width),h(this,e_).set(t,r),h(this,qh).div=t,h(this,qh).properties=r,q(this,Df,TI).call(this,h(this,qh)),r.hasText&&h(this,ga).append(t),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),h(this,ga).append(y)}},TI=function(e){var a;const{div:t,properties:r,ctx:i}=e,{style:o}=t;if(r.canvasWidth!==0&&r.hasText){const{fontFamily:l}=o,{canvasWidth:d,fontSize:c}=r;q(a=vo,Kl,FI).call(a,i,c*h(this,Up),l);const{width:u}=i.measureText(t.textContent);u>0&&o.setProperty("--scale-x",d*h(this,Up)/u)}r.angle!==0&&o.setProperty("--rotate",`${r.angle}deg`)},Kl=new WeakSet,V5=function(e=null){let t=h(this,vy).get(e||(e=""));if(!t){const r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=e,document.body.append(r),t=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),h(this,vy).set(e,t),h(this,n_).set(t,{size:0,family:""})}return t},FI=function(e,t,r){const i=h(this,n_).get(e);t===i.size&&r===i.family||(e.font=`${t}px ${r}`,i.size=t,i.family=r)},SG=function(){if(h(this,uv)!==null)return;const e=document.createElement("div");e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize="1px",e.style.position="absolute",e.textContent="X",document.body.append(e),R(this,uv,e.getBoundingClientRect().height),e.remove()},jG=function(e,t,r){const i=h(this,cv).get(e);if(i)return i;const o=q(this,Kl,V5).call(this,r);o.canvas.width=o.canvas.height=IN,q(this,Kl,FI).call(this,o,IN,e);const a=o.measureText(""),l=a.fontBoundingBoxAscent,d=Math.abs(a.fontBoundingBoxDescent);o.canvas.width=o.canvas.height=0;let c=.8;return l?c=l/(l+d):(Ds.platform.isFirefox&&Bn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."),t.ascent?c=t.ascent:t.descent&&(c=1+t.descent)),h(this,cv).set(e,c),c},N(vo,Kl),N(vo,cv,new Map),N(vo,vy,new Map),N(vo,n_,new WeakMap),N(vo,uv,null),N(vo,hv,new Set);let Qj=vo;const ghe=100;function kG(n={}){typeof n=="string"||n instanceof URL?n={url:n}:(n instanceof ArrayBuffer||ArrayBuffer.isView(n))&&(n={data:n});const e=new DI,{docId:t}=e,r=n.url?wue(n.url):null,i=n.data?Sue(n.data):null,o=n.httpHeaders||null,a=n.withCredentials===!0,l=n.password??null,d=n.range instanceof _G?n.range:null,c=Number.isInteger(n.rangeChunkSize)&&n.rangeChunkSize>0?n.rangeChunkSize:2**16;let u=n.worker instanceof $j?n.worker:null;const f=n.verbosity,p=typeof n.docBaseUrl=="string"&&!iD(n.docBaseUrl)?n.docBaseUrl:null,g=G2(n.cMapUrl),m=n.cMapPacked!==!1,y=G2(n.iccUrl),v=G2(n.standardFontDataUrl),x=G2(n.wasmUrl),w=n.stopAtErrors!==!0,S=Number.isInteger(n.maxImageSize)&&n.maxImageSize>-1?n.maxImageSize:-1,_=typeof n.isOffscreenCanvasSupported=="boolean"?n.isOffscreenCanvasSupported:!zl,b=typeof n.isImageDecoderSupported=="boolean"?n.isImageDecoderSupported:!zl&&(Ds.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(n.canvasMaxAreaInBytes)?n.canvasMaxAreaInBytes:-1,T=typeof n.disableFontFace=="boolean"?n.disableFontFace:zl,F=n.fontExtraProperties===!0,A=n.enableXfa===!0,D=n.ownerDocument||globalThis.document,P=n.disableRange===!0,L=n.disableStream===!0,W=n.disableAutoFetch===!0,O=n.pdfBug===!0,U=n.CanvasFactory||(zl?Due:Cue),M=n.FilterFactory||(zl?Fue:Aue),I=n.BinaryDataFactory||(zl?Eue:SN),H=n.enableHWA===!0,G=n.enableWebGPU===!0?Bue():Promise.resolve(!1),te=n.useWasm!==!1,re=n.pagesMapper||new fhe,me=typeof n.useSystemFonts=="boolean"?n.useSystemFonts:!zl&&!T,J=typeof n.useWorkerFetch=="boolean"?n.useWorkerFetch:!!(I===SN&&g&&m&&v&&x&&rj(g,document.baseURI)&&rj(v,document.baseURI)&&rj(x,document.baseURI)),ne=null;Hce(f);const ye={canvasFactory:new U({ownerDocument:D,enableHWA:H}),filterFactory:new M({docId:t,ownerDocument:D}),binaryDataFactory:J?null:new I({cMapUrl:g,standardFontDataUrl:v,wasmUrl:x})};u||(u=$j.create({verbosity:f,port:Bu.workerPort}),e._worker=u);const ke={docId:t,apiVersion:"5.7.284",data:i,password:l,disableAutoFetch:W,rangeChunkSize:c,docBaseUrl:p,enableXfa:A,evaluatorOptions:{maxImageSize:S,disableFontFace:T,ignoreErrors:w,isOffscreenCanvasSupported:_,isImageDecoderSupported:b,canvasMaxAreaInBytes:C,fontExtraProperties:F,useSystemFonts:me,useWasm:te,useWorkerFetch:J,cMapUrl:g,cMapPacked:m,iccUrl:y,standardFontDataUrl:v,wasmUrl:x,hasGPU:!1}},Ye={ownerDocument:D,pdfBug:O,styleElement:ne,enableHWA:H,loadingParams:{disableAutoFetch:W,enableXfa:A}};return Promise.all([u.promise,G]).then(function([,De]){if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");ke.evaluatorOptions.hasGPU=De;const qe=u.messageHandler.sendWithPromise("GetDocRequest",ke,i?[i.buffer]:null);let ue;if(!i)if(d)ue=new Jue({pdfDataRangeTransport:d,disableRange:P,disableStream:L});else if(r){const Ze=dhe(r);ue=new Ze({url:r,httpHeaders:o,withCredentials:a,rangeChunkSize:c,disableRange:P,disableStream:L})}else throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");return qe.then(Ze=>{if(e.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const ee=new xS(t,Ze,u.port),Z=new yhe(ee,e,ue,Ye,ye,re);e._transport=Z,ee.send("Ready",null)})}).catch(e._capability.reject),e}var qT;const VT=class VT{constructor(){ve(this,"_capability",Promise.withResolvers());ve(this,"_transport",null);ve(this,"_worker",null);ve(this,"docId",`d${Gi(VT,qT)._++}`);ve(this,"destroyed",!1);ve(this,"onPassword",null);ve(this,"onProgress",null)}get promise(){return this._capability.promise}async destroy(){var e,t,r,i;this.destroyed=!0;try{(e=this._worker)!=null&&e.port&&(this._worker._pendingDestroy=!0),await((t=this._transport)==null?void 0:t.destroy())}catch(o){throw(r=this._worker)!=null&&r.port&&delete this._worker._pendingDestroy,o}this._transport=null,(i=this._worker)==null||i.destroy(),this._worker=null}async getData(){return this._transport.getData()}};qT=new WeakMap,N(VT,qT,0);let DI=VT;var fv,wy;class _G{constructor(e,t,r=!1,i=null){N(this,fv,Promise.withResolvers());N(this,wy,null);this.length=e,this.initialData=t,this.progressiveDone=r,this.contentDispositionFilename=i,Object.defineProperty(this,"onDataProgress",{value:()=>{eue("`PDFDataRangeTransport.prototype.onDataProgress` - method was removed, since loading progress is now reported automatically through the `PDFDataTransportStream` class (and related code).")}})}onDataRange(e,t){h(this,wy).call(this,{type:"range",begin:e,chunk:t})}onDataProgressiveRead(e){h(this,fv).promise.then(()=>{h(this,wy).call(this,{type:"progressiveRead",chunk:e})})}onDataProgressiveDone(){h(this,fv).promise.then(()=>{h(this,wy).call(this,{type:"progressiveDone"})})}transportReady(e){R(this,wy,e),h(this,fv).resolve()}requestDataRange(e,t){Hr("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}fv=new WeakMap,wy=new WeakMap;class mhe{constructor(e,t){this._pdfInfo=e,this._transport=t}get pagesMapper(){return this._transport.pagesMapper}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Cn(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getAnnotationsByType(e,t){return this._transport.getAnnotationsByType(e,t)}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}extractPages(e){return this._transport.extractPages(e)}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}getRawData(e){return this._transport.getRawData(e)}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}var Vh,Sy,jy,_S;const V3=class V3{constructor(e,t,r,i,o=!1){N(this,jy);N(this,Vh,!1);N(this,Sy,null);this._pageIndex=e,this._pageInfo=t,this._transport=r,this._stats=o?new uN:null,this._pdfBug=o,this.commonObjs=r.commonObjs,this.objs=new bG,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,R(this,Sy,i),this.imageCoordinates=null}clone(e){const t=new V3(e,this._pageInfo,this._transport,h(this,Sy),this._pdfBug);return t.clonedFromIndex=this.clonedFromIndex??this._pageIndex,this._transport.updatePage(t),t}get pageNumber(){return this._pageIndex+1}set pageNumber(e){this._pageIndex=e-1,this._transport.updatePage(this)}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:r=0,offsetY:i=0,dontFlip:o=!1}={}){return new dC({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:r,offsetY:i,dontFlip:o})}getAnnotations({intent:e="display"}={}){const{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Cn(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var e;return((e=this._transport._htmlForXfa)==null?void 0:e.children[this._pageIndex])||null}render({canvasContext:e,canvas:t=e.canvas,viewport:r,intent:i="display",annotationMode:o=Ru.ENABLE,transform:a=null,background:l=null,optionalContentConfigPromise:d=null,annotationCanvasMap:c=null,pageColors:u=null,printAnnotationStorage:f=null,isEditing:p=!1,recordImages:g=!1,recordOperations:m=!1,operationsFilter:y=null}){var W,O,U;(W=this._stats)==null||W.time("Overall");const v=this._transport.getRenderingIntent(i,o,f,p),{renderingIntent:x,cacheKey:w}=v;R(this,Vh,!1),d||(d=this._transport.getOptionalContentConfig(x));const S=this._intentStates.getOrInsertComputed(w,QB);S.streamReaderCancelTimeout&&(clearTimeout(S.streamReaderCancelTimeout),S.streamReaderCancelTimeout=null);const _=!!(x&Rl.PRINT);S.displayReadyCapability||(S.displayReadyCapability=Promise.withResolvers(),S.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(O=this._stats)==null||O.time("Page Request"),this._pumpOperatorList(v));const b=!!(this._pdfBug&&((U=globalThis.StepperManager)!=null&&U.enabled)),C=!!t&&!this.recordedBBoxes&&(m||b),T=!!t&&!this.imageCoordinates&&g,F=M=>{var I,H,z,G;if(S.renderTasks.delete(P),C){const te=(I=P.gfx)==null?void 0:I.dependencyTracker.take();te&&((H=P.stepper)==null||H.setOperatorBBoxes(te,P.gfx.dependencyTracker.takeDebugMetadata()),m&&(this.recordedBBoxes=te))}T&&!M&&(this.imageCoordinates=(z=P.gfx)==null?void 0:z.imagesTracker.take()),_&&R(this,Vh,!0),q(this,jy,_S).call(this),M?(P.capability.reject(M),this._abortOperatorList({intentState:S,reason:M instanceof Error?M:new Error(M)})):P.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(G=globalThis.Stats)!=null&&G.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let A=null,D=null;(C||T)&&(D=new hue(t,S.operatorList.length)),C&&(A=new fue(D,b));const P=new PI({callback:F,params:{canvas:t,canvasContext:e,dependencyTracker:A??D,imagesTracker:T?new xI(t):null,viewport:r,transform:a,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:S.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!_,pdfBug:this._pdfBug,pageColors:u,enableHWA:this._transport.enableHWA,operationsFilter:y});(S.renderTasks||(S.renderTasks=new Set)).add(P);const L=P.task;return Promise.all([S.displayReadyCapability.promise,d]).then(([M,I])=>{var H;if(this.destroyed){F();return}if((H=this._stats)==null||H.time("Rendering"),!(I.renderingIntent&x))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");P.initializeGraphics({transparency:M,optionalContentConfig:I}),P.operatorListChanged()}).catch(F),L}getOperatorList({intent:e="display",annotationMode:t=Ru.ENABLE,printAnnotationStorage:r=null,isEditing:i=!1}={}){var c;function o(){l.operatorList.lastChunk&&(l.opListReadCapability.resolve(l.operatorList),l.renderTasks.delete(d))}const a=this._transport.getRenderingIntent(e,t,r,i,!0),l=this._intentStates.getOrInsertComputed(a.cacheKey,QB);let d;return l.opListReadCapability||(d=Object.create(null),d.operatorListChanged=o,l.opListReadCapability=Promise.withResolvers(),(l.renderTasks||(l.renderTasks=new Set)).add(d),l.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(c=this._stats)==null||c.time("Page Request"),this._pumpOperatorList(a)),l.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageId:h(this,Sy).getPageId(this._pageIndex+1)-1,pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(i){return i.items.length}})}async getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(i=>Kj.textContent(i));const t=this.streamTextContent(e),r={items:[],styles:Object.create(null),lang:null};for await(const i of t)r.lang??(r.lang=i.lang),Object.assign(r.styles,i.styles),r.items.push(...i.items);return r}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const e=[];for(const t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:new Error("Page was destroyed."),force:!0}),!t.opListReadCapability)for(const r of t.renderTasks)e.push(r.completed),r.cancel();return this.objs.clear(),R(this,Vh,!1),Promise.all(e)}cleanup(e=!1){R(this,Vh,!0);const t=q(this,jy,_S).call(this);return e&&t&&this._stats&&(this._stats=new uN),t}_startRenderPage(e,t){var i,o;const r=this._intentStates.get(t);r&&((i=this._stats)==null||i.timeEnd("Page Request"),(o=r.displayReadyCapability)==null||o.resolve(e))}_renderPageChunk(e,t){for(let r=0,i=e.length;r{d.read().then(({value:f,done:p})=>{if(p){c.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(f,c),u())},f=>{if(c.streamReader=null,!this._transport.destroyed){if(c.operatorList){c.operatorList.lastChunk=!0;for(const p of c.renderTasks)p.operatorListChanged();q(this,jy,_S).call(this)}if(c.displayReadyCapability)c.displayReadyCapability.reject(f);else if(c.opListReadCapability)c.opListReadCapability.reject(f);else throw f}})};u()}_abortOperatorList({intentState:e,reason:t,force:r=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&(clearTimeout(e.streamReaderCancelTimeout),e.streamReaderCancelTimeout=null),!r){if(e.renderTasks.size>0)return;if(t instanceof P3){let i=ghe;t.extraDelay>0&&t.extraDelay<1e3&&(i+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},i);return}}if(e.streamReader.cancel(new Ng(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(const[i,o]of this._intentStates)if(o===e){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}};Vh=new WeakMap,Sy=new WeakMap,jy=new WeakSet,_S=function(){if(!h(this,Vh)||this.destroyed)return!1;for(const{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),R(this,Vh,!1),!0};let EI=V3;var Hp,gc,Gh,ky,GT,_y,Cy,ka,G5,CG,AG,CS,pv,K5;const ss=class ss{constructor({name:e=null,port:t=null,verbosity:r=qce()}={}){N(this,ka);N(this,Hp,Promise.withResolvers());N(this,gc,null);N(this,Gh,null);N(this,ky,null);if(this.name=e,this.destroyed=!1,this.verbosity=r,t){if(h(ss,Cy).has(t))throw new Error("Cannot use more than one PDFWorker per port.");h(ss,Cy).set(t,this),q(this,ka,CG).call(this,t)}else q(this,ka,AG).call(this)}get promise(){return h(this,Hp).promise}get port(){return h(this,Gh)}get messageHandler(){return h(this,gc)}destroy(){var e,t;this.destroyed=!0,(e=h(this,ky))==null||e.terminate(),R(this,ky,null),h(ss,Cy).delete(h(this,Gh)),R(this,Gh,null),(t=h(this,gc))==null||t.destroy(),R(this,gc,null)}static create(e){const t=h(this,Cy).get(e==null?void 0:e.port);if(t){if(t._pendingDestroy)throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return t}return new ss(e)}static get workerSrc(){if(Bu.workerSrc)return Bu.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Cn(this,"_setupFakeWorkerGlobal",(async()=>h(this,pv,K5)?h(this,pv,K5):(await import(this.workerSrc)).WorkerMessageHandler)())}};Hp=new WeakMap,gc=new WeakMap,Gh=new WeakMap,ky=new WeakMap,GT=new WeakMap,_y=new WeakMap,Cy=new WeakMap,ka=new WeakSet,G5=function(){h(this,Hp).resolve(),h(this,gc).send("configure",{verbosity:this.verbosity})},CG=function(e){R(this,Gh,e),R(this,gc,new xS("main","worker",e)),h(this,gc).on("ready",()=>{}),q(this,ka,G5).call(this)},AG=function(){if(h(ss,_y)||h(ss,pv,K5)){q(this,ka,CS).call(this);return}let{workerSrc:e}=ss;try{ss._isSameOrigin(window.location,e)||(e=ss._createCDNWrapper(new URL(e,window.location).href));const t=new Worker(e,{type:"module"}),r=new xS("main","worker",t),i=()=>{o.abort(),r.destroy(),t.terminate(),this.destroyed?h(this,Hp).reject(new Error("Worker was destroyed")):q(this,ka,CS).call(this)},o=new AbortController;t.addEventListener("error",()=>{h(this,ky)||i()},{signal:o.signal}),r.on("test",l=>{if(o.abort(),this.destroyed||!l){i();return}R(this,gc,r),R(this,Gh,t),R(this,ky,t),q(this,ka,G5).call(this)}),r.on("ready",l=>{if(o.abort(),this.destroyed){i();return}try{a()}catch{q(this,ka,CS).call(this)}});const a=()=>{const l=new Uint8Array;r.send("test",l,[l.buffer])};a();return}catch{nD("The worker has been disabled.")}q(this,ka,CS).call(this)},CS=function(){h(ss,_y)||(Bn("Setting up fake worker."),R(ss,_y,!0)),ss._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){h(this,Hp).reject(new Error("Worker was destroyed"));return}const t=new _ue;R(this,Gh,t);const r=`fake${Gi(ss,GT)._++}`,i=new xS(r+"_worker",r,t);e.setup(i,t),R(this,gc,new xS(r,r+"_worker",t)),q(this,ka,G5).call(this)}).catch(e=>{h(this,Hp).reject(new Error(`Setting up fake worker failed: "${e.message}".`))})},pv=new WeakSet,K5=function(){var e;try{return((e=globalThis.pdfjsWorker)==null?void 0:e.WorkerMessageHandler)||null}catch{return null}},N(ss,pv),N(ss,GT,0),N(ss,_y,!1),N(ss,Cy,new WeakMap),zl&&(R(ss,_y,!0),Bu.workerSrc||(Bu.workerSrc="./pdf.worker.mjs")),ss._isSameOrigin=(e,t)=>{const r=URL.parse(e);if(!(r!=null&&r.origin)||r.origin==="null")return!1;const i=new URL(t,r);return r.origin===i.origin},ss._createCDNWrapper=e=>{const t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};let $j=ss;var bl,Ay,Kh,mc,Ty,gv,Xh,Ac,AS,X5;class yhe{constructor(e,t,r,i,o,a){N(this,Ac);ve(this,"downloadInfoCapability",Promise.withResolvers());N(this,bl,null);N(this,Ay,new Map);N(this,Kh,null);N(this,mc,new Map);N(this,Ty,new Map);N(this,gv,new Map);N(this,Xh,null);this.messageHandler=e,this.loadingTask=t,R(this,Kh,r),this.commonObjs=new bG,this.fontLoader=new pue({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.enableHWA=i.enableHWA,this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=o.canvasFactory,this.filterFactory=o.filterFactory,this.binaryDataFactory=o.binaryDataFactory,this.pagesMapper=a,this.destroyed=!1,this.destroyCapability=null,this.setupMessageHandler()}updatePage(e){const{_pageIndex:t}=e;h(this,mc).set(t,e),h(this,Ty).set(t,Promise.resolve(e))}get annotationStorage(){return Cn(this,"annotationStorage",new I3)}getRenderingIntent(e,t=Ru.ENABLE,r=null,i=!1,o=!1){let a=Rl.DISPLAY,l=Xj;switch(e){case"any":a=Rl.ANY;break;case"display":break;case"print":a=Rl.PRINT;break;default:Bn(`getRenderingIntent - invalid intent: ${e}`)}const d=a&Rl.PRINT&&r instanceof GV?r:this.annotationStorage;switch(t){case Ru.DISABLE:a+=Rl.ANNOTATIONS_DISABLE;break;case Ru.ENABLE:break;case Ru.ENABLE_FORMS:a+=Rl.ANNOTATIONS_FORMS;break;case Ru.ENABLE_STORAGE:a+=Rl.ANNOTATIONS_STORAGE,l=d.serializable;break;default:Bn(`getRenderingIntent - invalid annotationMode: ${t}`)}i&&(a+=Rl.IS_EDITING),o&&(a+=Rl.OPLIST);const{ids:c,hash:u}=d.modifiedIds,f=[a,l.hash,u];return{renderingIntent:a,cacheKey:f.join("_"),annotationStorageSerializable:l,modifiedIds:c}}destroy(){var r;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(r=h(this,Xh))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const e=[];for(const i of h(this,mc).values())e.push(i._destroy());h(this,mc).clear(),h(this,Ty).clear(),h(this,gv).clear(),Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const t=this.messageHandler.sendWithPromise("Terminate",null);return e.push(t),Promise.all(e).then(()=>{var i,o;this.commonObjs.clear(),this.fontLoader.clear(),h(this,Ay).clear(),this.filterFactory.destroy(),Qj.cleanup(),(i=h(this,Kh))==null||i.cancelAllRequests(new Ng("Worker was terminated.")),(o=this.messageHandler)==null||o.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:e,loadingTask:t}=this;e.on("GetReader",(r,i)=>{Zi(h(this,Kh),"GetReader - no `BasePDFStream` instance available."),R(this,bl,h(this,Kh).getFullReader()),h(this,bl).onProgress=o=>q(this,Ac,X5).call(this,o),i.onPull=()=>{h(this,bl).read().then(function({value:o,done:a}){if(a){i.close();return}Zi(o instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(o),1,[o])}).catch(o=>{i.error(o)})},i.onCancel=o=>{h(this,bl).cancel(o),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),e.on("ReaderHeadersReady",async r=>{await h(this,bl).headersReady;const{isStreamingSupported:i,isRangeSupported:o,contentLength:a}=h(this,bl);return i&&o&&(h(this,bl).onProgress=null),{isStreamingSupported:i,isRangeSupported:o,contentLength:a}}),e.on("GetRangeReader",(r,i)=>{Zi(h(this,Kh),"GetRangeReader - no `BasePDFStream` instance available.");const o=h(this,Kh).getRangeReader(r.begin,r.end);if(!o){i.close();return}i.onPull=()=>{o.read().then(function({value:a,done:l}){if(l){i.close();return}Zi(a instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(a),1,[a])}).catch(a=>{i.error(a)})},i.onCancel=a=>{o.cancel(a),i.ready.catch(l=>{if(!this.destroyed)throw l})}}),e.on("GetDoc",({pdfInfo:r})=>{this.pagesMapper.pagesNumber=r.numPages,this._numPages=r.numPages,this._htmlForXfa=r.htmlForXfa,delete r.htmlForXfa,t._capability.resolve(new mhe(r,this))}),e.on("DocException",r=>{t._capability.reject(La(r))}),e.on("PasswordRequest",r=>{R(this,Xh,Promise.withResolvers());try{if(!t.onPassword)throw La(r);const i=o=>{o instanceof Error?h(this,Xh).reject(o):h(this,Xh).resolve({password:o})};t.onPassword(i,r.code)}catch(i){h(this,Xh).reject(i)}return h(this,Xh).promise}),e.on("DataLoaded",r=>{q(this,Ac,X5).call(this,{loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),e.on("StartRenderPage",r=>{if(this.destroyed)return;h(this,mc).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),e.on("commonobj",([r,i,o])=>{var a;if(this.destroyed||this.commonObjs.has(r))return null;switch(i){case"Font":if("error"in o){const p=o.error;Bn(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const l=new xue(o),d=this._params.pdfBug&&((a=globalThis.FontInspector)!=null&&a.enabled)?(p,g)=>globalThis.FontInspector.fontAdded(p,g):null,c=new gue(l,d,o.charProcOperatorList,o.extra);this.fontLoader.bind(c).catch(()=>e.sendWithPromise("FontFallback",{id:r})).finally(()=>{c.fontExtraProperties||c.clearData(),this.commonObjs.resolve(r,c)});break;case"CopyLocalImage":const{imageRef:u}=o;Zi(u,"The imageRef must be defined.");for(const p of h(this,mc).values())for(const[,g]of p.objs){if((g==null?void 0:g.ref)!==u)continue;if(!g.dataLen)return null;const m=structuredClone(g);return this.commonObjs.resolve(r,m),g.dataLen}break;case"FontPath":this.commonObjs.resolve(r,new vue(o));break;case"Image":this.commonObjs.resolve(r,o);break;case"Pattern":const f=new bue(o);this.commonObjs.resolve(r,f.getIR());break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),e.on("obj",([r,i,o,a])=>{var d;if(this.destroyed)return;const l=h(this,mc).get(i);if(!l.objs.has(r)){if(l._intentStates.size===0){(d=a==null?void 0:a.bitmap)==null||d.close();return}switch(o){case"Image":case"Pattern":l.objs.resolve(r,a);break;default:throw new Error(`Got unknown object type ${o}`)}}}),e.on("DocProgress",r=>{this.destroyed||q(this,Ac,X5).call(this,r)}),e.on("FetchBinaryData",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.binaryDataFactory)throw new Error("`BinaryDataFactory` not initialized, see the `useWorkerFetch` parameter.");return this.binaryDataFactory.fetch(r)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var r;this.annotationStorage.size<=0&&Bn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:((r=h(this,bl))==null?void 0:r.filename)??null},t).finally(()=>{this.annotationStorage.resetModified()})}extractPages(e){const t={pageInfos:e};let r;if(this.annotationStorage.size>0){const{map:i,transfer:o}=this.annotationStorage.serializable;t.annotationStorage=i,r=o}return this.messageHandler.sendWithPromise("ExtractPages",t,r).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this.pagesMapper.pagesNumber)return Promise.reject(new Error("Invalid page request."));const t=e-1,r=this.pagesMapper.getPageId(e)-1,i=h(this,Ty).get(t);if(i)return i;const o=this.messageHandler.sendWithPromise("GetPage",{pageIndex:r}).then(a=>{if(this.destroyed)throw new Error("Transport destroyed");a.refStr&&h(this,gv).set(a.refStr,r);const l=new EI(t,a,this,this.pagesMapper,this._params.pdfBug);return h(this,mc).set(t,l),l});return h(this,Ty).set(t,o),o}async getPageIndex(e){if(!vI(e))throw new Error("Invalid pageIndex request.");const t=await this.messageHandler.sendWithPromise("GetPageIndex",{num:e.num,gen:e.gen}),r=this.pagesMapper.getPageNumber(t+1);if(r===0)throw new Error("GetPageIndex: page has been removed.");return r-1}getAnnotations(e,t){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:this.pagesMapper.getPageId(e+1)-1,intent:t})}getFieldObjects(){return q(this,Ac,AS).call(this,"GetFieldObjects")}hasJSActions(){return q(this,Ac,AS).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(e){return typeof e!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:e})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getAnnotationsByType(e,t){return this.messageHandler.sendWithPromise("GetAnnotationsByType",{types:e,pageIndexesToSkip:t})}getDocJSActions(){return q(this,Ac,AS).call(this,"GetDocJSActions")}getPageJSActions(e){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getStructTree(e){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:this.pagesMapper.getPageId(e+1)-1})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(e){return q(this,Ac,AS).call(this,"GetOptionalContentConfig").then(t=>new hhe(t,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const e="GetMetadata";return h(this,Ay).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,null).then(t=>{var r,i;return{info:t[0],metadata:t[1]?new che(t[1]):null,contentDispositionFilename:((r=h(this,bl))==null?void 0:r.filename)??null,contentLength:((i=h(this,bl))==null?void 0:i.contentLength)??null,hasStructTree:t[2]}}))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}getRawData(e){return this.messageHandler.sendWithPromise("GetRawData",e)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of h(this,mc).values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),h(this,Ay).clear(),this.filterFactory.destroy(!0),Qj.cleanup()}}cachedPageNumber(e){if(!vI(e))return null;const t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,r=h(this,gv).get(t);if(r>=0){const i=this.pagesMapper.getPageNumber(r+1);if(i!==0)return i}return null}}bl=new WeakMap,Ay=new WeakMap,Kh=new WeakMap,mc=new WeakMap,Ty=new WeakMap,gv=new WeakMap,Xh=new WeakMap,Ac=new WeakSet,AS=function(e,t=null){return h(this,Ay).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))},X5=function({loaded:e,total:t}){var r,i;(i=(r=this.loadingTask).onProgress)==null||i.call(r,{loaded:e,total:t,percent:t?Bi(Math.round(e/t*100),0,100):NaN})};class xhe{constructor(e){ve(this,"_internalRenderTask",null);ve(this,"onContinue",null);ve(this,"onError",null);this._internalRenderTask=e}get promise(){return this._internalRenderTask.capability.promise}cancel(e=0){this._internalRenderTask.cancel(null,e)}get separateAnnots(){const{separateAnnots:e}=this._internalRenderTask.operatorList;if(!e)return!1;const{annotationCanvasMap:t}=this._internalRenderTask;return e.form||e.canvas&&(t==null?void 0:t.size)>0}get imageCoordinates(){return this._internalRenderTask.imageCoordinates||null}}var qp,Fy;const fm=class fm{constructor({callback:e,params:t,objs:r,commonObjs:i,annotationCanvasMap:o,operatorList:a,pageIndex:l,canvasFactory:d,filterFactory:c,useRequestAnimationFrame:u=!1,pdfBug:f=!1,pageColors:p=null,enableHWA:g=!1,operationsFilter:m=null}){N(this,qp,null);this.callback=e,this.params=t,this.objs=r,this.commonObjs=i,this.annotationCanvasMap=o,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=l,this.canvasFactory=d,this.filterFactory=c,this._pdfBug=f,this.pageColors=p,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new xhe(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvas,this._canvasContext=t.canvas?null:t.canvasContext,this._enableHWA=g,this._dependencyTracker=t.dependencyTracker,this._imagesTracker=t.imagesTracker,this._operationsFilter=m}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:e=!1,optionalContentConfig:t}){var c,u;if(this.cancelled)return;if(this._canvas){if(h(fm,Fy).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");h(fm,Fy).add(this._canvas)}this._pdfBug&&((c=globalThis.StepperManager)!=null&&c.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{viewport:r,transform:i,background:o,dependencyTracker:a,imagesTracker:l}=this.params,d=this._canvasContext||this._canvas.getContext("2d",{alpha:!1,willReadFrequently:!this._enableHWA});this.gfx=new db(d,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:t},this.annotationCanvasMap,this.pageColors,a,l),this.gfx.beginDrawing({transform:i,viewport:r,transparency:e,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,(u=this.graphicsReadyCallback)==null||u.call(this)}cancel(e=null,t=0){var r,i,o;this.running=!1,this.cancelled=!0,(r=this.gfx)==null||r.endDrawing(),h(this,qp)&&(window.cancelAnimationFrame(h(this,qp)),R(this,qp,null)),h(fm,Fy).delete(this._canvas),e||(e=new P3(`Rendering cancelled, page ${this._pageIndex+1}`,t)),this.callback(e),(o=(i=this.task).onError)==null||o.call(i,e)}operatorListChanged(){var e,t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(e=this.gfx.dependencyTracker)==null||e.growOperationsCount(this.operatorList.fnArray.length),(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?R(this,qp,window.requestAnimationFrame(()=>{R(this,qp,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper,this._operationsFilter),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),h(fm,Fy).delete(this._canvas),this.callback())))}};qp=new WeakMap,Fy=new WeakMap,N(fm,Fy,new WeakSet);let PI=fm;const bhe="5.7.284",vhe="7e5b36c2d";var vl,Dy,mv,Is,r_,yv,Yh,i_,Vp,yc,s_,di,RI,BI,II,lm,TG,Jf;const Na=class Na{constructor({editor:e=null,uiManager:t=null}){N(this,di);N(this,vl,null);N(this,Dy,null);N(this,mv);N(this,Is,null);N(this,r_,!1);N(this,yv,!1);N(this,Yh,null);N(this,i_);N(this,Vp,null);N(this,yc,null);var r,i;e?(R(this,yv,!1),R(this,Yh,e)):R(this,yv,!0),R(this,yc,(e==null?void 0:e._uiManager)||t),R(this,i_,h(this,yc)._eventBus),R(this,mv,((r=e==null?void 0:e.color)==null?void 0:r.toUpperCase())||((i=h(this,yc))==null?void 0:i.highlightColors.values().next().value)||"#FFFF98"),h(Na,s_)||R(Na,s_,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return Cn(this,"_keyboardManager",new uC([[["Escape","mac+Escape"],Na.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],Na.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],Na.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],Na.prototype._moveToPrevious],[["Home","mac+Home"],Na.prototype._moveToBeginning],[["End","mac+End"],Na.prototype._moveToEnd]]))}renderButton(){const e=R(this,vl,document.createElement("button"));e.className="colorPicker",e.tabIndex="0",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),e.ariaHasPopup="true",h(this,Yh)&&(e.ariaControls=`${h(this,Yh).id}_colorpicker_dropdown`);const t=h(this,yc)._signal;e.addEventListener("click",q(this,di,lm).bind(this),{signal:t}),e.addEventListener("keydown",q(this,di,II).bind(this),{signal:t});const r=R(this,Dy,document.createElement("span"));return r.className="swatch",r.ariaHidden="true",r.style.backgroundColor=h(this,mv),e.append(r),e}renderMainDropdown(){const e=R(this,Is,q(this,di,RI).call(this));return e.ariaOrientation="horizontal",e.ariaLabelledBy="highlightColorPickerLabel",e}_colorSelectFromKeyboard(e){if(e.target===h(this,vl)){q(this,di,lm).call(this,e);return}const t=e.target.getAttribute("data-color");t&&q(this,di,BI).call(this,t,e)}_moveToNext(e){var t,r;if(!h(this,di,Jf)){q(this,di,lm).call(this,e);return}if(e.target===h(this,vl)){(t=h(this,Is).firstElementChild)==null||t.focus();return}(r=e.target.nextSibling)==null||r.focus()}_moveToPrevious(e){var t,r;if(e.target===((t=h(this,Is))==null?void 0:t.firstElementChild)||e.target===h(this,vl)){h(this,di,Jf)&&this._hideDropdownFromKeyboard();return}h(this,di,Jf)||q(this,di,lm).call(this,e),(r=e.target.previousSibling)==null||r.focus()}_moveToBeginning(e){var t;if(!h(this,di,Jf)){q(this,di,lm).call(this,e);return}(t=h(this,Is).firstElementChild)==null||t.focus()}_moveToEnd(e){var t;if(!h(this,di,Jf)){q(this,di,lm).call(this,e);return}(t=h(this,Is).lastElementChild)==null||t.focus()}hideDropdown(){var e,t;(e=h(this,Is))==null||e.classList.add("hidden"),h(this,vl).ariaExpanded="false",(t=h(this,Vp))==null||t.abort(),R(this,Vp,null)}_hideDropdownFromKeyboard(){var e;if(!h(this,yv)){if(!h(this,di,Jf)){(e=h(this,Yh))==null||e.unselect();return}this.hideDropdown(),h(this,vl).focus({preventScroll:!0,focusVisible:h(this,r_)})}}updateColor(e){if(h(this,Dy)&&(h(this,Dy).style.backgroundColor=e),!h(this,Is))return;const t=h(this,yc).highlightColors.values();for(const r of h(this,Is).children)r.ariaSelected=t.next().value===e.toUpperCase()}destroy(){var e,t;(e=h(this,vl))==null||e.remove(),R(this,vl,null),R(this,Dy,null),(t=h(this,Is))==null||t.remove(),R(this,Is,null)}};vl=new WeakMap,Dy=new WeakMap,mv=new WeakMap,Is=new WeakMap,r_=new WeakMap,yv=new WeakMap,Yh=new WeakMap,i_=new WeakMap,Vp=new WeakMap,yc=new WeakMap,s_=new WeakMap,di=new WeakSet,RI=function(){const e=document.createElement("div"),t=h(this,yc)._signal;e.addEventListener("contextmenu",Hd,{signal:t}),e.className="dropdown",e.role="listbox",e.ariaMultiSelectable="false",e.ariaOrientation="vertical",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown"),h(this,Yh)&&(e.id=`${h(this,Yh).id}_colorpicker_dropdown`);for(const[r,i]of h(this,yc).highlightColors){const o=document.createElement("button");o.tabIndex="0",o.role="option",o.setAttribute("data-color",i),o.title=r,o.setAttribute("data-l10n-id",h(Na,s_)[r]);const a=document.createElement("span");o.append(a),a.className="swatch",a.style.backgroundColor=i,o.ariaSelected=i===h(this,mv),o.addEventListener("click",q(this,di,BI).bind(this,i),{signal:t}),e.append(o)}return e.addEventListener("keydown",q(this,di,II).bind(this),{signal:t}),e},BI=function(e,t){t.stopPropagation(),h(this,i_).dispatch("switchannotationeditorparams",{source:this,type:Wn.HIGHLIGHT_COLOR,value:e}),this.updateColor(e)},II=function(e){Na._keyboardManager.exec(this,e)},lm=function(e){if(h(this,di,Jf)){this.hideDropdown();return}if(R(this,r_,e.detail===0),h(this,Vp)||(R(this,Vp,new AbortController),window.addEventListener("pointerdown",q(this,di,TG).bind(this),{signal:h(this,yc).combinedSignal(h(this,Vp))})),h(this,vl).ariaExpanded="true",h(this,Is)){h(this,Is).classList.remove("hidden");return}const t=R(this,Is,q(this,di,RI).call(this));h(this,vl).append(t)},TG=function(e){var t;(t=h(this,Is))!=null&&t.contains(e.target)||this.hideDropdown()},Jf=function(){return h(this,Is)&&!h(this,Is).classList.contains("hidden")},N(Na,s_,null);let ST=Na;var wl,xv,Ey,Qh,o_;const pm=class pm{constructor(e){N(this,wl,null);N(this,xv,!1);N(this,Ey,null);N(this,Qh,null);R(this,Ey,e),R(this,Qh,e._uiManager),h(pm,o_)||R(pm,o_,Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"}))}renderButton(){if(h(this,wl))return h(this,wl);const{editorType:e,colorType:t,colorAndOpacityType:r,opacityType:i,color:o,opacity:a}=h(this,Ey),l=R(this,xv,Ds.isAlphaColorInputSupported&&i!==void 0),d=R(this,wl,document.createElement("input"));if(d.type="color",l){d.setAttribute("alpha","");const c=yt.hexNums[Math.round((a??1)*255)];d.value=(o||"#000000")+c}else d.value=o||"#000000";return d.className="basicColorPicker",d.tabIndex=0,d.setAttribute("data-l10n-id",h(pm,o_)[e]),d.addEventListener("input",()=>{if(l){const c=B3(d.value);if(!c)return;const[u,f,p,g]=c,m=yt.makeHexColor(u,f,p);r!==void 0?h(this,Qh).updateParams(r,{color:m,opacity:g}):(h(this,Qh).updateParams(t,m),h(this,Qh).updateParams(i,g))}else h(this,Qh).updateParams(t,d.value)},{signal:h(this,Qh)._signal}),d}update(e){if(h(this,wl))if(h(this,xv)){const t=yt.hexNums[Math.round(h(this,Ey).opacity*255)];h(this,wl).value=e+t}else h(this,wl).value=e}updateOpacity(e){if(!h(this,wl)||!h(this,xv))return;const t=yt.hexNums[Math.round(e*255)];h(this,wl).value=h(this,Ey).color+t}destroy(){var e;(e=h(this,wl))==null||e.remove(),R(this,wl,null)}hideDropdown(){}};wl=new WeakMap,xv=new WeakMap,Ey=new WeakMap,Qh=new WeakMap,o_=new WeakMap,N(pm,o_,null);let jT=pm;function MN(n){return Math.floor(Bi(n,0,1)*255).toString(16).padStart(2,"0")}function Vw(n){return Bi(n,0,1)*255}class zN{static CMYK_G([e,t,r,i]){return["G",1-Math.min(1,.3*e+.59*r+.11*t+i)]}static G_CMYK([e]){return["CMYK",0,0,0,1-e]}static G_RGB([e]){return["RGB",e,e,e]}static G_rgb([e]){return e=Vw(e),[e,e,e]}static G_HTML([e]){const t=MN(e);return`#${t}${t}${t}`}static RGB_G([e,t,r]){return["G",.3*e+.59*t+.11*r]}static RGB_rgb(e){return e.map(Vw)}static RGB_HTML(e){return`#${e.map(MN).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([e,t,r,i]){return["RGB",1-Math.min(1,e+i),1-Math.min(1,r+i),1-Math.min(1,t+i)]}static CMYK_rgb([e,t,r,i]){return[Vw(1-Math.min(1,e+i)),Vw(1-Math.min(1,r+i)),Vw(1-Math.min(1,t+i))]}static CMYK_HTML(e){const t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,r]){const i=1-e,o=1-t,a=1-r,l=Math.min(i,o,a);return["CMYK",i,o,a,l]}}class whe{create(e,t,r=!1){if(e<=0||t<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),r||(i.setAttribute("width",`${e}px`),i.setAttribute("height",`${t}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${e} ${t}`),i}createElement(e){if(typeof e!="string")throw new Error("Invalid SVG element type");return this._createSVG(e)}_createSVG(e){Hr("Abstract method `_createSVG` called.")}}class kT extends whe{_createSVG(e){return document.createElementNS(hh,e)}}const She=9,C0=new WeakSet,jhe=new Date().getTimezoneOffset()*60*1e3;class HP{static create(e){switch(e.data.annotationType){case Cs.LINK:return new z3(e);case Cs.TEXT:return new _he(e);case Cs.WIDGET:switch(e.data.fieldType){case"Tx":return new Che(e);case"Btn":return e.data.radioButton?new EG(e):e.data.checkBox?new The(e):new Fhe(e);case"Ch":return new Dhe(e);case"Sig":return new Ahe(e)}return new U0(e);case Cs.POPUP:return new zI(e);case Cs.FREETEXT:return new MG(e);case Cs.LINE:return new Phe(e);case Cs.SQUARE:return new Rhe(e);case Cs.CIRCLE:return new Bhe(e);case Cs.POLYLINE:return new zG(e);case Cs.CARET:return new Mhe(e);case Cs.INK:return new O3(e);case Cs.POLYGON:return new Ihe(e);case Cs.HIGHLIGHT:return new OG(e);case Cs.UNDERLINE:return new zhe(e);case Cs.SQUIGGLY:return new Ohe(e);case Cs.STRIKEOUT:return new Lhe(e);case Cs.STAMP:return new LG(e);case Cs.FILEATTACHMENT:return new Nhe(e);default:return new ts(e)}}}var Py,bv,vd,a_,MI;const G3=class G3{constructor(e,{isRenderable:t=!1,ignoreBorder:r=!1,createQuadrilaterals:i=!1}={}){N(this,a_);N(this,Py,null);N(this,bv,!1);N(this,vd,null);this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableComment=e.enableComment,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,this.hasOwnCommentButton=!1,t&&(this.contentElement=this.container=this._createContainer(r)),i&&this._createQuadrilaterals()}static _hasPopupData({contentsObj:e,richText:t}){return!!(e!=null&&e.str||t!=null&&t.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return G3._hasPopupData(this.data)||this.enableComment&&!!this.commentText}get commentData(){var r;const{data:e}=this,t=(r=this.annotationStorage)==null?void 0:r.getEditor(e.id);return t?t.getData():e}get hasCommentButton(){return this.enableComment&&this.hasPopupElement}get commentButtonPosition(){var l;const e=(l=this.annotationStorage)==null?void 0:l.getEditor(this.data.id);if(e)return e.commentButtonPositionInPage;const{quadPoints:t,inkLists:r,rect:i}=this.data;let o=-1/0,a=-1/0;if((t==null?void 0:t.length)>=8){for(let d=0;da?(a=t[d+1],o=t[d+2]):t[d+1]===a&&(o=Math.max(o,t[d+2]));return[o,a]}if((r==null?void 0:r.length)>=1){for(const d of r)for(let c=0,u=d.length;ca?(a=d[c+1],o=d[c]):d[c+1]===a&&(o=Math.max(o,d[c]));if(o!==1/0)return[o,a]}return i?[i[2],i[3]]:null}_normalizePoint(e){const{page:{view:t},viewport:{rawDims:{pageWidth:r,pageHeight:i,pageX:o,pageY:a}}}=this.parent;return e[1]=t[3]-e[1]+t[1],e[0]=100*(e[0]-o)/r,e[1]=100*(e[1]-a)/i,e}get commentText(){var t,r,i;const{data:e}=this;return((r=(t=this.annotationStorage.getRawValue(`${Gj}${e.id}`))==null?void 0:t.popup)==null?void 0:r.contents)||((i=e.contentsObj)==null?void 0:i.str)||""}set commentText(e){const{data:t}=this,r={deleted:!e,contents:e||""};this.annotationStorage.updateEditor(t.id,{popup:r})||this.annotationStorage.setValue(`${Gj}${t.id}`,{id:t.id,annotationType:t.annotationType,page:this.parent.page,popup:r,popupRef:t.popupRef,modificationDate:new Date}),e||this.removePopup()}removePopup(){var e,t;(t=((e=h(this,vd))==null?void 0:e.popup)||this.popup)==null||t.remove(),R(this,vd,this.popup=null)}updateEdited(e){var o;if(!this.container)return;e.rect&&(h(this,Py)||R(this,Py,{rect:this.data.rect.slice(0)}));const{rect:t,popup:r}=e;t&&q(this,a_,MI).call(this,t);let i=((o=h(this,vd))==null?void 0:o.popup)||this.popup;!i&&(r!=null&&r.text)&&(this._createPopup(r),i=h(this,vd).popup),i&&(i.updateEdited(e),r!=null&&r.deleted&&(i.remove(),R(this,vd,null),this.popup=null))}resetEdited(){var e;h(this,Py)&&(q(this,a_,MI).call(this,h(this,Py).rect),(e=h(this,vd))==null||e.popup.resetEdited(),R(this,Py,null))}_createContainer(e){const{data:t,parent:{page:r,viewport:i}}=this,o=document.createElement("section");o.setAttribute("data-annotation-id",t.id),!(this instanceof U0)&&!(this instanceof z3)&&(o.tabIndex=0);const{style:a}=o;if(a.zIndex=this.parent.zIndex,this.parent.zIndex+=2,t.alternativeText&&(o.title=t.alternativeText),t.noRotate&&o.classList.add("norotate"),!t.rect||this instanceof zI){const{rotation:y}=t;return!t.hasOwnCanvas&&y!==0&&this.setRotation(y,o),o}const{width:l,height:d}=this;if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;const y=t.borderStyle.horizontalCornerRadius,v=t.borderStyle.verticalCornerRadius;if(y>0||v>0){const w=`calc(${y}px * var(--total-scale-factor)) / calc(${v}px * var(--total-scale-factor))`;a.borderRadius=w}else if(this instanceof EG){const w=`calc(${l}px * var(--total-scale-factor)) / calc(${d}px * var(--total-scale-factor))`;a.borderRadius=w}switch(t.borderStyle.style){case Sx.SOLID:a.borderStyle="solid";break;case Sx.DASHED:a.borderStyle="dashed";break;case Sx.BEVELED:Bn("Unimplemented border style: beveled");break;case Sx.INSET:Bn("Unimplemented border style: inset");break;case Sx.UNDERLINE:a.borderBottomStyle="solid";break}const x=t.borderColor||null;x?(R(this,bv,!0),a.borderColor=yt.makeHexColor(...x)):a.borderWidth=0}const c=yt.normalizeRect([t.rect[0],r.view[3]-t.rect[1]+r.view[1],t.rect[2],r.view[3]-t.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:f,pageX:p,pageY:g}=i.rawDims;a.left=`${100*(c[0]-p)/u}%`,a.top=`${100*(c[1]-g)/f}%`;const{rotation:m}=t;return t.hasOwnCanvas||m===0?(a.width=`${100*l/u}%`,a.height=`${100*d/f}%`):this.setRotation(m,o),o}setRotation(e,t=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:i}=this.parent.viewport.rawDims;let{width:o,height:a}=this;e%180!==0&&([o,a]=[a,o]),t.style.width=`${100*o/r}%`,t.style.height=`${100*a/i}%`,t.setAttribute("data-main-rotation",(360-e)%360)}get _commonActions(){const e=(t,r,i)=>{const o=i.detail[t],a=o[0],l=o.slice(1);i.target.style[r]=zN[`${a}_HTML`](l),this.annotationStorage.setValue(this.data.id,{[r]:zN[`${a}_rgb`](l)})};return Cn(this,"_commonActions",{display:t=>{const{display:r}=t.detail,i=r%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:r===1||r===2})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:r}=t.detail;this.container.style.visibility=r?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:r,noView:r})},focus:t=>{setTimeout(()=>t.target.focus({preventScroll:!1}),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{e("bgColor","backgroundColor",t)},fillColor:t=>{e("fillColor","backgroundColor",t)},fgColor:t=>{e("fgColor","color",t)},textColor:t=>{e("textColor","color",t)},borderColor:t=>{e("borderColor","borderColor",t)},strokeColor:t=>{e("strokeColor","borderColor",t)},rotation:t=>{const r=t.detail.rotation;this.setRotation(r),this.annotationStorage.setValue(this.data.id,{rotation:r})}})}_dispatchEventFromSandbox(e,t){const r=this._commonActions;for(const i of Object.keys(t.detail)){const o=e[i]||r[i];o==null||o(t)}}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;const t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;const r=this._commonActions;for(const[i,o]of Object.entries(t)){const a=r[i];if(a){const l={detail:{[i]:o},target:e};a(l),delete t[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:e}=this.data;if(!e)return;const[t,r,i,o]=this.data.rect.map(y=>Math.fround(y));if(e.length===8){const[y,v,x,w]=e.subarray(2,6);if(i===y&&o===v&&t===x&&r===w)return}const{style:a}=this.container;let l;if(h(this,bv)){const{borderColor:y,borderWidth:v}=a;a.borderWidth=0,l=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const d=i-t,c=o-r,{svgFactory:u}=this,f=u.createElement("svg");f.classList.add("quadrilateralsContainer"),f.setAttribute("width",0),f.setAttribute("height",0),f.role="none";const p=u.createElement("defs");f.append(p);const g=u.createElement("clipPath"),m=`clippath_${this.data.id}`;g.setAttribute("id",m),g.setAttribute("clipPathUnits","objectBoundingBox"),p.append(g);for(let y=2,v=e.length;y`)}h(this,bv)&&(l.push("')"),a.backgroundImage=l.join("")),this.container.append(f),this.container.style.clipPath=`url(#${m})`}_createPopup(e=null){const{data:t}=this;let r,i;e?(r={str:e.text},i=e.date):(r=t.contentsObj,i=t.modificationDate),R(this,vd,new zI({data:{color:t.color,titleObj:t.titleObj,modificationDate:i,contentsObj:r,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation,noRotate:!0},linkService:this.linkService,parent:this.parent,elements:[this]}))}get hasPopupElement(){return!!(h(this,vd)||this.popup||this.data.popupRef)}get extraPopupElement(){return h(this,vd)}render(){Hr("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){const r=[];if(this._fieldObjects){const i=this._fieldObjects[e];if(i)for(const{page:o,id:a,exportValues:l}of i){if(o===-1||a===t)continue;const d=typeof l=="string"?l:null,c=document.querySelector(`[data-element-id="${a}"]`);if(c&&!C0.has(c)){Bn(`_getElementsByName - element not allowed: ${a}`);continue}r.push({id:a,exportValue:d,domElement:c})}return r}for(const i of document.getElementsByName(e)){const{exportValue:o}=i,a=i.getAttribute("data-element-id");a!==t&&C0.has(i)&&r.push({id:a,exportValue:o,domElement:i})}return r}show(){var e;this.container&&(this.container.hidden=!1),(e=this.popup)==null||e.maybeShow()}hide(){var e;this.container&&(this.container.hidden=!0),(e=this.popup)==null||e.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(const t of e)t.classList.add("highlightArea");else e.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener("dblclick",()=>{var r;(r=this.linkService.eventBus)==null||r.dispatch("switchannotationeditormode",{source:this,mode:e,editId:t,mustEnterInEditMode:!0})})}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}};Py=new WeakMap,bv=new WeakMap,vd=new WeakMap,a_=new WeakSet,MI=function(e){const{container:{style:t},data:{rect:r,rotation:i},parent:{viewport:{rawDims:{pageWidth:o,pageHeight:a,pageX:l,pageY:d}}}}=this;r==null||r.splice(0,4,...e),t.left=`${100*(e[0]-l)/o}%`,t.top=`${100*(a-e[3]+d)/a}%`,i===0?(t.width=`${100*(e[2]-e[0])/o}%`,t.height=`${100*(e[3]-e[1])/a}%`):this.setRotation(i)};let ts=G3;class khe extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.editor=e.editor}render(){return this.container.className="editorAnnotation",this.container}createOrUpdatePopup(){const{editor:e}=this;e.hasComment&&this._createPopup(e.comment)}get hasCommentButton(){return this.enableComment&&this.editor.hasComment}get commentButtonPosition(){return this.editor.commentButtonPositionInPage}get commentText(){return this.editor.comment.text}set commentText(e){this.editor.comment=e,e||this.removePopup()}get commentData(){return this.editor.getData()}remove(){this.parent.removeAnnotation(this.data.id),this.container.remove(),this.container=null,this.removePopup()}}var Ll,dm,FG,DG;class z3 extends ts{constructor(t,r=null){super(t,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});N(this,Ll);this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:r}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let o=!1;return t.url?(r.addLinkAttributes(i,t.url,t.newWindow),o=!0):t.action?(this._bindNamedAction(i,t.action,t.overlaidText),o=!0):t.attachment?(q(this,Ll,FG).call(this,i,t.attachment,t.overlaidText,t.attachmentDest),o=!0):t.setOCGState?(q(this,Ll,DG).call(this,i,t.setOCGState,t.overlaidText),o=!0):t.dest?(this._bindLink(i,t.dest,t.overlaidText),o=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,t),o=!0),t.resetForm?(this._bindResetFormAction(i,t.resetForm),o=!0):this.isTooltipOnly&&!o&&(this._bindLink(i,""),o=!0)),this.container.classList.add("linkAnnotation"),o&&(this.contentElement=i,this.container.append(i)),this.container}_bindLink(t,r,i=""){t.href=this.linkService.getDestinationHash(r),t.onclick=()=>(r&&this.linkService.goToDestination(r),!1),(r||r==="")&&q(this,Ll,dm).call(this),i&&(t.title=i)}_bindNamedAction(t,r,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(r),!1),i&&(t.title=i),q(this,Ll,dm).call(this)}_bindJSAction(t,r){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const o of Object.keys(r.actions)){const a=i.get(o);a&&(t[a]=()=>{var l;return(l=this.linkService.eventBus)==null||l.dispatch("dispatcheventinsandbox",{source:this,detail:{id:r.id,name:o}}),!1})}r.overlaidText&&(t.title=r.overlaidText),t.onclick||(t.onclick=()=>!1),q(this,Ll,dm).call(this)}_bindResetFormAction(t,r){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),q(this,Ll,dm).call(this),!this._fieldObjects){Bn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(t.onclick=()=>!1);return}t.onclick=()=>{var f;i==null||i();const{fields:o,refs:a,include:l}=r,d=[];if(o.length!==0||a.length!==0){const p=new Set(a);for(const g of o){const m=this._fieldObjects[g]||[];for(const{id:y}of m)p.add(y)}for(const g of Object.values(this._fieldObjects))for(const m of g)p.has(m.id)===l&&d.push(m)}else for(const p of Object.values(this._fieldObjects))d.push(...p);const c=this.annotationStorage,u=[];for(const p of d){const{id:g}=p;switch(u.push(g),p.type){case"text":{const y=p.defaultValue||"";c.setValue(g,{value:y});break}case"checkbox":case"radiobutton":{const y=p.defaultValue===p.exportValues;c.setValue(g,{value:y});break}case"combobox":case"listbox":{const y=p.defaultValue||"";c.setValue(g,{value:y});break}default:continue}const m=document.querySelector(`[data-element-id="${g}"]`);if(m){if(!C0.has(m)){Bn(`_bindResetFormAction - element not allowed: ${g}`);continue}}else continue;m.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((f=this.linkService.eventBus)==null||f.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Ll=new WeakSet,dm=function(){this.container.setAttribute("data-internal-link","")},FG=function(t,r,i="",o=null){t.href=this.linkService.getAnchorUrl(""),r.description?t.title=r.description:i&&(t.title=i),t.onclick=()=>{var a;return(a=this.downloadManager)==null||a.openOrDownloadData(r.content,r.filename,o),!1},q(this,Ll,dm).call(this)},DG=function(t,r,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(r),!1),i&&(t.title=i),q(this,Ll,dm).call(this)};class _he extends ts{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const e=document.createElement("img");return e.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",e.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),e.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container.append(e),this.container}}class U0 extends ts{render(){return this.container}showElementAndHideCanvas(e){var t;this.data.hasOwnCanvas&&(((t=e.previousSibling)==null?void 0:t.nodeName)==="CANVAS"&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return Ds.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,r,i,o){r.includes("mouse")?e.addEventListener(r,a=>{var l;(l=this.linkService.eventBus)==null||l.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:o(a),shift:a.shiftKey,modifier:this._getKeyModifier(a)}})}):e.addEventListener(r,a=>{var l;if(r==="blur"){if(!t.focused||!a.relatedTarget)return;t.focused=!1}else if(r==="focus"){if(t.focused)return;t.focused=!0}o&&((l=this.linkService.eventBus)==null||l.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:o(a)}}))})}_setEventListeners(e,t,r,i){var o,a,l;for(const[d,c]of r)(c==="Action"||(o=this.data.actions)!=null&&o[c])&&((c==="Focus"||c==="Blur")&&(t||(t={focused:!1})),this._setEventListener(e,t,d,c,i),c==="Focus"&&!((a=this.data.actions)!=null&&a.Blur)?this._setEventListener(e,t,"blur","Blur",null):c==="Blur"&&!((l=this.data.actions)!=null&&l.Focus)&&this._setEventListener(e,t,"focus","Focus",null))}_setBackgroundColor(e){const t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?"transparent":yt.makeHexColor(...t)}_setTextStyle(e){const t=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||She,o=e.style;let a;const l=2,d=c=>Math.round(10*c)/10;if(this.data.multiLine){const c=Math.abs(this.data.rect[3]-this.data.rect[1]-l),u=Math.round(c/(OP*i))||1,f=c/u;a=Math.min(i,d(f/OP))}else{const c=Math.abs(this.data.rect[3]-this.data.rect[1]-l);a=Math.min(i,d(c/OP))}o.fontSize=`calc(${a}px * var(--total-scale-factor))`,o.color=yt.makeHexColor(...r),this.data.textAlignment!==null&&(o.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute("required",!0):e.removeAttribute("required"),e.setAttribute("aria-required",t)}}class Che extends U0{constructor(e){const t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,r,i){const o=this.annotationStorage;for(const a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=r),o.setValue(a.id,{[i]:r})}render(){var i,o;const e=this.annotationStorage,t=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){const a=e.getValue(t,{value:this.data.fieldValue});let l=a.value||"";const d=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;d&&l.length>d&&(l=l.slice(0,d));let c=a.formattedValue||((i=this.data.textContent)==null?void 0:i.join(` -`))||null;c&&this.data.comb&&(c=c.replaceAll(/\s+/g,""));const u={userValue:l,formattedValue:c,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=c??l,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type=this.data.password?"password":"text",r.setAttribute("value",c??l),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),C0.add(r),this.contentElement=r,r.setAttribute("data-element-id",t),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=0;const{datetimeFormat:f,datetimeType:p,timeStep:g}=this.data,m=!!p&&this.enableScripting;f&&(r.title=f),this._setRequired(r,this.data.required),d&&(r.maxLength=d),r.addEventListener("input",v=>{e.setValue(t,{value:v.target.value}),this.setPropertyOnSiblings(r,"value",v.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",v=>{const x=this.data.defaultFieldValue??"";r.value=u.userValue=x,u.formattedValue=null});let y=v=>{const{formattedValue:x}=u;x!=null&&(v.target.value=x),v.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",x=>{var S;if(u.focused)return;const{target:w}=x;if(m&&(w.type=p,g&&(w.step=g)),u.userValue){const _=u.userValue;if(m)if(p==="time"){const b=new Date(_),C=[b.getHours(),b.getMinutes(),b.getSeconds()];w.value=C.map(T=>T.toString().padStart(2,"0")).join(":")}else w.value=new Date(_-jhe).toISOString().split(p==="date"?"T":".",1)[0];else w.value=_}u.lastCommittedValue=w.value,u.commitKey=1,(S=this.data.actions)!=null&&S.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",x=>{this.showElementAndHideCanvas(x.target);const w={value(S){u.userValue=S.detail.value??"",m||e.setValue(t,{value:u.userValue.toString()}),S.target.value=u.userValue},formattedValue(S){const{formattedValue:_}=S.detail;u.formattedValue=_,_!=null&&S.target!==document.activeElement&&(S.target.value=_);const b={formattedValue:_};m&&(b.value=_),e.setValue(t,b)},selRange(S){S.target.setSelectionRange(...S.detail.selRange)},charLimit:S=>{var T;const{charLimit:_}=S.detail,{target:b}=S;if(_===0){b.removeAttribute("maxLength");return}b.setAttribute("maxLength",_);let C=u.userValue;!C||C.length<=_||(C=C.slice(0,_),b.value=u.userValue=C,e.setValue(t,{value:C}),(T=this.linkService.eventBus)==null||T.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:C,willCommit:!0,commitKey:1,selStart:b.selectionStart,selEnd:b.selectionEnd}}))}};this._dispatchEventFromSandbox(w,x)}),r.addEventListener("keydown",x=>{var _;u.commitKey=1;let w=-1;if(x.key==="Escape"?w=0:x.key==="Enter"&&!this.data.multiLine?w=2:x.key==="Tab"&&(u.commitKey=3),w===-1)return;const{value:S}=x.target;u.lastCommittedValue!==S&&(u.lastCommittedValue=S,u.userValue=S,(_=this.linkService.eventBus)==null||_.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:S,willCommit:!0,commitKey:w,selStart:x.target.selectionStart,selEnd:x.target.selectionEnd}}))});const v=y;y=null,r.addEventListener("blur",x=>{var _,b;if(!u.focused||!x.relatedTarget)return;(_=this.data.actions)!=null&&_.Blur||(u.focused=!1);const{target:w}=x;let{value:S}=w;if(m){if(S&&p==="time"){const C=S.split(":").map(T=>parseInt(T,10));S=new Date(2e3,0,1,C[0],C[1],C[2]||0).valueOf(),w.step=""}else S.includes("T")||(S=`${S}T00:00`),S=new Date(S).valueOf();w.type="text"}u.userValue=S,u.lastCommittedValue!==S&&((b=this.linkService.eventBus)==null||b.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:S,willCommit:!0,commitKey:u.commitKey,selStart:x.target.selectionStart,selEnd:x.target.selectionEnd}})),v(x)}),(o=this.data.actions)!=null&&o.Keystroke&&r.addEventListener("beforeinput",x=>{var A;u.lastCommittedValue=null;const{data:w,target:S}=x,{value:_,selectionStart:b,selectionEnd:C}=S;let T=b,F=C;switch(x.inputType){case"deleteWordBackward":{const D=_.substring(0,b).match(/\w*[^\w]*$/);D&&(T-=D[0].length);break}case"deleteWordForward":{const D=_.substring(b).match(/^[^\w]*\w*/);D&&(F+=D[0].length);break}case"deleteContentBackward":b===C&&(T-=1);break;case"deleteContentForward":b===C&&(F+=1);break}x.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:_,change:w||"",willCommit:!1,selStart:T,selEnd:F}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],x=>x.target.value)}if(y&&r.addEventListener("blur",y),this.data.comb){const x=(this.data.rect[2]-this.data.rect[0])/d;r.classList.add("comb"),r.style.letterSpacing=`calc(${x}px * var(--total-scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class Ahe extends U0{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}}class The extends U0{constructor(e){super(e,{isRenderable:e.renderForms})}render(){const e=this.annotationStorage,t=this.data,r=t.id;let i=e.getValue(r,{value:t.exportValue===t.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",e.setValue(r,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const o=document.createElement("input");return C0.add(o),o.setAttribute("data-element-id",r),o.disabled=t.readOnly,this._setRequired(o,this.data.required),o.type="checkbox",o.name=t.fieldName,i&&o.setAttribute("checked",!0),o.setAttribute("exportValue",t.exportValue),o.tabIndex=0,o.addEventListener("change",a=>{const{name:l,checked:d}=a.target;for(const c of this._getElementsByName(l,r)){const u=d&&c.exportValue===t.exportValue;c.domElement&&(c.domElement.checked=u),e.setValue(c.id,{value:u})}e.setValue(r,{value:d})}),o.addEventListener("resetform",a=>{const l=t.defaultFieldValue||"Off";a.target.checked=l===t.exportValue}),this.enableScripting&&this.hasJSActions&&(o.addEventListener("updatefromsandbox",a=>{const l={value(d){d.target.checked=d.detail.value!=="Off",e.setValue(r,{value:d.target.checked})}};this._dispatchEventFromSandbox(l,a)}),this._setEventListeners(o,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)),this._setBackgroundColor(o),this._setDefaultPropertiesFromJS(o),this.container.append(o),this.container}}class EG extends U0{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const e=this.annotationStorage,t=this.data,r=t.id;let i=e.getValue(r,{value:t.fieldValue===t.buttonValue}).value;if(typeof i=="string"&&(i=i!==t.buttonValue,e.setValue(r,{value:i})),i)for(const a of this._getElementsByName(t.fieldName,r))e.setValue(a.id,{value:!1});const o=document.createElement("input");if(C0.add(o),o.setAttribute("data-element-id",r),o.disabled=t.readOnly,this._setRequired(o,this.data.required),o.type="radio",o.name=t.fieldName,i&&o.setAttribute("checked",!0),o.tabIndex=0,o.addEventListener("change",a=>{const{name:l,checked:d}=a.target;for(const c of this._getElementsByName(l,r))e.setValue(c.id,{value:!1});e.setValue(r,{value:d})}),o.addEventListener("resetform",a=>{const l=t.defaultFieldValue;a.target.checked=l!=null&&l===t.buttonValue}),this.enableScripting&&this.hasJSActions){const a=t.buttonValue;o.addEventListener("updatefromsandbox",l=>{const d={value:c=>{const u=a===c.detail.value;for(const f of this._getElementsByName(c.target.name)){const p=u&&f.id===r;f.domElement&&(f.domElement.checked=p),e.setValue(f.id,{value:p})}}};this._dispatchEventFromSandbox(d,l)}),this._setEventListeners(o,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],l=>l.target.checked)}return this._setBackgroundColor(o),this._setDefaultPropertiesFromJS(o),this.container.append(o),this.container}}class Fhe extends z3{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){const e=super.render();e.classList.add("buttonWidgetAnnotation","pushButton");const t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener("updatefromsandbox",r=>{this._dispatchEventFromSandbox({},r)})),e}}class Dhe extends U0{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const e=this.annotationStorage,t=this.data.id,r=e.getValue(t,{value:this.data.fieldValue}),i=document.createElement("select");C0.add(i),i.setAttribute("data-element-id",t),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=0;let o=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",f=>{const p=this.data.defaultFieldValue;for(const g of i.options)g.selected=g.value===p});const a=(f,p)=>{const g=p.replaceAll(" "," ");f.textContent=g,g!==p&&f.setAttribute("display-value",p)};for(const f of this.data.options){const p=document.createElement("option");a(p,f.displayValue),p.value=f.exportValue,r.value.includes(f.exportValue)&&(p.setAttribute("selected",!0),o=!1),i.append(p)}let l=null;if(o){const f=document.createElement("option");f.value=" ",f.setAttribute("hidden",!0),f.setAttribute("selected",!0),i.prepend(f),l=()=>{f.remove(),i.removeEventListener("input",l),l=null},i.addEventListener("input",l)}const d=f=>{const p=f?"value":"textContent",{options:g,multiple:m}=i;return m?Array.prototype.filter.call(g,y=>y.selected).map(y=>y[p]):g.selectedIndex===-1?null:g[g.selectedIndex][p]};let c=d(!1);const u=f=>{const p=f.target.options;return Array.prototype.map.call(p,g=>({displayValue:g.getAttribute("display-value")||g.textContent,exportValue:g.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",f=>{const p={value(g){l==null||l();const m=g.detail.value,y=new Set(Array.isArray(m)?m:[m]);for(const v of i.options)v.selected=y.has(v.value);e.setValue(t,{value:d(!0)}),c=d(!1)},multipleSelection(g){i.multiple=!0},remove(g){const m=i.options,y=g.detail.remove;m[y].selected=!1,i.remove(y),m.length>0&&Array.prototype.findIndex.call(m,x=>x.selected)===-1&&(m[0].selected=!0),e.setValue(t,{value:d(!0),items:u(g)}),c=d(!1)},clear(g){for(;i.length!==0;)i.remove(0);e.setValue(t,{value:null,items:[]}),c=d(!1)},insert(g){const{index:m,displayValue:y,exportValue:v}=g.detail.insert,x=i.children[m],w=document.createElement("option");a(w,y),w.value=v,x?x.before(w):i.append(w),e.setValue(t,{value:d(!0),items:u(g)}),c=d(!1)},items(g){const{items:m}=g.detail;for(;i.length!==0;)i.remove(0);for(const y of m){const{displayValue:v,exportValue:x}=y,w=document.createElement("option");a(w,v),w.value=x,i.append(w)}i.options.length>0&&(i.options[0].selected=!0),e.setValue(t,{value:d(!0),items:u(g)}),c=d(!1)},indices(g){const m=new Set(g.detail.indices);for(const y of g.target.options)y.selected=m.has(y.index);e.setValue(t,{value:d(!0)}),c=d(!1)},editable(g){g.target.disabled=!g.detail.editable}};this._dispatchEventFromSandbox(p,f)}),i.addEventListener("input",f=>{var m;const p=d(!0),g=d(!1);e.setValue(t,{value:p}),f.preventDefault(),(m=this.linkService.eventBus)==null||m.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:c,change:g,changeEx:p,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],f=>f.target.value)):i.addEventListener("input",function(f){e.setValue(t,{value:d(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}var l_,OI;class zI extends ts{constructor(t){const{data:r,elements:i,parent:o}=t,a=!!o._commentManager;super(t,{isRenderable:!a&&ts._hasPopupData(r)});N(this,l_);if(this.elements=i,a&&ts._hasPopupData(r)){const l=this.popup=q(this,l_,OI).call(this);for(const d of i)d.popup=l}else this.popup=null}render(){const{container:t}=this;t.classList.add("popupAnnotation"),t.role="comment";const r=this.popup=q(this,l_,OI).call(this),i=[];for(const o of this.elements)o.popup=r,o.container.ariaHasPopup="dialog",i.push(o.data.id),o.addHighlightArea();return this.container.setAttribute("aria-controls",i.map(o=>`${Yx}${o}`).join(",")),this.container}}l_=new WeakSet,OI=function(){return new Ehe({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate||this.data.creationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open,commentManager:this.parent._commentManager})};var Sl,Gp,KT,XT,vv,wv,ds,gu,Kp,Ry,Sv,jv,mu,jl,$h,Zh,cs,Jh,Xp,d_,ef,kv,By,Yp,ro,Qp,Hn,Y5,LI,NI,WI,Q5,UI,PG,RG,BG,IG,$5,Z5,HI;class Ehe{constructor({container:e,color:t,elements:r,titleObj:i,modificationDate:o,contentsObj:a,richText:l,parent:d,rect:c,parentRect:u,open:f,commentManager:p=null}){N(this,Hn);N(this,Sl,null);N(this,Gp,q(this,Hn,BG).bind(this));N(this,KT,q(this,Hn,HI).bind(this));N(this,XT,q(this,Hn,Z5).bind(this));N(this,vv,q(this,Hn,$5).bind(this));N(this,wv,null);N(this,ds,null);N(this,gu,null);N(this,Kp,null);N(this,Ry,null);N(this,Sv,null);N(this,jv,null);N(this,mu,!1);N(this,jl,null);N(this,$h,null);N(this,Zh,null);N(this,cs,null);N(this,Jh,null);N(this,Xp,null);N(this,d_,null);N(this,ef,null);N(this,kv,null);N(this,By,null);N(this,Yp,!1);N(this,ro,null);N(this,Qp,null);R(this,ds,e),R(this,kv,i),R(this,gu,a),R(this,ef,l),R(this,Sv,d),R(this,wv,t),R(this,d_,c),R(this,jv,u),R(this,Ry,r),R(this,Sl,p),R(this,ro,r[0]),R(this,Kp,bT.toDateObject(o)),this.trigger=r.flatMap(g=>g.getElementsToTriggerPopup()),p||(q(this,Hn,Y5).call(this),h(this,ds).hidden=!0,f&&q(this,Hn,$5).call(this))}renderCommentButton(){if(h(this,cs)){h(this,cs).parentNode||h(this,ro).container.after(h(this,cs));return}if(h(this,Jh)||q(this,Hn,LI).call(this),!h(this,Jh))return;const{signal:e}=R(this,$h,new AbortController),t=h(this,ro).hasOwnCommentButton,r=()=>{h(this,Sl).toggleCommentPopup(this,!0,void 0,!t)},i=()=>{h(this,Sl).toggleCommentPopup(this,!1,!0,!t)},o=()=>{h(this,Sl).toggleCommentPopup(this,!1,!1)};if(t){R(this,cs,h(this,ro).container);for(const a of this.trigger)a.ariaHasPopup="dialog",a.ariaControls="commentPopup",a.addEventListener("keydown",h(this,Gp),{signal:e}),a.addEventListener("click",r,{signal:e}),a.addEventListener("pointerenter",i,{signal:e}),a.addEventListener("pointerleave",o,{signal:e}),a.classList.add("popupTriggerArea")}else{const a=R(this,cs,document.createElement("button"));a.className="annotationCommentButton";const l=h(this,ro).container;a.style.zIndex=parseInt(l.style.zIndex,10)+1,a.tabIndex=0,a.ariaHasPopup="dialog",a.ariaControls="commentPopup",a.setAttribute("data-l10n-id","pdfjs-show-comment-button"),q(this,Hn,WI).call(this),q(this,Hn,NI).call(this),a.addEventListener("keydown",h(this,Gp),{signal:e}),a.addEventListener("click",r,{signal:e}),a.addEventListener("pointerenter",i,{signal:e}),a.addEventListener("pointerleave",o,{signal:e}),l.after(a)}}get commentButtonColor(){const{color:e,opacity:t}=h(this,ro).commentData;return e?h(this,Sv)._commentManager.makeCommentColor(e,t):null}focusCommentButton(){setTimeout(()=>{var e;(e=h(this,cs))==null||e.focus()},0)}getData(){const{richText:e,color:t,opacity:r,creationDate:i,modificationDate:o}=h(this,ro).commentData;return{contentsObj:{str:this.comment},richText:e,color:t,opacity:r,creationDate:i,modificationDate:o}}get elementBeforePopup(){return h(this,cs)}get comment(){return h(this,Qp)||R(this,Qp,h(this,ro).commentText),h(this,Qp)}set comment(e){e!==this.comment&&(h(this,ro).commentText=R(this,Qp,e))}focus(){var e;(e=h(this,ro).container)==null||e.focus()}get parentBoundingClientRect(){return h(this,ro).layer.getBoundingClientRect()}setCommentButtonStates({selected:e,hasPopup:t}){h(this,cs)&&(h(this,cs).classList.toggle("selected",e),h(this,cs).ariaExpanded=t)}setSelectedCommentButton(e){h(this,cs).classList.toggle("selected",e)}get commentPopupPosition(){if(h(this,Xp))return h(this,Xp);const{x:e,y:t,height:r}=h(this,cs).getBoundingClientRect(),{x:i,y:o,width:a,height:l}=h(this,ro).layer.getBoundingClientRect();return[(e-i)/a,(t+r-o)/l]}set commentPopupPosition(e){R(this,Xp,e)}hasDefaultPopupPosition(){return h(this,Xp)===null}get commentButtonPosition(){return h(this,Jh)}get commentButtonWidth(){return h(this,cs).getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){const[t,r]=h(this,Xp)||this.commentButtonPosition.map(c=>c/100),i=this.parentBoundingClientRect,{x:o,y:a,width:l,height:d}=i;h(this,Sl).showDialog(null,this,o+t*l,a+r*d,{...e,parentDimensions:i})}render(){var r,i;if(h(this,jl))return;const e=R(this,jl,document.createElement("div"));if(e.className="popup",h(this,wv)){const o=e.style.outlineColor=yt.makeHexColor(...h(this,wv));e.style.backgroundColor=`color-mix(in srgb, ${o} 30%, white)`}const t=document.createElement("span");if(t.className="header",(r=h(this,kv))!=null&&r.str){const o=document.createElement("span");o.className="title",t.append(o),{dir:o.dir,str:o.textContent}=h(this,kv)}if(e.append(t),h(this,Kp)){const o=document.createElement("time");o.className="popupDate",o.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),o.setAttribute("data-l10n-args",JSON.stringify({dateObj:h(this,Kp).valueOf()})),o.dateTime=h(this,Kp).toISOString(),t.append(o)}uV({html:h(this,Hn,Q5)||h(this,gu).str,dir:(i=h(this,gu))==null?void 0:i.dir,className:"popupContent"},e),h(this,ds).append(e)}updateEdited({rect:e,popup:t,deleted:r}){var i;if(h(this,Sl)){r?(this.remove(),R(this,Qp,null)):t&&(t.deleted?this.remove():(q(this,Hn,WI).call(this),R(this,Qp,t.text))),e&&(R(this,Jh,null),q(this,Hn,LI).call(this),q(this,Hn,NI).call(this));return}if(r||t!=null&&t.deleted){this.remove();return}q(this,Hn,Y5).call(this),h(this,By)||R(this,By,{contentsObj:h(this,gu),richText:h(this,ef)}),e&&R(this,Zh,null),t&&t.text&&(R(this,ef,q(this,Hn,RG).call(this,t.text)),R(this,Kp,bT.toDateObject(t.date)),R(this,gu,null)),(i=h(this,jl))==null||i.remove(),R(this,jl,null)}resetEdited(){var e;h(this,By)&&({contentsObj:Gi(this,gu)._,richText:Gi(this,ef)._}=h(this,By),R(this,By,null),(e=h(this,jl))==null||e.remove(),R(this,jl,null),R(this,Zh,null))}remove(){var e,t,r;if((e=h(this,$h))==null||e.abort(),R(this,$h,null),(t=h(this,jl))==null||t.remove(),R(this,jl,null),R(this,Yp,!1),R(this,mu,!1),(r=h(this,cs))==null||r.remove(),R(this,cs,null),this.trigger)for(const i of this.trigger)i.classList.remove("popupTriggerArea")}forceHide(){R(this,Yp,this.isVisible),h(this,Yp)&&(h(this,ds).hidden=!0)}maybeShow(){h(this,Sl)||(q(this,Hn,Y5).call(this),h(this,Yp)&&(h(this,jl)||q(this,Hn,Z5).call(this),R(this,Yp,!1),h(this,ds).hidden=!1))}get isVisible(){return h(this,Sl)?!1:h(this,ds).hidden===!1}}Sl=new WeakMap,Gp=new WeakMap,KT=new WeakMap,XT=new WeakMap,vv=new WeakMap,wv=new WeakMap,ds=new WeakMap,gu=new WeakMap,Kp=new WeakMap,Ry=new WeakMap,Sv=new WeakMap,jv=new WeakMap,mu=new WeakMap,jl=new WeakMap,$h=new WeakMap,Zh=new WeakMap,cs=new WeakMap,Jh=new WeakMap,Xp=new WeakMap,d_=new WeakMap,ef=new WeakMap,kv=new WeakMap,By=new WeakMap,Yp=new WeakMap,ro=new WeakMap,Qp=new WeakMap,Hn=new WeakSet,Y5=function(){var t;if(h(this,$h))return;R(this,$h,new AbortController);const{signal:e}=h(this,$h);for(const r of this.trigger)r.addEventListener("click",h(this,vv),{signal:e}),r.addEventListener("pointerenter",h(this,XT),{signal:e}),r.addEventListener("pointerleave",h(this,KT),{signal:e}),r.classList.add("popupTriggerArea");for(const r of h(this,Ry))(t=r.container)==null||t.addEventListener("keydown",h(this,Gp),{signal:e})},LI=function(){const e=h(this,Ry).find(t=>t.hasCommentButton);e&&R(this,Jh,e._normalizePoint(e.commentButtonPosition))},NI=function(){if(h(this,ro).extraPopupElement&&!h(this,ro).editor)return;h(this,cs)||this.renderCommentButton();const[e,t]=h(this,Jh),{style:r}=h(this,cs);r.left=`calc(${e}%)`,r.top=`calc(${t}% - var(--comment-button-dim))`},WI=function(){h(this,ro).extraPopupElement||(h(this,cs)||this.renderCommentButton(),h(this,cs).style.backgroundColor=this.commentButtonColor||"")},Q5=function(){const e=h(this,ef),t=h(this,gu);return e!=null&&e.str&&(!(t!=null&&t.str)||t.str===e.str)&&h(this,ef).html||null},UI=function(){var e,t,r;return((r=(t=(e=h(this,Hn,Q5))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:r.fontSize)||0},PG=function(){var e,t,r;return((r=(t=(e=h(this,Hn,Q5))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:r.color)||null},RG=function(e){const t=[],r={str:e,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:t}]}},i={style:{color:h(this,Hn,PG),fontSize:h(this,Hn,UI)?`calc(${h(this,Hn,UI)}px * var(--total-scale-factor))`:""}};for(const o of e.split(` -`))t.push({name:"span",value:o,attributes:i});return r},BG=function(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key==="Enter"||e.key==="Escape"&&h(this,mu))&&q(this,Hn,$5).call(this)},IG=function(){if(h(this,Zh)!==null)return;const{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:r,pageX:i,pageY:o}}}=h(this,Sv);let a=!!h(this,jv),l=a?h(this,jv):h(this,d_);for(const m of h(this,Ry))if(!l||yt.intersect(m.data.rect,l)!==null){l=m.data.rect,a=!0;break}const d=yt.normalizeRect([l[0],e[3]-l[1]+e[1],l[2],e[3]-l[3]+e[1]]),u=a?l[2]-l[0]+5:0,f=d[0]+u,p=d[1];R(this,Zh,[100*(f-i)/t,100*(p-o)/r]);const{style:g}=h(this,ds);g.left=`${h(this,Zh)[0]}%`,g.top=`${h(this,Zh)[1]}%`},$5=function(){if(h(this,Sl)){h(this,Sl).toggleCommentPopup(this,!1);return}R(this,mu,!h(this,mu)),h(this,mu)?(q(this,Hn,Z5).call(this),h(this,ds).addEventListener("click",h(this,vv)),h(this,ds).addEventListener("keydown",h(this,Gp))):(q(this,Hn,HI).call(this),h(this,ds).removeEventListener("click",h(this,vv)),h(this,ds).removeEventListener("keydown",h(this,Gp)))},Z5=function(){h(this,jl)||this.render(),this.isVisible?h(this,mu)&&h(this,ds).classList.add("focused"):(q(this,Hn,IG).call(this),h(this,ds).hidden=!1,h(this,ds).style.zIndex=parseInt(h(this,ds).style.zIndex,10)+1e3)},HI=function(){h(this,ds).classList.remove("focused"),!(h(this,mu)||!this.isVisible)&&(h(this,ds).hidden=!0,h(this,ds).style.zIndex=parseInt(h(this,ds).style.zIndex,10)-1e3)};class MG extends ts{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=jn.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const e=this.contentElement=document.createElement("div");e.classList.add("annotationTextContent"),e.setAttribute("role","comment");for(const t of this.textContent){const r=document.createElement("span");r.textContent=t,e.append(r)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this._editOnDoubleClick(),this.container}}var c_;class Phe extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,c_,null)}render(){this.container.classList.add("lineAnnotation");const{data:t,width:r,height:i}=this,o=this.svgFactory.create(r,i,!0),a=R(this,c_,this.svgFactory.createElement("svg:line"));return a.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),a.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),a.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),a.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),a.setAttribute("stroke-width",t.borderStyle.width||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),o.append(a),this.container.append(o),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,c_)}addHighlightArea(){this.container.classList.add("highlightArea")}}c_=new WeakMap;var u_;class Rhe extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,u_,null)}render(){this.container.classList.add("squareAnnotation");const{data:t,width:r,height:i}=this,o=this.svgFactory.create(r,i,!0),a=t.borderStyle.width,l=R(this,u_,this.svgFactory.createElement("svg:rect"));return l.setAttribute("x",a/2),l.setAttribute("y",a/2),l.setAttribute("width",r-a),l.setAttribute("height",i-a),l.setAttribute("stroke-width",a||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,u_)}addHighlightArea(){this.container.classList.add("highlightArea")}}u_=new WeakMap;var h_;class Bhe extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,h_,null)}render(){this.container.classList.add("circleAnnotation");const{data:t,width:r,height:i}=this,o=this.svgFactory.create(r,i,!0),a=t.borderStyle.width,l=R(this,h_,this.svgFactory.createElement("svg:ellipse"));return l.setAttribute("cx",r/2),l.setAttribute("cy",i/2),l.setAttribute("rx",r/2-a/2),l.setAttribute("ry",i/2-a/2),l.setAttribute("stroke-width",a||1),l.setAttribute("stroke","transparent"),l.setAttribute("fill","transparent"),o.append(l),this.container.append(o),!t.popupRef&&this.hasPopupData&&(this.hasOwnCommentButton=!0,this._createPopup()),this.container}getElementsToTriggerPopup(){return h(this,h_)}addHighlightArea(){this.container.classList.add("highlightArea")}}h_=new WeakMap;var f_;class zG extends ts{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});N(this,f_,null);this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:r,borderStyle:i,popupRef:o},width:a,height:l}=this;if(!r)return this.container;const d=this.svgFactory.create(a,l,!0);let c=[];for(let f=0,p=r.length;f=0&&a.setAttribute("stroke-width",r||1),i)for(let l=0,d=h(this,Iy).length;l{a.key==="Enter"&&(o?a.metaKey:a.ctrlKey)&&q(this,y_,VI).call(this)}),!r.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return h(this,m_)}addHighlightArea(){this.container.classList.add("highlightArea")}}m_=new WeakMap,y_=new WeakSet,VI=function(){var t;(t=this.downloadManager)==null||t.openOrDownloadData(this.content,this.filename)};var My,zy,_v,$p,x_,Oy,kl,b_,vf,J5,KI;const K3=class K3{constructor({div:e,accessibilityManager:t,annotationCanvasMap:r,annotationEditorUIManager:i,page:o,viewport:a,structTreeLayer:l,commentManager:d,linkService:c,annotationStorage:u}){N(this,vf);N(this,My,null);N(this,zy,null);N(this,_v,null);N(this,$p,new Map);N(this,x_,null);N(this,Oy,null);N(this,kl,[]);N(this,b_,!1);ve(this,"zIndex",0);this.div=e,R(this,My,t),R(this,zy,r),R(this,x_,l||null),R(this,Oy,c||null),R(this,_v,u||new I3),this.page=o,this.viewport=a,this._annotationEditorUIManager=i,this._commentManager=d||null}hasEditableAnnotations(){return h(this,$p).size>0}async render(e){var l;const{annotations:t}=e,r=this.div;k0(r,this.viewport);const i=new Map,o=[],a={data:null,layer:r,linkService:h(this,Oy),downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new kT,annotationStorage:h(this,_v),enableComment:e.enableComment===!0,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(const d of t){if(d.noHTML)continue;const c=d.annotationType===Cs.POPUP;if(c){const p=i.get(d.id);if(!p)continue;if(!this._commentManager){o.push(d);continue}a.elements=p}else if(d.rect[2]===d.rect[0]||d.rect[3]===d.rect[1])continue;a.data=d;const u=HP.create(a);if(!u.isRenderable)continue;c||(h(this,kl).push(u),d.popupRef&&i.getOrInsertComputed(d.popupRef,F3).push(u));const f=u.render();d.hidden&&(f.style.visibility="hidden"),u._isEditable&&(h(this,$p).set(u.data.id,u),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(u))}await q(this,vf,J5).call(this);for(const d of o){const c=a.elements=i.get(d.id);a.data=d;const u=HP.create(a);if(!u.isRenderable)continue;const f=u.render();u.contentElement.id=`${Yx}${d.id}`,d.hidden&&(f.style.visibility="hidden"),c.at(-1).container.after(f)}q(this,vf,KI).call(this)}async addLinkAnnotations(e){const t={data:null,layer:this.div,linkService:h(this,Oy),svgFactory:new kT,parent:this};for(const r of e){r.borderStyle||(r.borderStyle=K3._defaultBorderStyle),t.data=r;const i=HP.create(t);i.isRenderable&&(i.render(),i.contentElement.id=`${Yx}${r.id}`,h(this,kl).push(i))}await q(this,vf,J5).call(this)}update({viewport:e}){const t=this.div;this.viewport=e,k0(t,{rotation:e.rotation}),q(this,vf,KI).call(this),t.hidden=!1}getEditableAnnotations(){return h(this,$p).values()}getEditableAnnotation(e){return h(this,$p).get(e)}addFakeAnnotation(e){const{div:t}=this,{id:r,rotation:i}=e,o=new khe({data:{id:r,rect:e.getPDFRect(),rotation:i},editor:e,layer:t,parent:this,enableComment:!!this._commentManager,linkService:h(this,Oy),annotationStorage:h(this,_v)});return o.render(),o.contentElement.id=`${Yx}${r}`,o.createOrUpdatePopup(),h(this,kl).push(o),o}removeAnnotation(e){var i;const t=h(this,kl).findIndex(o=>o.data.id===e);if(t<0)return;const[r]=h(this,kl).splice(t,1);(i=h(this,My))==null||i.removePointerInTextLayer(r.contentElement)}updateFakeAnnotations(e){if(e.length!==0){for(const t of e)t.updateFakeAnnotationElement(this);q(this,vf,J5).call(this)}}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}static get _defaultBorderStyle(){return Cn(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:Sx.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}};My=new WeakMap,zy=new WeakMap,_v=new WeakMap,$p=new WeakMap,x_=new WeakMap,Oy=new WeakMap,kl=new WeakMap,b_=new WeakMap,vf=new WeakSet,J5=async function(){var r,i,o;if(h(this,kl).length===0)return;this.div.replaceChildren();const e=[];if(!h(this,b_)){R(this,b_,!0);for(const{contentElement:a,data:{id:l}}of h(this,kl)){const d=a.id=`${Yx}${l}`;e.push((r=h(this,x_))==null?void 0:r.getAriaAttributes(d).then(c=>{if(c)for(const[u,f]of c)a.setAttribute(u,f)}))}}h(this,kl).sort(({data:{rect:[a,l,d,c]}},{data:{rect:[u,f,p,g]}})=>{if(a===d&&l===c)return 1;if(u===p&&f===g)return-1;const m=c,y=l,v=(l+c)/2,x=g,w=f,S=(f+g)/2;if(v>=x&&S<=y)return-1;if(S>=m&&v<=w)return 1;const _=(a+d)/2,b=(u+p)/2;return _-b});const t=document.createDocumentFragment();for(const a of h(this,kl))t.append(a.container),this._commentManager?(o=((i=a.extraPopupElement)==null?void 0:i.popup)||a.popup)==null||o.renderCommentButton():a.extraPopupElement&&t.append(a.extraPopupElement.render());if(this.div.append(t),await Promise.all(e),h(this,My))for(const a of h(this,kl))h(this,My).addPointerInTextLayer(a.contentElement,!1)},KI=function(){var t;if(!h(this,zy))return;const e=this.div;for(const[r,i]of h(this,zy)){const o=e.querySelector(`[data-annotation-id="${r}"]`);if(!o)continue;i.className="annotationContent";const{firstChild:a}=o;a?a.nodeName==="CANVAS"?a.replaceWith(i):a.classList.contains("annotationContent")?a.after(i):a.before(i):o.append(i);const l=h(this,$p).get(r);l&&(l._hasNoCanvas?((t=this._annotationEditorUIManager)==null||t.setMissingCanvas(r,o.id,i),l._hasNoCanvas=!1):l.canvas=i)}h(this,zy).clear()};let GI=K3;const Q2=/\r\n?|\n/g;var _l,v_,Ly,Cl,Es,NG,WG,UG,eA,wf,tA,nA,HG,YI,qG;const wi=class wi extends xi{constructor(t){super({...t,name:"freeTextEditor"});N(this,Es);N(this,_l,"");N(this,v_,`${this.id}-editor`);N(this,Ly,null);N(this,Cl);ve(this,"_colorPicker",null);this.color=t.color||wi._defaultColor||xi._defaultLineColor,R(this,Cl,t.fontSize||wi._defaultFontSize),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert"),this.canAddComment=!1}static get _keyboardManager(){const t=wi.prototype,r=a=>a.isEmpty(),i=_0.TRANSLATE_SMALL,o=_0.TRANSLATE_BIG;return Cn(this,"_keyboardManager",new uC([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:r}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-o,0],checker:r}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[i,0],checker:r}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[o,0],checker:r}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:r}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-o],checker:r}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,i],checker:r}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,o],checker:r}]]))}static initialize(t,r){xi.initialize(t,r);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,r){switch(t){case Wn.FREETEXT_SIZE:wi._defaultFontSize=r;break;case Wn.FREETEXT_COLOR:wi._defaultColor=r;break}}updateParams(t,r){switch(t){case Wn.FREETEXT_SIZE:q(this,Es,NG).call(this,r);break;case Wn.FREETEXT_COLOR:q(this,Es,WG).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Wn.FREETEXT_SIZE,wi._defaultFontSize],[Wn.FREETEXT_COLOR,wi._defaultColor||xi._defaultLineColor]]}get propertiesToUpdate(){return[[Wn.FREETEXT_SIZE,h(this,Cl)],[Wn.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||(this._colorPicker=new jT(this)),[["colorPicker",this._colorPicker]]}get colorType(){return Wn.FREETEXT_COLOR}onUpdatedColor(){var t;this.editorDiv.style.color=this.color,(t=this._colorPicker)==null||t.update(this.color),super.onUpdatedColor()}_translateEmpty(t,r){this._uiManager.translateSelectedEditors(t,r,!0)}getInitialTranslation(){const t=this.parentScale;return[-wi._internalPadding*t,-(wi._internalPadding+h(this,Cl))*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(!super.enableEditMode())return!1;this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),R(this,Ly,new AbortController);const t=this._uiManager.combinedSignal(h(this,Ly));return this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t}),!0}disableEditMode(){var t;return super.disableEditMode()?(this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",h(this,v_)),this._isDraggable=!0,(t=h(this,Ly))==null||t.abort(),R(this,Ly,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"),!0):!1}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){var r;this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),(r=this._initialOptions)!=null&&r.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=h(this,_l),r=R(this,_l,q(this,Es,UG).call(this).trimEnd());if(t===r)return;const i=o=>{if(R(this,_l,o),!o){this.remove();return}q(this,Es,nA).call(this),this._uiManager.rebuild(this),q(this,Es,eA).call(this)};this.addCommands({cmd:()=>{i(r)},undo:()=>{i(t)},mustExec:!1}),q(this,Es,eA).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){wi._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}get canChangeContent(){return!0}render(){if(this.div)return this.div;let t,r;(this._isCopy||this.annotationElementId)&&(t=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",h(this,v_)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${h(this,Cl)}px * var(--total-scale-factor))`,i.color=this.color,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),this._isCopy||this.annotationElementId){const[o,a]=this.parentDimensions;if(this.annotationElementId){const{position:l}=this._initialData;let[d,c]=this.getInitialTranslation();[d,c]=this.pageTranslationToScreen(d,c);const[u,f]=this.pageDimensions,[p,g]=this.pageTranslation;let m,y;switch(this.rotation){case 0:m=t+(l[0]-p)/u,y=r+this.height-(l[1]-g)/f;break;case 90:m=t+(l[0]-p)/u,y=r-(l[1]-g)/f,[d,c]=[c,-d];break;case 180:m=t-this.width+(l[0]-p)/u,y=r-(l[1]-g)/f,[d,c]=[-d,-c];break;case 270:m=t+(l[0]-p-this.height*f)/u,y=r+(l[1]-g-this.width*u)/f,[d,c]=[-c,d];break}this.setAt(m*o,y*a,d,c)}else this._moveAfterPaste(t,r);q(this,Es,nA).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(t){var m,y,v;const r=t.clipboardData||window.clipboardData,{types:i}=r;if(i.length===1&&i[0]==="text/plain")return;t.preventDefault();const o=q(m=wi,wf,YI).call(m,r.getData("text")||"").replaceAll(Q2,` -`);if(!o)return;const a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();const l=a.getRangeAt(0);if(!o.includes(` -`)){l.insertNode(document.createTextNode(o)),this.editorDiv.normalize(),a.collapseToStart();return}const{startContainer:d,startOffset:c}=l,u=[],f=[];if(d.nodeType===Node.TEXT_NODE){const x=d.parentElement;if(f.push(d.nodeValue.slice(c).replaceAll(Q2,"")),x!==this.editorDiv){let w=u;for(const S of this.editorDiv.childNodes){if(S===x){w=f;continue}w.push(q(y=wi,wf,tA).call(y,S))}}u.push(d.nodeValue.slice(0,c).replaceAll(Q2,""))}else if(d===this.editorDiv){let x=u,w=0;for(const S of this.editorDiv.childNodes)w++===c&&(x=f),x.push(q(v=wi,wf,tA).call(v,S))}R(this,_l,`${u.join(` -`)}${o}${f.join(` -`)}`),q(this,Es,nA).call(this);const p=new Range;let g=Math.sumPrecise(u.map(x=>x.length));for(const{firstChild:x}of this.editorDiv.childNodes)if(x.nodeType===Node.TEXT_NODE){const w=x.nodeValue.length;if(g<=w){p.setStart(x,g),p.setEnd(x,g);break}g-=w}a.removeAllRanges(),a.addRange(p)}get contentDiv(){return this.editorDiv}getPDFRect(){const t=wi._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,r,i){var l;let o=null;if(t instanceof MG){const{data:{defaultAppearanceData:{fontSize:d,fontColor:c},rect:u,rotation:f,id:p,popupRef:g,richText:m,contentsObj:y,creationDate:v,modificationDate:x},textContent:w,textPosition:S,parent:{page:{pageNumber:_}}}=t;if(!w||w.length===0)return null;o=t={annotationType:jn.FREETEXT,color:Array.from(c),fontSize:d,value:w.join(` -`),position:S,pageIndex:_-1,rect:u.slice(0),rotation:f,annotationElementId:p,id:p,deleted:!1,popupRef:g,comment:(y==null?void 0:y.str)||null,richText:m,creationDate:v,modificationDate:x}}const a=await super.deserialize(t,r,i);return R(a,Cl,t.fontSize),a.color=yt.makeHexColor(...t.color),R(a,_l,q(l=wi,wf,YI).call(l,t.value)),a._initialData=o,t.comment&&a.setCommentData(t),a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const r=xi._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:r,fontSize:h(this,Cl),value:q(this,Es,HG).call(this)});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!q(this,Es,qG).call(this,i)?null:(i.id=this.annotationElementId,i)}renderAnnotationElement(t){const r=super.renderAnnotationElement(t);if(!r)return null;const{style:i}=r;i.fontSize=`calc(${h(this,Cl)}px * var(--total-scale-factor))`,i.color=this.color,r.replaceChildren();for(const o of h(this,_l).split(` -`)){const a=document.createElement("div");a.append(o?document.createTextNode(o):document.createElement("br")),r.append(a)}return t.updateEdited({rect:this.getPDFRect(),popup:this._uiManager.hasCommentManager()||this.hasEditedComment?this.comment:{text:h(this,_l)}}),r}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}};_l=new WeakMap,v_=new WeakMap,Ly=new WeakMap,Cl=new WeakMap,Es=new WeakSet,NG=function(t){const r=o=>{this.editorDiv.style.fontSize=`calc(${o}px * var(--total-scale-factor))`,this.translate(0,-(o-h(this,Cl))*this.parentScale),R(this,Cl,o),q(this,Es,eA).call(this)},i=h(this,Cl);this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},WG=function(t){const r=o=>{this.color=o,this.onUpdatedColor()},i=this.color;this.addCommands({cmd:r.bind(this,t),undo:r.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},UG=function(){var i;const t=[];this.editorDiv.normalize();let r=null;for(const o of this.editorDiv.childNodes)(r==null?void 0:r.nodeType)===Node.TEXT_NODE&&o.nodeName==="BR"||(t.push(q(i=wi,wf,tA).call(i,o)),r=o);return t.join(` -`)},eA=function(){const[t,r]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:o,div:a}=this,l=a.style.display,d=a.classList.contains("hidden");a.classList.remove("hidden"),a.style.display="hidden",o.div.append(this.div),i=a.getBoundingClientRect(),a.remove(),a.style.display=l,a.classList.toggle("hidden",d)}this.rotation%180===this.parentRotation%180?(this.width=i.width/t,this.height=i.height/r):(this.width=i.height/t,this.height=i.width/r),this.fixAndSetPosition()},wf=new WeakSet,tA=function(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(Q2,"")},nA=function(){if(this.editorDiv.replaceChildren(),!!h(this,_l))for(const t of h(this,_l).split(` -`)){const r=document.createElement("div");r.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(r)}},HG=function(){return h(this,_l).replaceAll(" "," ")},YI=function(t){return t.replaceAll(" "," ")},qG=function(t){const{value:r,fontSize:i,color:o,pageIndex:a}=this._initialData;return this.hasEditedComment||this._hasBeenMoved||t.value!==r||t.fontSize!==i||t.color.some((l,d)=>l!==o[d])||t.pageIndex!==a},N(wi,wf),ve(wi,"_freeTextDefaultContent",""),ve(wi,"_internalPadding",0),ve(wi,"_defaultColor",null),ve(wi,"_defaultFontSize",10),ve(wi,"_type","freetext"),ve(wi,"_editorType",jn.FREETEXT);let XI=wi;class Wt{toSVGPath(){Hr("Abstract method `toSVGPath` must be implemented.")}get box(){Hr("Abstract getter `box` must be implemented.")}serialize(e,t){Hr("Abstract method `serialize` must be implemented.")}static _rescale(e,t,r,i,o,a){a||(a=new Float32Array(e.length));for(let l=0,d=e.length;l=6;i-=6)isNaN(t[i])?r.push(`L${t[i+4]} ${t[i+5]}`):r.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);return q(this,Hs,GG).call(this,r),r.join(" ")}newFreeDrawOutline(e,t,r,i,o,a){return new $G(e,t,r,i,o,a)}getOutlines(){var f;const e=h(this,yu),t=h(this,xc),r=h(this,Jn),[i,o,a,l]=h(this,Al),d=new Float32Array((((f=h(this,Zp))==null?void 0:f.length)??0)+2);for(let p=0,g=d.length-2;p=6;p-=6)for(let g=0;g<6;g+=2){if(isNaN(t[p+g])){c[u]=c[u+1]=NaN,u+=2;continue}c[u]=t[p+g],c[u+1]=t[p+g+1],u+=2}return q(this,Hs,YG).call(this,c,u),this.newFreeDrawOutline(c,d,h(this,Al),h(this,Tv),h(this,Cv),h(this,Av))}};Al=new WeakMap,xc=new WeakMap,Cv=new WeakMap,Av=new WeakMap,yu=new WeakMap,Jn=new WeakMap,Ny=new WeakMap,Wy=new WeakMap,w_=new WeakMap,S_=new WeakMap,Tv=new WeakMap,Fv=new WeakMap,Zp=new WeakMap,j_=new WeakMap,YT=new WeakMap,QT=new WeakMap,Hs=new WeakSet,TS=function(){const e=h(this,Jn).subarray(4,6),t=h(this,Jn).subarray(16,18),[r,i,o,a]=h(this,Al);return[(h(this,Ny)+(e[0]-t[0])/2-r)/o,(h(this,Wy)+(e[1]-t[1])/2-i)/a,(h(this,Ny)+(t[0]-e[0])/2-r)/o,(h(this,Wy)+(t[1]-e[1])/2-i)/a]},VG=function(){const[e,t,r,i]=h(this,Al),[o,a,l,d]=q(this,Hs,TS).call(this);return`M${(h(this,Jn)[2]-e)/r} ${(h(this,Jn)[3]-t)/i} L${(h(this,Jn)[4]-e)/r} ${(h(this,Jn)[5]-t)/i} L${o} ${a} L${l} ${d} L${(h(this,Jn)[16]-e)/r} ${(h(this,Jn)[17]-t)/i} L${(h(this,Jn)[14]-e)/r} ${(h(this,Jn)[15]-t)/i} Z`},GG=function(e){const t=h(this,xc);e.push(`L${t[4]} ${t[5]} Z`)},KG=function(e){const[t,r,i,o]=h(this,Al),a=h(this,Jn).subarray(4,6),l=h(this,Jn).subarray(16,18),[d,c,u,f]=q(this,Hs,TS).call(this);e.push(`L${(a[0]-t)/i} ${(a[1]-r)/o} L${d} ${c} L${u} ${f} L${(l[0]-t)/i} ${(l[1]-r)/o}`)},XG=function(e){const t=h(this,Jn),[r,i,o,a]=h(this,Al),[l,d,c,u]=q(this,Hs,TS).call(this),f=new Float32Array(36);return f.set([NaN,NaN,NaN,NaN,(t[2]-r)/o,(t[3]-i)/a,NaN,NaN,NaN,NaN,(t[4]-r)/o,(t[5]-i)/a,NaN,NaN,NaN,NaN,l,d,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,(t[16]-r)/o,(t[17]-i)/a,NaN,NaN,NaN,NaN,(t[14]-r)/o,(t[15]-i)/a],0),this.newFreeDrawOutline(f,e,h(this,Al),h(this,Tv),h(this,Cv),h(this,Av))},YG=function(e,t){const r=h(this,xc);return e.set([NaN,NaN,NaN,NaN,r[4],r[5]],t),t+=6},QG=function(e,t){const r=h(this,Jn).subarray(4,6),i=h(this,Jn).subarray(16,18),[o,a,l,d]=h(this,Al),[c,u,f,p]=q(this,Hs,TS).call(this);return e.set([NaN,NaN,NaN,NaN,(r[0]-o)/l,(r[1]-a)/d,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,f,p,NaN,NaN,NaN,NaN,(i[0]-o)/l,(i[1]-a)/d],t),t+=24},N(xh,j_,8),N(xh,YT,2),N(xh,QT,h(xh,j_)+h(xh,YT));let _T=xh;var Dv,Uy,tf,k_,Tl,__,vs,$T,ZG;class $G extends Wt{constructor(t,r,i,o,a,l){super();N(this,$T);N(this,Dv);N(this,Uy,new Float32Array(4));N(this,tf);N(this,k_);N(this,Tl);N(this,__);N(this,vs);R(this,vs,t),R(this,Tl,r),R(this,Dv,i),R(this,__,o),R(this,tf,a),R(this,k_,l),this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],q(this,$T,ZG).call(this,l);const[d,c,u,f]=h(this,Uy);for(let p=0,g=t.length;px?(l=v,d=x):d===x&&(l=f(l,v)),up[1]?(l=p[0],d=p[1]):d===p[1]&&(l=f(l,p[0])),ut[0]-r[0]||t[1]-r[1]||t[2]-r[2]);const e=[];for(const t of h(this,Jp))t[3]?(e.push(...q(this,Ta,$I).call(this,t)),q(this,Ta,eK).call(this,t)):(q(this,Ta,tK).call(this,t),e.push(...q(this,Ta,$I).call(this,t)));return q(this,Ta,JG).call(this,e)}}C_=new WeakMap,A_=new WeakMap,T_=new WeakMap,Jp=new WeakMap,bc=new WeakMap,Ta=new WeakSet,JG=function(e){const t=[],r=new Set;for(const a of e){const[l,d,c]=a;t.push([l,d,a],[l,c,a])}t.sort((a,l)=>a[1]-l[1]||a[0]-l[0]);for(let a=0,l=t.length;a0;){const a=r.values().next().value;let[l,d,c,u,f]=a;r.delete(a);let p=l,g=d;for(o=[l,c],i.push(o);;){let m;if(r.has(u))m=u;else if(r.has(f))m=f;else break;r.delete(m),[l,d,c,u,f]=m,p!==l&&(o.push(p,g,l,g===d?d:c),p=l),g=g===d?c:d}o.push(p,g)}return new Whe(i,h(this,C_),h(this,A_),h(this,T_))},rA=function(e){const t=h(this,bc);let r=0,i=t.length-1;for(;r<=i;){const o=r+i>>1,a=t[o][0];if(a===e)return o;a=0;i--){const[o,a]=h(this,bc)[i];if(o!==e)break;if(o===e&&a===t){h(this,bc).splice(i,1);return}}},$I=function(e){const[t,r,i]=e,o=[[t,r,i]],a=q(this,Ta,rA).call(this,i);for(let l=0;l=d){if(g>c)o[u][1]=c;else{if(f===1)return[];o.splice(u,1),u--,f--}continue}o[u][2]=d,g>c&&o.push([t,c,g])}}}return o};var F_,Ev;class Whe extends Wt{constructor(t,r,i,o){super();N(this,F_);N(this,Ev);R(this,Ev,t),R(this,F_,r),this.firstPoint=i,this.lastPoint=o}toSVGPath(){const t=[];for(const r of h(this,Ev)){let[i,o]=r;t.push(`M${i} ${o}`);for(let a=2;a-1?(R(this,_o,!0),q(this,Un,iA).call(this,t),q(this,Un,cm).call(this)):h(this,nf)&&(R(this,Pv,t.anchorNode),R(this,D_,t.anchorOffset),R(this,P_,t.focusNode),R(this,R_,t.focusOffset),q(this,Un,JI).call(this),q(this,Un,cm).call(this),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert")}static get _keyboardManager(){const t=Rr.prototype;return Cn(this,"_keyboardManager",new uC([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:h(this,_o)?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:h(this,wd),methodOfCreation:h(this,B_)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.getNonHCMColorName(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}static initialize(t,r){var i;xi.initialize(t,r),Rr._defaultColor||(Rr._defaultColor=((i=r.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(t,r){switch(t){case Wn.HIGHLIGHT_COLOR:Rr._defaultColor=r;break;case Wn.HIGHLIGHT_THICKNESS:Rr._defaultThickness=r;break}}translateInPage(t,r){}get toolbarPosition(){return h(this,Bv)}get commentButtonPosition(){return h(this,Rv)}updateParams(t,r){switch(t){case Wn.HIGHLIGHT_COLOR:q(this,Un,nK).call(this,r);break;case Wn.HIGHLIGHT_THICKNESS:q(this,Un,rK).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Wn.HIGHLIGHT_COLOR,Rr._defaultColor],[Wn.HIGHLIGHT_THICKNESS,Rr._defaultThickness]]}get propertiesToUpdate(){return[[Wn.HIGHLIGHT_COLOR,this.color||Rr._defaultColor],[Wn.HIGHLIGHT_THICKNESS,h(this,wd)||Rr._defaultThickness],[Wn.HIGHLIGHT_FREE,h(this,_o)]]}onUpdatedColor(){var t,r;(t=this.parent)==null||t.drawLayer.updateProperties(h(this,Dl),{root:{fill:this.color,"fill-opacity":this.opacity}}),(r=h(this,E_))==null||r.updateColor(this.color),super.onUpdatedColor()}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",R(this,E_,new ST({editor:this}))]]:super.toolbarButtons}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(q(this,Un,oA).call(this))}getBaseTranslation(){return[0,0]}getRect(t,r){return super.getRect(t,r,q(this,Un,oA).call(this))}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){q(this,Un,eM).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(q(this,Un,cm).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let r=!1;this.parent&&!t?q(this,Un,eM).call(this):t&&(q(this,Un,cm).call(this,t),r=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),this.show(this._isVisible),r&&this.select()}rotate(t){var o,a,l;const{drawLayer:r}=this.parent;let i;h(this,_o)?(t=(t-this.rotation+360)%360,i=q(o=Rr,Fd,Fx).call(o,h(this,Fl).box,t)):i=q(a=Rr,Fd,Fx).call(a,[this.x,this.y,this.width,this.height],t),r.updateProperties(h(this,Dl),{bbox:i,root:{"data-main-rotation":t}}),r.updateProperties(h(this,ea),{bbox:q(l=Rr,Fd,Fx).call(l,h(this,Ga).box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();h(this,Iv)&&(t.setAttribute("aria-label",h(this,Iv)),t.setAttribute("role","mark")),h(this,_o)?t.classList.add("free"):this.div.addEventListener("keydown",q(this,Un,sK).bind(this),{signal:this._uiManager._signal});const r=R(this,qy,document.createElement("div"));return t.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=h(this,Hy),this.setDims(),xV(this,h(this,qy),["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{hovered:!0}})}pointerleave(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{hovered:!1}})}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:q(this,Un,sA).call(this,!0);break;case 1:case 3:q(this,Un,sA).call(this,!1);break}}select(){var t;super.select(),h(this,ea)&&((t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{hovered:!1,selected:!0}}))}unselect(){var t;super.unselect(),h(this,ea)&&((t=this.parent)==null||t.drawLayer.updateProperties(h(this,ea),{rootClass:{selected:!1}}),h(this,_o)||q(this,Un,sA).call(this,!1))}get _mustFixPosition(){return!h(this,_o)}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(h(this,Dl),{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(h(this,ea),{rootClass:{hidden:!t}}))}static startHighlighting(t,r,{target:i,x:o,y:a}){const{x:l,y:d,width:c,height:u}=i.getBoundingClientRect(),f=new AbortController,p=t.combinedSignal(f),g=m=>{f.abort(),q(this,Fd,dK).call(this,t,m)};window.addEventListener("blur",g,{signal:p}),window.addEventListener("pointerup",g,{signal:p}),window.addEventListener("pointerdown",$i,{capture:!0,passive:!1,signal:p}),window.addEventListener("contextmenu",Hd,{signal:p}),i.addEventListener("pointermove",q(this,Fd,lK).bind(this,t),{signal:p}),this._freeHighlight=new ZI({x:o,y:a},[l,d,c,u],t.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static async deserialize(t,r,i){var v,x,w,S;let o=null;if(t instanceof OG){const{data:{quadPoints:_,rect:b,rotation:C,id:T,color:F,opacity:A,popupRef:D,richText:P,contentsObj:L,creationDate:W,modificationDate:O},parent:{page:{pageNumber:U}}}=t;o=t={annotationType:jn.HIGHLIGHT,color:Array.from(F),opacity:A,quadPoints:_,boxes:null,pageIndex:U-1,rect:b.slice(0),rotation:C,annotationElementId:T,id:T,deleted:!1,popupRef:D,richText:P,comment:(L==null?void 0:L.str)||null,creationDate:W,modificationDate:O}}else if(t instanceof O3){const{data:{inkLists:_,rect:b,rotation:C,id:T,color:F,borderStyle:{rawWidth:A},popupRef:D,richText:P,contentsObj:L,creationDate:W,modificationDate:O},parent:{page:{pageNumber:U}}}=t;o=t={annotationType:jn.HIGHLIGHT,color:Array.from(F),thickness:A,inkLists:_,boxes:null,pageIndex:U-1,rect:b.slice(0),rotation:C,annotationElementId:T,id:T,deleted:!1,popupRef:D,richText:P,comment:(L==null?void 0:L.str)||null,creationDate:W,modificationDate:O}}const{color:a,quadPoints:l,inkLists:d,outlines:c,opacity:u}=t,f=await super.deserialize(t,r,i);f.color=yt.makeHexColor(...a),f.opacity=u||1,d&&R(f,wd,t.thickness),f._initialData=o,t.comment&&f.setCommentData(t);const[p,g]=f.pageDimensions,[m,y]=f.pageTranslation;if(l){const _=R(f,nf,[]);for(let b=0;b=0)R(this,Dl,r),R(this,Hy,i),this.parent.drawLayer.finalizeDraw(r,{bbox:t.box,path:{d:t.toSVGPath()}}),R(this,ea,this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:h(this,Ga).box,path:{d:h(this,Ga).toSVGPath()}},!0));else if(this.parent){const m=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(h(this,Dl),{bbox:q(p=Rr,Fd,Fx).call(p,h(this,Fl).box,(m-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(h(this,ea),{bbox:q(g=Rr,Fd,Fx).call(g,h(this,Ga).box,m),path:{d:h(this,Ga).toSVGPath()}})}const[a,l,d,c]=t.box;switch(this.rotation){case 0:this.x=a,this.y=l,this.width=d,this.height=c;break;case 90:{const[m,y]=this.parentDimensions;this.x=l,this.y=1-a,this.width=d*y/m,this.height=c*m/y;break}case 180:this.x=1-a,this.y=1-l,this.width=d,this.height=c;break;case 270:{const[m,y]=this.parentDimensions;this.x=1-l,this.y=a,this.width=d*y/m,this.height=c*m/y;break}}const{firstPoint:u}=t;R(this,Rv,[(u[0]-a)/d,(u[1]-l)/c]);const{lastPoint:f}=h(this,Ga);R(this,Bv,[(f[0]-a)/d,(f[1]-l)/c])},nK=function(t){const r=(a,l)=>{this.color=a,this.opacity=l,this.onUpdatedColor()},i=this.color,o=this.opacity;this.addCommands({cmd:r.bind(this,t,Rr._defaultOpacity),undo:r.bind(this,i,o),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)},rK=function(t){const r=h(this,wd),i=o=>{R(this,wd,o),q(this,Un,iK).call(this,o)};this.addCommands({cmd:i.bind(this,t),undo:i.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)},iK=function(t){h(this,_o)&&(q(this,Un,iA).call(this,{highlightOutlines:h(this,Fl).getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())},eM=function(){h(this,Dl)===null||!this.parent||(this.parent.drawLayer.remove(h(this,Dl)),R(this,Dl,null),this.parent.drawLayer.remove(h(this,ea)),R(this,ea,null))},cm=function(t=this.parent){h(this,Dl)===null&&({id:Gi(this,Dl)._,clipPathId:Gi(this,Hy)._}=t.drawLayer.draw({bbox:h(this,Fl).box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.opacity},rootClass:{highlight:!0,free:h(this,_o)},path:{d:h(this,Fl).toSVGPath()}},!1,!0),R(this,ea,t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:h(this,_o)},bbox:h(this,Ga).box,path:{d:h(this,Ga).toSVGPath()}},h(this,_o))),h(this,qy)&&(h(this,qy).style.clipPath=h(this,Hy)))},Fd=new WeakSet,Fx=function([t,r,i,o],a){switch(a){case 90:return[1-r-o,t,o,i];case 180:return[1-t-i,1-r-o,i,o];case 270:return[r,1-t-i,o,i]}return[t,r,i,o]},sK=function(t){Rr._keyboardManager.exec(this,t)},sA=function(t){if(!h(this,Pv))return;const r=window.getSelection();t?r.setPosition(h(this,Pv),h(this,D_)):r.setPosition(h(this,P_),h(this,R_))},oA=function(){return h(this,_o)?this.rotation:0},oK=function(){if(h(this,_o))return null;const[t,r]=this.pageDimensions,[i,o]=this.pageTranslation,a=h(this,nf),l=new Float32Array(a.length*8);let d=0;for(const{x:c,y:u,width:f,height:p}of a){const g=c*t+i,m=(1-u)*r+o;l[d]=l[d+4]=g,l[d+1]=l[d+3]=m,l[d+2]=l[d+6]=g+f*t,l[d+5]=l[d+7]=m-p*r,d+=8}return l},aK=function(t){return h(this,Fl).serialize(t,q(this,Un,oA).call(this))},lK=function(t,r){this._freeHighlight.add(r)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})},dK=function(t,r){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(r,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},cK=function(t){const{color:r}=this._initialData;return this.hasEditedComment||t.color.some((i,o)=>i!==r[o])},N(Rr,Fd),ve(Rr,"_defaultColor",null),ve(Rr,"_defaultOpacity",1),ve(Rr,"_defaultThickness",12),ve(Rr,"_type","highlight"),ve(Rr,"_editorType",jn.HIGHLIGHT),ve(Rr,"_freeHighlightId",-1),ve(Rr,"_freeHighlight",null),ve(Rr,"_freeHighlightClipId","");let CT=Rr;var Vy;class uK{constructor(){N(this,Vy,Object.create(null))}updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(const[t,r]of Object.entries(e))t.startsWith("_")||this.updateProperty(t,r)}updateSVGProperty(e,t){h(this,Vy)[e]=t}toSVGProperties(){const e=h(this,Vy);return R(this,Vy,Object.create(null)),{root:e}}reset(){R(this,Vy,Object.create(null))}updateAll(e=this){this.updateProperties(e)}clone(){Hr("Not implemented")}}Vy=new WeakMap;var ma,Mv,io,Gy,Ky,kr,tM,nM,rM,FS,hK,aA,DS,Dx;const rr=class rr extends xi{constructor(t){super(t);N(this,kr);N(this,ma,null);N(this,Mv);ve(this,"_colorPicker",null);ve(this,"_drawId",null);R(this,Mv,t.mustBeCommitted||!1),this._addOutlines(t)}onUpdatedColor(){var t;(t=this._colorPicker)==null||t.update(this.color),super.onUpdatedColor()}onUpdatedOpacity(){var t,r;(r=(t=this._colorPicker)==null?void 0:t.updateOpacity)==null||r.call(t,this.opacity)}_addOutlines(t){t.drawOutlines&&(q(this,kr,tM).call(this,t),q(this,kr,FS).call(this))}static _mergeSVGProperties(t,r){const i=new Set(Object.keys(t));for(const[o,a]of Object.entries(r))i.has(o)?Object.assign(t[o],a):t[o]=a;return t}static getDefaultDrawingOptions(t){Hr("Not implemented")}static get typesMap(){Hr("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,r){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,r),this._currentParent&&(h(rr,io).updateProperty(i,r),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,r){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,r)}static get defaultPropertiesToUpdate(){const t=[],r=this._defaultDrawingOptions;for(const[i,o]of this.typesMap)t.push([i,r[o]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:r}=this;for(const[i,o]of this.constructor.typesMap)t.push([i,r[o]]);return t}_updateProperty(t,r,i){const o=this._drawingOptions,a=o[r],l=d=>{var u;o.updateProperty(r,d);const c=h(this,ma).updateProperty(r,d);c&&q(this,kr,DS).call(this,c),(u=this.parent)==null||u.drawLayer.updateProperties(this._drawId,o.toSVGProperties()),t===this.colorType?this.onUpdatedColor():t===this.opacityType&&this.onUpdatedOpacity()};this.addCommands({cmd:l.bind(this,i),undo:l.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_updateColorAndOpacity(t,r){const i=this.constructor.typesMap.get(this.colorType),o=this.constructor.typesMap.get(this.opacityType),a=this._drawingOptions,l=a[i],d=a[o],c=(u,f)=>{var p;a.updateProperty(i,u),a.updateProperty(o,f),h(this,ma).updateProperty(i,u),h(this,ma).updateProperty(o,f),(p=this.parent)==null||p.drawLayer.updateProperties(this._drawId,a.toSVGProperties()),this.onUpdatedColor(),this.onUpdatedOpacity()};this.addCommands({cmd:c.bind(this,t,r),undo:c.bind(this,l,d),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Wn.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties(h(this,ma).getPathResizingSVGProperties(q(this,kr,aA).call(this)),{bbox:q(this,kr,Dx).call(this)}))}_onResized(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties(h(this,ma).getPathResizedSVGProperties(q(this,kr,aA).call(this)),{bbox:q(this,kr,Dx).call(this)}))}_onTranslating(t,r){var i;(i=this.parent)==null||i.drawLayer.updateProperties(this._drawId,{bbox:q(this,kr,Dx).call(this)})}_onTranslated(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties(h(this,ma).getPathTranslatedSVGProperties(q(this,kr,aA).call(this),this.parentDimensions),{bbox:q(this,kr,Dx).call(this)}))}_onStartDragging(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,h(this,Mv)&&(R(this,Mv,!1),this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){q(this,kr,rM).call(this),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(q(this,kr,FS).call(this),q(this,kr,DS).call(this,h(this,ma).box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let r=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),q(this,kr,rM).call(this)):t&&(this._uiManager.addShouldRescale(this),q(this,kr,FS).call(this,t),r=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(t),r&&this.select()}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,rr._mergeSVGProperties({bbox:q(this,kr,Dx).call(this)},h(this,ma).updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&q(this,kr,DS).call(this,h(this,ma).updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let t,r;this._isCopy&&(t=this.x,r=this.y);const i=super.render();i.classList.add("draw");const o=document.createElement("div");return i.append(o),o.setAttribute("aria-hidden","true"),o.className="internal",this.setDims(),this._uiManager.addShouldRescale(this),this.disableEditing(),this._isCopy&&this._moveAfterPaste(t,r),i}static createDrawerInstance(t,r,i,o,a){Hr("Not implemented")}static startDrawing(t,r,i,o){var v;const{target:a,offsetX:l,offsetY:d,pointerId:c,pointerType:u}=o;if(Yo.isInitializedAndDifferentPointerType(u))return;const{viewport:{rotation:f}}=t,{width:p,height:g}=a.getBoundingClientRect(),m=R(rr,Gy,new AbortController),y=t.combinedSignal(m);if(Yo.setPointer(u,c),window.addEventListener("pointerup",x=>{Yo.isSamePointerIdOrRemove(x.pointerId)&&this._endDraw(x)},{signal:y}),window.addEventListener("pointercancel",x=>{Yo.isSamePointerIdOrRemove(x.pointerId)&&this._currentParent.endDrawingSession()},{signal:y}),window.addEventListener("pointerdown",x=>{Yo.isSamePointerType(x.pointerType)&&(Yo.initializeAndAddPointerId(x.pointerId),h(rr,io).isCancellable()&&(h(rr,io).removeLastElement(),h(rr,io).isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:y}),window.addEventListener("contextmenu",Hd,{signal:y}),a.addEventListener("pointermove",this._drawMove.bind(this),{signal:y}),a.addEventListener("touchmove",x=>{Yo.isSameTimeStamp(x.timeStamp)&&$i(x)},{signal:y}),t.toggleDrawing(),(v=r._editorUndoBar)==null||v.hide(),h(rr,io)){t.drawLayer.updateProperties(this._currentDrawId,h(rr,io).startNew(l,d,p,g,f));return}r.updateUIForDefaultProperties(this),R(rr,io,this.createDrawerInstance(l,d,p,g,f)),R(rr,Ky,this.getDefaultDrawingOptions()),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(h(rr,Ky).toSVGProperties(),h(rr,io).defaultSVGProperties),!0,!1)}static _drawMove(t){if(Yo.isSameTimeStamp(t.timeStamp),!h(rr,io))return;const{offsetX:r,offsetY:i,pointerId:o}=t;if(Yo.isSamePointerId(o)){if(Yo.isUsingMultiplePointers()){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,h(rr,io).add(r,i)),Yo.setTimeStamp(t.timeStamp),$i(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,R(rr,io,null),R(rr,Ky,null),Yo.clearTimeStamp()),h(rr,Gy)&&(h(rr,Gy).abort(),R(rr,Gy,null),Yo.clearPointerIds())}static _endDraw(t){const r=this._currentParent;if(r){if(r.toggleDrawing(!0),this._cleanup(!1),(t==null?void 0:t.target)===r.div&&r.drawLayer.updateProperties(this._currentDrawId,h(rr,io).end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const i=h(rr,io),o=this._currentDrawId,a=i.getLastElement();r.addCommands({cmd:()=>{r.drawLayer.updateProperties(o,i.setLastElement(a))},undo:()=>{r.drawLayer.updateProperties(o,i.removeLastElement())},mustExec:!1,type:Wn.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const r=this._currentParent;if(!r)return null;if(r.toggleDrawing(!0),r.cleanUndoStack(Wn.DRAW_STEP),!h(rr,io).isEmpty()){const{pageDimensions:[i,o],scale:a}=r,l=r.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:h(rr,io).getOutlines(i*a,o*a,a,this._INNER_MARGIN),drawingOptions:h(rr,Ky),mustBeCommitted:!t});return this._cleanup(!0),l}return r.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,r,i,o,a,l){Hr("Not implemented")}static async deserialize(t,r,i){var f,p;const{rawDims:{pageWidth:o,pageHeight:a,pageX:l,pageY:d}}=r.viewport,c=this.deserializeDraw(l,d,o,a,this._INNER_MARGIN,t),u=await super.deserialize(t,r,i);return u.createDrawingOptions(t),q(f=u,kr,tM).call(f,{drawOutlines:c}),q(p=u,kr,FS).call(p),u.onScaleChanging(),u.rotate(),u}serializeDraw(t){const[r,i]=this.pageTranslation,[o,a]=this.pageDimensions;return h(this,ma).serialize([r,i,o,a],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}};ma=new WeakMap,Mv=new WeakMap,io=new WeakMap,Gy=new WeakMap,Ky=new WeakMap,kr=new WeakSet,tM=function({drawOutlines:t,drawId:r,drawingOptions:i}){R(this,ma,t),this._drawingOptions||(this._drawingOptions=i),this.annotationElementId||this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`),r>=0?(this._drawId=r,this.parent.drawLayer.finalizeDraw(r,t.defaultProperties)):this._drawId=q(this,kr,nM).call(this,t,this.parent),q(this,kr,DS).call(this,t.box)},nM=function(t,r){const{id:i}=r.drawLayer.draw(rr._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i},rM=function(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())},FS=function(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=q(this,kr,nM).call(this,h(this,ma),t)}},hK=function([t,r,i,o]){const{parentDimensions:[a,l],rotation:d}=this;switch(d){case 90:return[r,1-t,i*(l/a),o*(a/l)];case 180:return[1-t,1-r,i,o];case 270:return[1-r,t,i*(l/a),o*(a/l)];default:return[t,r,i,o]}},aA=function(){const{x:t,y:r,width:i,height:o,parentDimensions:[a,l],rotation:d}=this;switch(d){case 90:return[1-r,t,i*(a/l),o*(l/a)];case 180:return[1-t,1-r,i,o];case 270:return[r,1-t,i*(a/l),o*(l/a)];default:return[t,r,i,o]}},DS=function(t){[this.x,this.y,this.width,this.height]=q(this,kr,hK).call(this,t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()},Dx=function(){const{x:t,y:r,width:i,height:o,rotation:a,parentRotation:l,parentDimensions:[d,c]}=this;switch((a*4+l)/90){case 1:return[1-r-o,t,o,i];case 2:return[1-t-i,1-r-o,i,o];case 3:return[r,1-t-i,o,i];case 4:return[t,r-i*(d/c),o*(c/d),i*(d/c)];case 5:return[1-r,t,i*(d/c),o*(c/d)];case 6:return[1-t-o*(c/d),1-r,o*(c/d),i*(d/c)];case 7:return[r-i*(d/c),1-t-o*(c/d),i*(d/c),o*(c/d)];case 8:return[t-i,r-o,i,o];case 9:return[1-r,t-i,o,i];case 10:return[1-t,1-r,i,o];case 11:return[r-o,1-t,o,i];case 12:return[t-o*(c/d),r,o*(c/d),i*(d/c)];case 13:return[1-r-i*(d/c),t-o*(c/d),i*(d/c),o*(c/d)];case 14:return[1-t,1-r-i*(d/c),o*(c/d),i*(d/c)];case 15:return[r,1-t,i*(d/c),o*(c/d)];default:return[t,r,i,o]}},ve(rr,"_currentDrawId",-1),ve(rr,"_currentParent",null),N(rr,io,null),N(rr,Gy,null),N(rr,Ky,null),ve(rr,"_INNER_MARGIN",3);let AT=rr;var xu,so,oo,Xy,zv,ya,Co,Sd,Yy,Qy,$y,Ov,lA;class Hhe{constructor(e,t,r,i,o,a){N(this,Ov);N(this,xu,new Float64Array(6));N(this,so);N(this,oo);N(this,Xy);N(this,zv);N(this,ya);N(this,Co,"");N(this,Sd,0);N(this,Yy,new hC);N(this,Qy);N(this,$y);R(this,Qy,r),R(this,$y,i),R(this,Xy,o),R(this,zv,a),[e,t]=q(this,Ov,lA).call(this,e,t);const l=R(this,so,[NaN,NaN,NaN,NaN,e,t]);R(this,ya,[e,t]),R(this,oo,[{line:l,points:h(this,ya)}]),h(this,xu).set(l,0)}updateProperty(e,t){e==="stroke-width"&&R(this,zv,t)}isEmpty(){return!h(this,oo)||h(this,oo).length===0}isCancellable(){return h(this,ya).length<=10}add(e,t){[e,t]=q(this,Ov,lA).call(this,e,t);const[r,i,o,a]=h(this,xu).subarray(2,6),l=e-o,d=t-a;return Math.hypot(h(this,Qy)*l,h(this,$y)*d)<=2?null:(h(this,ya).push(e,t),isNaN(r)?(h(this,xu).set([o,a,e,t],2),h(this,so).push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(h(this,xu)[0])&&h(this,so).splice(6,6),h(this,xu).set([r,i,o,a,e,t],0),h(this,so).push(...Wt.createBezierPoints(r,i,o,a,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){const r=this.add(e,t);return r||(h(this,ya).length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,r,i,o){R(this,Qy,r),R(this,$y,i),R(this,Xy,o),[e,t]=q(this,Ov,lA).call(this,e,t);const a=R(this,so,[NaN,NaN,NaN,NaN,e,t]);R(this,ya,[e,t]);const l=h(this,oo).at(-1);return l&&(l.line=new Float32Array(l.line),l.points=new Float32Array(l.points)),h(this,oo).push({line:a,points:h(this,ya)}),h(this,xu).set(a,0),R(this,Sd,0),this.toSVGPath(),null}getLastElement(){return h(this,oo).at(-1)}setLastElement(e){return h(this,oo)?(h(this,oo).push(e),R(this,so,e.line),R(this,ya,e.points),R(this,Sd,0),{path:{d:this.toSVGPath()}}):h(this,Yy).setLastElement(e)}removeLastElement(){if(!h(this,oo))return h(this,Yy).removeLastElement();h(this,oo).pop(),R(this,Co,"");for(let e=0,t=h(this,oo).length;e_??NaN),p,g,m,y),points:v(d[w].map(_=>_??NaN),p,g,m,y)});const x=new this.prototype.constructor;return x.build(f,i,o,1,c,u,a),x}get box(){return h(this,xa)}updateProperty(t,r){return t==="stroke-width"?q(this,Fo,gK).call(this,r):null}updateParentDimensions([t,r],i){const[o,a]=q(this,Fo,ph).call(this);R(this,bu,t),R(this,vu,r),R(this,Lv,i);const[l,d]=q(this,Fo,ph).call(this),c=l-o,u=d-a,f=h(this,xa);return f[0]-=c,f[1]-=u,f[2]+=2*c,f[3]+=2*u,f}updateRotation(t){return R(this,I_,t),{path:{transform:this.rotationTransform}}}get viewBox(){return h(this,xa).map(Wt.svgRound).join(" ")}get defaultProperties(){const[t,r]=h(this,xa);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`}}}get rotationTransform(){const[,,t,r]=h(this,xa);let i=0,o=0,a=0,l=0,d=0,c=0;switch(h(this,I_)){case 90:o=r/t,a=-t/r,d=t;break;case 180:i=-1,l=-1,d=t,c=r;break;case 270:o=-r/t,a=t/r,c=r;break;default:return""}return`matrix(${i} ${o} ${a} ${l} ${Wt.svgRound(d)} ${Wt.svgRound(c)})`}getPathResizingSVGProperties([t,r,i,o]){const[a,l]=q(this,Fo,ph).call(this),[d,c,u,f]=h(this,xa);if(Math.abs(u-a)<=Wt.PRECISION||Math.abs(f-l)<=Wt.PRECISION){const v=t+i/2-(d+u/2),x=r+o/2-(c+f/2);return{path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`,transform:`${this.rotationTransform} translate(${v} ${x})`}}}const p=(i-2*a)/(u-2*a),g=(o-2*l)/(f-2*l),m=u/i,y=f/o;return{path:{"transform-origin":`${Wt.svgRound(d)} ${Wt.svgRound(c)}`,transform:`${this.rotationTransform} scale(${m} ${y}) translate(${Wt.svgRound(a)} ${Wt.svgRound(l)}) scale(${p} ${g}) translate(${Wt.svgRound(-a)} ${Wt.svgRound(-l)})`}}}getPathResizedSVGProperties([t,r,i,o]){const[a,l]=q(this,Fo,ph).call(this),d=h(this,xa),[c,u,f,p]=d;if(d[0]=t,d[1]=r,d[2]=i,d[3]=o,Math.abs(f-a)<=Wt.PRECISION||Math.abs(p-l)<=Wt.PRECISION){const x=t+i/2-(c+f/2),w=r+o/2-(u+p/2);for(const{line:S,points:_}of h(this,El))Wt._translate(S,x,w,S),Wt._translate(_,x,w,_);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const g=(i-2*a)/(f-2*a),m=(o-2*l)/(p-2*l),y=-g*(c+a)+t+a,v=-m*(u+l)+r+l;if(g!==1||m!==1||y!==0||v!==0)for(const{line:x,points:w}of h(this,El))Wt._rescale(x,y,v,g,m,x),Wt._rescale(w,y,v,g,m,w);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,r],i){const[o,a]=i,l=h(this,xa),d=t-l[0],c=r-l[1];if(h(this,bu)===o&&h(this,vu)===a)for(const{line:u,points:f}of h(this,El))Wt._translate(u,d,c,u),Wt._translate(f,d,c,f);else{const u=h(this,bu)/o,f=h(this,vu)/a;R(this,bu,o),R(this,vu,a);for(const{line:p,points:g}of h(this,El))Wt._rescale(p,d,c,u,f,p),Wt._rescale(g,d,c,u,f,g);l[2]*=u,l[3]*=f}return l[0]=t,l[1]=r,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Wt.svgRound(t)} ${Wt.svgRound(r)}`}}}get defaultSVGProperties(){const t=h(this,xa);return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Wt.svgRound(t[0])} ${Wt.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}xa=new WeakMap,I_=new WeakMap,M_=new WeakMap,El=new WeakMap,bu=new WeakMap,vu=new WeakMap,Lv=new WeakMap,Nv=new WeakMap,Zy=new WeakMap,Fo=new WeakSet,ph=function(t=h(this,Zy)){const r=h(this,M_)+t/2*h(this,Lv);return h(this,Nv)%180===0?[r/h(this,bu),r/h(this,vu)]:[r/h(this,vu),r/h(this,bu)]},fK=function(){const[t,r,i,o]=h(this,xa),[a,l]=q(this,Fo,ph).call(this,0);return[t+a,r+l,i-2*a,o-2*l]},pK=function(){const t=R(this,xa,_m.slice());for(const{line:o}of h(this,El)){if(o.length<=12){for(let d=4,c=o.length;dl!==r[d])||t.thickness!==i||t.opacity!==o||t.pageIndex!==a},ve($x,"_type","ink"),ve($x,"_editorType",jn.INK),ve($x,"_defaultDrawingOptions",null);let iM=$x;class sM extends hC{toSVGPath(){let e=super.toSVGPath();return e.endsWith("Z")||(e+="Z"),e}}const $2=8,Gw=3;var Jy,Vr,oM,vc,yK,xK,aM,dA,bK,vK,wK,lM,dM,SK;class df{static extractContoursFromText(e,{fontFamily:t,fontStyle:r,fontWeight:i},o,a,l,d){let c=new OffscreenCanvas(1,1),u=c.getContext("2d",{alpha:!1});const f=200,p=u.font=`${r} ${i} ${f}px ${t}`,{actualBoundingBoxLeft:g,actualBoundingBoxRight:m,actualBoundingBoxAscent:y,actualBoundingBoxDescent:v,fontBoundingBoxAscent:x,fontBoundingBoxDescent:w,width:S}=u.measureText(e),_=1.5,b=Math.ceil(Math.max(Math.abs(g)+Math.abs(m)||0,S)*_),C=Math.ceil(Math.max(Math.abs(y)+Math.abs(v)||f,Math.abs(x)+Math.abs(w)||f)*_);c=new OffscreenCanvas(b,C),u=c.getContext("2d",{alpha:!0,willReadFrequently:!0}),u.font=p,u.filter="grayscale(1)",u.fillStyle="white",u.fillRect(0,0,b,C),u.fillStyle="black",u.fillText(e,b*(_-1)/2,C*(3-_)/2);const T=q(this,Vr,lM).call(this,u.getImageData(0,0,b,C).data),F=q(this,Vr,wK).call(this,T),A=q(this,Vr,dM).call(this,F),D=q(this,Vr,aM).call(this,T,b,C,A);return this.processDrawnLines({lines:{curves:D,width:b,height:C},pageWidth:o,pageHeight:a,rotation:l,innerMargin:d,mustSmooth:!0,areContours:!0})}static process(e,t,r,i,o){const[a,l,d]=q(this,Vr,SK).call(this,e),[c,u]=q(this,Vr,vK).call(this,a,l,d,Math.hypot(l,d)*h(this,Jy).sigmaSFactor,h(this,Jy).sigmaR,h(this,Jy).kernelSize),f=q(this,Vr,dM).call(this,u),p=q(this,Vr,aM).call(this,c,l,d,f);return this.processDrawnLines({lines:{curves:p,width:l,height:d},pageWidth:t,pageHeight:r,rotation:i,innerMargin:o,mustSmooth:!0,areContours:!0})}static processDrawnLines({lines:e,pageWidth:t,pageHeight:r,rotation:i,innerMargin:o,mustSmooth:a,areContours:l}){i%180!==0&&([t,r]=[r,t]);const{curves:d,width:c,height:u}=e,f=e.thickness??0,p=[],g=Math.min(t/c,r/u),m=g/t,y=g/r,v=[];for(const{points:w}of d){const S=a?q(this,Vr,bK).call(this,w):w;if(!S)continue;v.push(S);const _=S.length,b=new Float32Array(_),C=new Float32Array(3*(_===2?2:_-2));if(p.push({line:C,points:b}),_===2){b[0]=S[0]*m,b[1]=S[1]*y,C.set([NaN,NaN,NaN,NaN,b[0],b[1]],0);continue}let[T,F,A,D]=S;T*=m,F*=y,A*=m,D*=y,b.set([T,F,A,D],0),C.set([NaN,NaN,NaN,NaN,T,F],0);for(let P=4;P<_;P+=2){const L=b[P]=S[P]*m,W=b[P+1]=S[P+1]*y;C.set(Wt.createBezierPoints(T,F,A,D,L,W),(P-2)*3),[T,F,A,D]=[A,D,L,W]}}if(p.length===0)return null;const x=l?new sM:new hC;return x.build(p,t,r,1,i,l?0:f,o),{outline:x,newCurves:v,areContours:l,thickness:f,width:c,height:u}}static async compressSignature({outlines:e,areContours:t,thickness:r,width:i,height:o}){let a=1/0,l=-1/0,d=0;for(const w of e){d+=w.length;for(let S=2,_=w.length;S<_;S++){const b=w[S]-w[S-2];a=Math.min(a,b),l=Math.max(l,b)}}let c;a>=-128&&l<=127?c=Int8Array:a>=-32768&&l<=32767?c=Int16Array:c=Int32Array;const u=e.length,f=$2+Gw*u,p=new Uint32Array(f);let g=0;p[g++]=f*Uint32Array.BYTES_PER_ELEMENT+(d-2*u)*c.BYTES_PER_ELEMENT,p[g++]=0,p[g++]=i,p[g++]=o,p[g++]=t?0:1,p[g++]=Math.max(0,Math.floor(r??0)),p[g++]=u,p[g++]=c.BYTES_PER_ELEMENT;for(const w of e)p[g++]=w.length-2,p[g++]=w[0],p[g++]=w[1];const m=new CompressionStream("deflate-raw"),y=m.writable.getWriter();await y.ready,y.write(p);const v=c.prototype.constructor;for(const w of e){const S=new v(w.length-2);for(let _=2,b=w.length;_{await o.ready,await o.close()}).catch(()=>{});let a=null,l=0;for await(const S of r)a||(a=new Uint8Array(new Uint32Array(S.buffer,0,4)[0])),a.set(S,l),l+=S.length;const d=new Uint32Array(a.buffer,0,a.length>>2),c=d[1];if(c!==0)throw new Error(`Invalid version: ${c}`);const u=d[2],f=d[3],p=d[4]===0,g=d[5],m=d[6],y=d[7],v=[],x=($2+Gw*m)*Uint32Array.BYTES_PER_ELEMENT;let w;switch(y){case Int8Array.BYTES_PER_ELEMENT:w=new Int8Array(a.buffer,x);break;case Int16Array.BYTES_PER_ELEMENT:w=new Int16Array(a.buffer,x);break;case Int32Array.BYTES_PER_ELEMENT:w=new Int32Array(a.buffer,x);break}l=0;for(let S=0;S0?0:4:r===1?i+6:2-i},vc=new WeakMap,yK=function(e,t,r,i,o,a,l){const d=q(this,Vr,oM).call(this,r,i,o,a);for(let c=0;c<8;c++){const u=(-c+d-l+16)%8,f=h(this,vc)[2*u],p=h(this,vc)[2*u+1];if(e[(r+f)*t+(i+p)]!==0)return u}return-1},xK=function(e,t,r,i,o,a,l){const d=q(this,Vr,oM).call(this,r,i,o,a);for(let c=0;c<8;c++){const u=(c+d+l+16)%8,f=h(this,vc)[2*u],p=h(this,vc)[2*u+1];if(e[(r+f)*t+(i+p)]!==0)return u}return-1},aM=function(e,t,r,i){const o=e.length,a=new Int32Array(o);for(let u=0;u=1&&a[p+1]===0)l+=1,y+=1,g>1&&(d=g);else{g!==1&&(d=Math.abs(g));continue}const v=[f,u],x=y===f+1,w={isHole:x,points:v,id:l,parent:0};c.push(w);let S;for(const P of c)if(P.id===d){S=P;break}S?S.isHole?w.parent=x?S.parent:d:w.parent=x?d:S.parent:w.parent=x?d:0;const _=q(this,Vr,yK).call(this,a,t,u,f,m,y,0);if(_===-1){a[p]=-l,a[p]!==1&&(d=Math.abs(a[p]));continue}let b=h(this,vc)[2*_],C=h(this,vc)[2*_+1];const T=u+b,F=f+C;m=T,y=F;let A=u,D=f;for(;;){const P=q(this,Vr,xK).call(this,a,t,A,D,m,y,1);b=h(this,vc)[2*P],C=h(this,vc)[2*P+1];const L=A+b,W=D+C;v.push(W,L);const O=A*t+D;if(a[O+1]===0?a[O]=-l:a[O]===1&&(a[O]=l),L===u&&W===f&&A===T&&D===F){a[p]!==1&&(d=Math.abs(a[p]));break}else m=A,y=D,A=L,D=W}}}return c},dA=function(e,t,r,i){if(r-t<=4){for(let T=t;Tb&&(C=T,b=F)}b>(c*_)**2?(q(this,Vr,dA).call(this,e,t,C+2,i),q(this,Vr,dA).call(this,e,C,r,i)):i.push(o,a)},bK=function(e){const t=[],r=e.length;return q(this,Vr,dA).call(this,e,0,r,t),t.push(e[r-2],e[r-1]),t.length<=4?null:t},vK=function(e,t,r,i,o,a){const l=new Float32Array(a**2),d=-2*i**2,c=a>>1;for(let y=0;y=r))for(let F=0;F=t)continue;const D=e[T*t+A],P=l[C*a+F]*u[Math.abs(D-w)];S+=D*P,_+=P}}const b=g[x]=Math.round(S/_);m[b]++}return[g,m]},wK=function(e){const t=new Uint32Array(256);for(const r of e)t[r]++;return t},lM=function(e){const t=e.length,r=new Uint8ClampedArray(t>>2);let i=-1/0,o=1/0;for(let l=0,d=r.length;ld!==0);let a=o,l=o;for(t=o;t<256;t++){const d=e[t];d>r&&(t-a>i&&(i=t-a,l=t-1),r=d,a=t)}for(t=l-1;t>=0&&!(e[t]>e[t+1]);t--);return t},SK=function(e){const t=e,{width:r,height:i}=e,{maxDim:o}=h(this,Jy);let a=r,l=i;if(r>o||i>o){let p=r,g=i,m=Math.log2(Math.max(r,i)/o);const y=Math.floor(m);m=m===y?y-1:y;for(let x=0;x{r==null||r.updateEditSignatureButton(t)}))}getSignaturePreview(){const{newCurves:t,areContours:r,thickness:i,width:o,height:a}=h(this,tg),l=Math.max(o,a),d=df.processDrawnLines({lines:{curves:t.map(c=>({points:c})),thickness:i,width:o,height:a},pageWidth:l,pageHeight:l,rotation:0,innerMargin:0,mustSmooth:!1,areContours:r});return{areContours:r,outline:d.outline}}get toolbarButtons(){return this._uiManager.signatureManager?[["editSignature",this._uiManager.signatureManager]]:super.toolbarButtons}addSignature(t,r,i,o){const{x:a,y:l}=this,{outline:d}=R(this,tg,t);R(this,eg,d instanceof sM),this.description=i;let c;h(this,eg)?c=gl.getDefaultDrawingOptions():(c=gl._defaultDrawnSignatureOptions.clone(),c.updateProperties({"stroke-width":d.thickness})),this._addOutlines({drawOutlines:d,drawingOptions:c});const[,u]=this.pageDimensions;let f=r/u;f=f>=1?.5:f,this.width*=f/this.height,this.width>=1&&(f*=.9/this.width,this.width=.9),this.height=f,this.setDims(),this.x=a,this.y=l,this.center(),this._onResized(),this.onScaleChanging(),this.rotate(),this._uiManager.addToAnnotationStorage(this),this.setUuid(o),this._reportTelemetry({action:"pdfjs.signature.inserted",data:{hasBeenSaved:!!o,hasDescription:!!i}}),this.div.hidden=!1}getFromImage(t){const{rawDims:{pageWidth:r,pageHeight:i},rotation:o}=this.parent.viewport;return df.process(t,r,i,o,gl._INNER_MARGIN)}getFromText(t,r){const{rawDims:{pageWidth:i,pageHeight:o},rotation:a}=this.parent.viewport;return df.extractContoursFromText(t,r,i,o,a,gl._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:r,pageHeight:i},rotation:o}=this.parent.viewport;return df.processDrawnLines({lines:t,pageWidth:r,pageHeight:i,rotation:o,innerMargin:gl._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:r}){t?this._drawingOptions=gl.getDefaultDrawingOptions():(this._drawingOptions=gl._defaultDrawnSignatureOptions.clone(),this._drawingOptions.updateProperties({"stroke-width":r}))}serialize(t=!1){if(this.isEmpty())return null;const{lines:r,points:i}=this.serializeDraw(t),{_drawingOptions:{"stroke-width":o}}=this,a=Object.assign(super.serialize(t),{isSignature:!0,areContours:h(this,eg),color:[0,0,0],thickness:h(this,eg)?0:o});return this.addComment(a),t?(a.paths={lines:r,points:i},a.uuid=h(this,e0),a.isCopy=!0):a.lines=r,h(this,wu)&&(a.accessibilityData={type:"Figure",alt:h(this,wu)}),a}static deserializeDraw(t,r,i,o,a,l){return l.areContours?sM.deserialize(t,r,i,o,a,l):hC.deserialize(t,r,i,o,a,l)}static async deserialize(t,r,i){var a;const o=await super.deserialize(t,r,i);return R(o,eg,t.areContours),o.description=((a=t.accessibilityData)==null?void 0:a.alt)||"",R(o,e0,t.uuid),o}};eg=new WeakMap,wu=new WeakMap,tg=new WeakMap,e0=new WeakMap,ve(gl,"_type","signature"),ve(gl,"_editorType",jn.SIGNATURE),ve(gl,"_defaultDrawingOptions",null);let cM=gl;var Ri,ao,ng,rf,rg,Wv,sf,t0,Su,Pl,Uv,_r,ES,PS,cA,uA,hA,hM,fA,jK;class uM extends xi{constructor(t){super({...t,name:"stampEditor"});N(this,_r);N(this,Ri,null);N(this,ao,null);N(this,ng,null);N(this,rf,null);N(this,rg,null);N(this,Wv,"");N(this,sf,null);N(this,t0,!1);N(this,Su,null);N(this,Pl,!1);N(this,Uv,!1);R(this,rf,t.bitmapUrl),R(this,rg,t.bitmapFile),this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,r){xi.initialize(t,r)}static isHandlingMimeForPasting(t){return $B.includes(t)}static paste(t,r){r.pasteEditor({mode:jn.STAMP},{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var t;return{type:"stamp",hasAltText:!!((t=this.altTextData)!=null&&t.altText)}}static computeTelemetryFinalData(t){const r=t.get("hasAltText");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}async mlGuessAltText(t=null,r=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:o,width:a,height:l}=t||this.copyCanvas(null,null,!0).imageData,d=await i.guess({name:"altText",request:{data:o,width:a,height:l,channels:o.length/(a*l)}});if(!d)throw new Error("No response from the AI service.");if(d.error)throw new Error("Error from the AI service.");if(d.cancel)return null;if(!d.output)throw new Error("No valid response from the AI service.");const c=d.output;return await this.setGuessedAltText(c),r&&!this.hasAltTextData()&&(this.altTextData={alt:c,decorative:!1}),c}remove(){var t;h(this,ao)&&(R(this,Ri,null),this._uiManager.imageManager.deleteId(h(this,ao)),(t=h(this,sf))==null||t.remove(),R(this,sf,null),h(this,Su)&&(clearTimeout(h(this,Su)),R(this,Su,null))),super.remove()}rebuild(){if(!this.parent){h(this,ao)&&q(this,_r,cA).call(this);return}super.rebuild(),this.div!==null&&(h(this,ao)&&h(this,sf)===null&&q(this,_r,cA).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(h(this,ng)||h(this,Ri)||h(this,rf)||h(this,rg)||h(this,ao)||h(this,t0))}get toolbarButtons(){return[["altText",this.createAltText()]]}get isResizable(){return!0}render(){if(this.div)return this.div;let t,r;return this._isCopy&&(t=this.x,r=this.y),super.render(),this.div.hidden=!0,this.createAltText(),h(this,t0)||(h(this,Ri)?q(this,_r,uA).call(this):q(this,_r,cA).call(this)),this._isCopy&&this._moveAfterPaste(t,r),this._uiManager.addShouldRescale(this),this.div}setCanvas(t,r){const{id:i,bitmap:o}=this._uiManager.imageManager.getFromCanvas(t,r);r.remove(),i&&this._uiManager.imageManager.isValidId(i)&&(R(this,ao,i),o&&R(this,Ri,o),R(this,t0,!1),q(this,_r,uA).call(this))}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;h(this,Su)!==null&&clearTimeout(h(this,Su)),R(this,Su,setTimeout(()=>{R(this,Su,null),q(this,_r,hM).call(this)},200))}copyCanvas(t,r,i=!1){t||(t=224);const{width:o,height:a}=h(this,Ri),l=new Lu;let d=h(this,Ri),c=o,u=a,f=null;if(r){if(o>r||a>r){const T=Math.min(r/o,r/a);c=Math.floor(o*T),u=Math.floor(a*T)}f=document.createElement("canvas");const g=f.width=Math.ceil(c*l.sx),m=f.height=Math.ceil(u*l.sy);h(this,Pl)||(d=q(this,_r,hA).call(this,g,m));const y=f.getContext("2d");y.filter=this._uiManager.hcmFilter;let v="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":rue.isDarkMode&&(v="#8f8f9d",x="#42414d");const w=15,S=w*l.sx,_=w*l.sy,b=new OffscreenCanvas(S*2,_*2),C=b.getContext("2d");C.fillStyle=v,C.fillRect(0,0,S*2,_*2),C.fillStyle=x,C.fillRect(0,0,S,_),C.fillRect(S,_,S,_),y.fillStyle=y.createPattern(b,"repeat"),y.fillRect(0,0,g,m),y.drawImage(d,0,0,d.width,d.height,0,0,g,m)}let p=null;if(i){let g,m;if(l.symmetric&&d.widtht||a>t){const x=Math.min(t/o,t/a);g=Math.floor(o*x),m=Math.floor(a*x),h(this,Pl)||(d=q(this,_r,hA).call(this,g,m))}const v=new OffscreenCanvas(g,m).getContext("2d",{willReadFrequently:!0});v.drawImage(d,0,0,d.width,d.height,0,0,g,m),p={width:g,height:m,data:v.getImageData(0,0,g,m).data}}return{canvas:f,width:c,height:u,imageData:p}}static async deserialize(t,r,i){var v;let o=null,a=!1;if(t instanceof LG){const{data:{rect:x,rotation:w,id:S,structParent:_,popupRef:b,richText:C,contentsObj:T,creationDate:F,modificationDate:A},container:D,parent:{page:{pageNumber:P}},canvas:L}=t;let W,O;L?(delete t.canvas,{id:W,bitmap:O}=i.imageManager.getFromCanvas(D.id,L),L.remove()):(a=!0,t._hasNoCanvas=!0);const U=((v=await r._structTree.getAriaAttributes(`${Yx}${S}`))==null?void 0:v.get("aria-label"))||"";o=t={annotationType:jn.STAMP,bitmapId:W,bitmap:O,pageIndex:P-1,rect:x.slice(0),rotation:w,annotationElementId:S,id:S,deleted:!1,accessibilityData:{decorative:!1,altText:U},isSvg:!1,structParent:_,popupRef:b,richText:C,comment:(T==null?void 0:T.str)||null,creationDate:F,modificationDate:A}}const l=await super.deserialize(t,r,i),{rect:d,bitmap:c,bitmapUrl:u,bitmapId:f,isSvg:p,accessibilityData:g}=t;a?(i.addMissingCanvas(t.id,l),R(l,t0,!0)):f&&i.imageManager.isValidId(f)?(R(l,ao,f),c&&R(l,Ri,c)):R(l,rf,u),R(l,Pl,p);const[m,y]=l.pageDimensions;return l.width=(d[2]-d[0])/m,l.height=(d[3]-d[1])/y,g&&(l.altTextData=g),l._initialData=o,t.comment&&l.setCommentData(t),R(l,Uv,!!o),l}serialize(t=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i=Object.assign(super.serialize(t),{bitmapId:h(this,ao),isSvg:h(this,Pl)});if(this.addComment(i),t)return i.bitmapUrl=q(this,_r,fA).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i.isCopy=!0,i;const{decorative:o,altText:a}=this.serializeAltText(!1);if(!o&&a&&(i.accessibilityData={type:"Figure",alt:a}),this.annotationElementId){const d=q(this,_r,jK).call(this,i);return d.isSame?null:(d.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1,i.id=this.annotationElementId,delete i.bitmapId,i)}if(r===null)return i;r.stamps||(r.stamps=new Map);const l=h(this,Pl)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!r.stamps.has(h(this,ao)))r.stamps.set(h(this,ao),{area:l,serialized:i}),i.bitmap=q(this,_r,fA).call(this,!1);else if(h(this,Pl)){const d=r.stamps.get(h(this,ao));l>d.area&&(d.area=l,d.serialized.bitmap.close(),d.serialized.bitmap=q(this,_r,fA).call(this,!1))}return i}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}Ri=new WeakMap,ao=new WeakMap,ng=new WeakMap,rf=new WeakMap,rg=new WeakMap,Wv=new WeakMap,sf=new WeakMap,t0=new WeakMap,Su=new WeakMap,Pl=new WeakMap,Uv=new WeakMap,_r=new WeakSet,ES=function(t,r=!1){if(!t){this.remove();return}R(this,Ri,t.bitmap),r||(R(this,ao,t.id),R(this,Pl,t.isSvg)),t.file&&R(this,Wv,t.file.name),q(this,_r,uA).call(this)},PS=function(){if(R(this,ng,null),this._uiManager.enableWaiting(!1),!!h(this,sf)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&h(this,Ri)){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&h(this,Ri)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},cA=function(){if(h(this,ao)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(h(this,ao)).then(i=>q(this,_r,ES).call(this,i,!0)).finally(()=>q(this,_r,PS).call(this));return}if(h(this,rf)){const i=h(this,rf);R(this,rf,null),this._uiManager.enableWaiting(!0),R(this,ng,this._uiManager.imageManager.getFromUrl(i).then(o=>q(this,_r,ES).call(this,o)).finally(()=>q(this,_r,PS).call(this)));return}if(h(this,rg)){const i=h(this,rg);R(this,rg,null),this._uiManager.enableWaiting(!0),R(this,ng,this._uiManager.imageManager.getFromFile(i).then(o=>q(this,_r,ES).call(this,o)).finally(()=>q(this,_r,PS).call(this)));return}const t=document.createElement("input");t.type="file",t.accept=$B.join(",");const r=this._uiManager._signal;R(this,ng,new Promise(i=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const o=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),q(this,_r,ES).call(this,o)}i()},{signal:r}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:r})}).finally(()=>q(this,_r,PS).call(this))),t.click()},uA=function(){var c;const{div:t}=this;let{width:r,height:i}=h(this,Ri);const[o,a]=this.pageDimensions,l=.75;if(this.width)r=this.width*o,i=this.height*a;else if(r>l*o||i>l*a){const u=Math.min(l*o/r,l*a/i);r*=u,i*=u}this._uiManager.enableWaiting(!1);const d=R(this,sf,document.createElement("canvas"));d.setAttribute("role","img"),this.addContainer(d),this.width=r/o,this.height=i/a,this.setDims(),(c=this._initialOptions)!=null&&c.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),q(this,_r,hM).call(this),h(this,Uv)||(this.parent.addUndoableEditor(this),R(this,Uv,!0)),this._reportTelemetry({action:"inserted_image"}),h(this,Wv)&&this.div.setAttribute("aria-description",h(this,Wv)),this.annotationElementId||this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert")},hA=function(t,r){const{width:i,height:o}=h(this,Ri);let a=i,l=o,d=h(this,Ri);for(;a>2*t||l>2*r;){const c=a,u=l;a>2*t&&(a=Math.ceil(a/2)),l>2*r&&(l=Math.ceil(l/2));const f=new OffscreenCanvas(a,l);f.getContext("2d").drawImage(d,0,0,c,u,0,0,a,l),d=f.transferToImageBitmap()}return d},hM=function(){const[t,r]=this.parentDimensions,{width:i,height:o}=this,a=new Lu,l=Math.ceil(i*t*a.sx),d=Math.ceil(o*r*a.sy),c=h(this,sf);if(!c||c.width===l&&c.height===d)return;c.width=l,c.height=d;const u=h(this,Pl)?h(this,Ri):q(this,_r,hA).call(this,l,d),f=c.getContext("2d");f.filter=this._uiManager.hcmFilter,f.drawImage(u,0,0,u.width,u.height,0,0,l,d)},fA=function(t){if(t){if(h(this,Pl)){const o=this._uiManager.imageManager.getSvgUrl(h(this,ao));if(o)return o}const r=document.createElement("canvas");return{width:r.width,height:r.height}=h(this,Ri),r.getContext("2d").drawImage(h(this,Ri),0,0),r.toDataURL()}if(h(this,Pl)){const[r,i]=this.pageDimensions,o=Math.round(this.width*r*Wg.PDF_TO_CSS_UNITS),a=Math.round(this.height*i*Wg.PDF_TO_CSS_UNITS),l=new OffscreenCanvas(o,a);return l.getContext("2d").drawImage(h(this,Ri),0,0,h(this,Ri).width,h(this,Ri).height,0,0,o,a),l.transferToImageBitmap()}return structuredClone(h(this,Ri))},jK=function(t){var l;const{pageIndex:r,accessibilityData:{altText:i}}=this._initialData,o=t.pageIndex===r,a=(((l=t.accessibilityData)==null?void 0:l.alt)||"")===i;return{isSame:!this.hasEditedComment&&!this._hasBeenMoved&&!this._hasBeenResized&&o&&a,isSameAltText:a}},ve(uM,"_type","stamp"),ve(uM,"_editorType",jn.STAMP);var n0,Hv,ig,sg,of,Ka,og,qv,Vv,wc,af,lo,lf,ag,Gv,Vt,lg,fi,pM,kK,$c,gM,mM,pA;const oc=class oc{constructor({uiManager:e,pageIndex:t,div:r,structTreeLayer:i,accessibilityManager:o,annotationLayer:a,drawLayer:l,textLayer:d,viewport:c,l10n:u}){N(this,fi);N(this,n0);N(this,Hv,!1);N(this,ig,null);N(this,sg,null);N(this,of,null);N(this,Ka,new Map);N(this,og,!1);N(this,qv,!1);N(this,Vv,!1);N(this,wc,null);N(this,af,null);N(this,lo,null);N(this,lf,null);N(this,ag,null);N(this,Gv,-1);N(this,Vt);const f=[...h(oc,lg).values()];if(!oc._initialized){oc._initialized=!0;for(const p of f)p.initialize(u,e)}e.registerEditorTypes(f),R(this,Vt,e),this.pageIndex=t,this.div=r,R(this,n0,o),R(this,ig,a),this.viewport=c,R(this,lo,d),this.drawLayer=l,this._structTree=i,h(this,Vt).addLayer(this)}get isEmpty(){return h(this,Ka).size===0}get isInvisible(){return this.isEmpty&&h(this,Vt).getMode()===jn.NONE}updateToolbar(e){h(this,Vt).updateToolbar(e)}updateMode(e=h(this,Vt).getMode()){switch(q(this,fi,pA).call(this),e){case jn.NONE:this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case jn.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case jn.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:t}=this.div;if(t.toggle("nonEditing",!1),e===jn.POPUP)t.toggle("commentEditing",!0);else{t.toggle("commentEditing",!1);for(const r of h(oc,lg).values())t.toggle(`${r._type}Editing`,e===r._editorType)}this.div.hidden=!1}hasTextLayer(e){var t;return e===((t=h(this,lo))==null?void 0:t.div)}setEditingState(e){h(this,Vt).setEditingState(e)}addCommands(e){h(this,Vt).addCommands(e)}cleanUndoStack(e){h(this,Vt).cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle("drawing",!e)}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}toggleAnnotationLayerPointerEvents(e=!1){var t;(t=h(this,ig))==null||t.togglePointerEvents(e)}async enable(){var r;R(this,Vv,!0),this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),(r=h(this,ag))==null||r.abort(),R(this,ag,null);const e=new Set;for(const i of h(this,fi,pM))i.enableEditing(),i.show(!0),i.annotationElementId&&(h(this,Vt).removeChangedExistingAnnotation(i),e.add(i.annotationElementId));const t=h(this,ig);if(t)for(const i of t.getEditableAnnotations()){if(i.hide(),h(this,Vt).isDeletedAnnotationElement(i.data.id)||e.has(i.data.id))continue;const o=await this.deserialize(i);o&&(this.addOrRebuild(o),o.enableEditing())}R(this,Vv,!1),h(this,Vt)._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){var i;if(R(this,qv,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),h(this,lo)&&!h(this,ag)){R(this,ag,new AbortController);const o=h(this,Vt).combinedSignal(h(this,ag));h(this,lo).div.addEventListener("pointerdown",a=>{const{clientX:d,clientY:c,timeStamp:u}=a,f=h(this,Gv);if(u-f>500){R(this,Gv,u);return}R(this,Gv,-1);const{classList:p}=this.div;p.toggle("getElements",!0);const g=document.elementsFromPoint(d,c);if(p.toggle("getElements",!1),!this.div.contains(g[0]))return;let m;const y=new RegExp(`^${Gj}[0-9]+$`);for(const x of g)if(y.test(x.id)){m=x.id;break}if(!m)return;const v=h(this,Ka).get(m);(v==null?void 0:v.annotationElementId)===null&&($i(a),v.dblclick(a))},{signal:o,capture:!0})}const e=h(this,ig),t=[];if(e){const o=new Map,a=new Map;for(const l of h(this,fi,pM)){if(l.disableEditing(),!l.annotationElementId){t.push(l);continue}if(l.serialize()!==null){o.set(l.annotationElementId,l);continue}else a.set(l.annotationElementId,l);(i=this.getEditableAnnotation(l.annotationElementId))==null||i.show(),l.remove()}for(const l of e.getEditableAnnotations()){const{id:d}=l.data;if(h(this,Vt).isDeletedAnnotationElement(d)){l.updateEdited({deleted:!0});continue}let c=a.get(d);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=o.get(d),c&&(h(this,Vt).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}q(this,fi,pA).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const o of h(oc,lg).values())r.remove(`${o._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),e==null||e.updateFakeAnnotations(t),R(this,qv,!1)}getEditableAnnotation(e){var t;return((t=h(this,ig))==null?void 0:t.getEditableAnnotation(e))||null}setActiveEditor(e){h(this,Vt).getActive()!==e&&h(this,Vt).setActiveEditor(e)}enableTextSelection(){var e;if(this.div.tabIndex=-1,(e=h(this,lo))!=null&&e.div&&!h(this,lf)){R(this,lf,new AbortController);const t=h(this,Vt).combinedSignal(h(this,lf));h(this,lo).div.addEventListener("pointerdown",q(this,fi,kK).bind(this),{signal:t}),h(this,lo).div.classList.add("highlighting")}}disableTextSelection(){var e;this.div.tabIndex=0,(e=h(this,lo))!=null&&e.div&&h(this,lf)&&(h(this,lf).abort(),R(this,lf,null),h(this,lo).div.classList.remove("highlighting"))}enableClick(){if(h(this,sg))return;R(this,sg,new AbortController);const e=h(this,Vt).combinedSignal(h(this,sg));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:e});const t=this.pointerup.bind(this);this.div.addEventListener("pointerup",t,{signal:e}),this.div.addEventListener("pointercancel",t,{signal:e})}disableClick(){var e;(e=h(this,sg))==null||e.abort(),R(this,sg,null)}attach(e){h(this,Ka).set(e.id,e);const{annotationElementId:t}=e;t&&h(this,Vt).isDeletedAnnotationElement(t)&&h(this,Vt).removeDeletedAnnotationElement(e)}detach(e){var t;h(this,Ka).delete(e.id),(t=h(this,n0))==null||t.removePointerInTextLayer(e.contentDiv),!h(this,qv)&&e.annotationElementId&&h(this,Vt).addDeletedAnnotationElement(e)}remove(e){this.detach(e),h(this,Vt).removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){var t;e.parent!==this&&(e.parent&&e.annotationElementId&&(h(this,Vt).addDeletedAnnotationElement(e),xi.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),(t=e.parent)==null||t.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),h(this,Vt).addEditor(e),this.attach(e),!e.isAttachedToDOM){const t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!h(this,Vv)),h(this,Vt).addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){var r;if(!e.isAttachedToDOM)return;const{activeElement:t}=document;e.div.contains(t)&&!h(this,of)&&(e._focusEventsAllowed=!1,R(this,of,setTimeout(()=>{R(this,of,null),e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:h(this,Vt)._signal}),t.focus())},0))),e._structTreeParentId=(r=h(this,n0))==null?void 0:r.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||(e.parent=this),e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){const t=()=>e._uiManager.rebuild(e),r=()=>{e.remove()};this.addCommands({cmd:t,undo:r,mustExec:!1})}getEditorByUID(e){for(const t of h(this,Ka).values())if(t.uid===e)return t;return null}combinedSignal(e){return h(this,Vt).combinedSignal(e)}canCreateNewEmptyEditor(){var e;return(e=h(this,fi,$c))==null?void 0:e.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await h(this,Vt).updateMode(e.mode);const{offsetX:r,offsetY:i}=q(this,fi,mM).call(this),o=h(this,Vt).getId(),a=q(this,fi,gM).call(this,{parent:this,id:o,x:r,y:i,uiManager:h(this,Vt),isCentered:!0,...t});a&&this.add(a)}async deserialize(e){var t;return await((t=h(oc,lg).get(e.annotationType??e.annotationEditorType))==null?void 0:t.deserialize(e,this,h(this,Vt)))||null}createAndAddNewEditor(e,t,r={}){const i=h(this,Vt).getId(),o=q(this,fi,gM).call(this,{parent:this,id:i,x:e.offsetX,y:e.offsetY,uiManager:h(this,Vt),isCentered:t,...r});return o&&this.add(o),o}get boundingClientRect(){return this.div.getBoundingClientRect()}addNewEditor(e={}){this.createAndAddNewEditor(q(this,fi,mM).call(this),!0,e)}setSelected(e){h(this,Vt).setSelected(e)}toggleSelected(e){h(this,Vt).toggleSelected(e)}unselect(e){h(this,Vt).unselect(e)}pointerup(e){var i;const{isMac:t}=Ds.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div||!h(this,og)||(R(this,og,!1),(i=h(this,fi,$c))!=null&&i.isDrawer&&h(this,fi,$c).supportMultipleDrawings))return;if(!h(this,Hv)){R(this,Hv,!0);return}const r=h(this,Vt).getMode();if(r===jn.STAMP||r===jn.POPUP||r===jn.SIGNATURE){h(this,Vt).unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){var i;if(h(this,Vt).getMode()===jn.HIGHLIGHT&&this.enableTextSelection(),h(this,og)){R(this,og,!1);return}const{isMac:t}=Ds.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(R(this,og,!0),(i=h(this,fi,$c))!=null&&i.isDrawer){this.startDrawingSession(e);return}const r=h(this,Vt).getActive();R(this,Hv,!r||r.isEmpty())}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),h(this,wc)){h(this,fi,$c).startDrawing(this,h(this,Vt),!1,e);return}h(this,Vt).setCurrentDrawingSession(this),R(this,wc,new AbortController);const t=h(this,Vt).combinedSignal(h(this,wc));this.div.addEventListener("blur",({relatedTarget:r})=>{r&&!this.div.contains(r)&&(R(this,af,null),this.commitOrRemove())},{signal:t}),h(this,fi,$c).startDrawing(this,h(this,Vt),!1,e)}pause(e){if(e){const{activeElement:t}=document;this.div.contains(t)&&R(this,af,t);return}h(this,af)&&setTimeout(()=>{var t;(t=h(this,af))==null||t.focus(),R(this,af,null)},0)}endDrawingSession(e=!1){return h(this,wc)?(h(this,Vt).setCurrentDrawingSession(null),h(this,wc).abort(),R(this,wc,null),R(this,af,null),h(this,fi,$c).endDrawing(e)):null}findNewParent(e,t,r){const i=h(this,Vt).findParent(t,r);return i===null||i===this?!1:(i.changeParent(e),!0)}commitOrRemove(){return h(this,wc)?(this.endDrawingSession(),!0):!1}onScaleChanging(){h(this,wc)&&h(this,fi,$c).onScaleChangingWhenDrawing(this)}destroy(){var e,t;this.commitOrRemove(),((e=h(this,Vt).getActive())==null?void 0:e.parent)===this&&(h(this,Vt).commitOrRemove(),h(this,Vt).setActiveEditor(null)),h(this,of)&&(clearTimeout(h(this,of)),R(this,of,null));for(const r of h(this,Ka).values())(t=h(this,n0))==null||t.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,h(this,Ka).clear(),h(this,Vt).removeLayer(this)}async render({viewport:e}){this.viewport=e,k0(this.div,e);for(const t of h(this,Vt).getEditors(this.pageIndex))this.add(t),t.rebuild();await h(this,Vt).findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){h(this,Vt).commitOrRemove(),q(this,fi,pA).call(this);const t=this.viewport.rotation,r=e.rotation;if(this.viewport=e,k0(this.div,{rotation:r}),t!==r)for(const i of h(this,Ka).values())i.rotate(r)}get pageDimensions(){const{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return h(this,Vt).viewParameters.realScale}};n0=new WeakMap,Hv=new WeakMap,ig=new WeakMap,sg=new WeakMap,of=new WeakMap,Ka=new WeakMap,og=new WeakMap,qv=new WeakMap,Vv=new WeakMap,wc=new WeakMap,af=new WeakMap,lo=new WeakMap,lf=new WeakMap,ag=new WeakMap,Gv=new WeakMap,Vt=new WeakMap,lg=new WeakMap,fi=new WeakSet,pM=function(){return h(this,Ka).size!==0?h(this,Ka).values():h(this,Vt).getEditors(this.pageIndex)},kK=function(e){h(this,Vt).unselectAll();const{target:t}=e;if(t===h(this,lo).div||(t.getAttribute("role")==="img"||t.classList.contains("endOfContent")||t.classList.contains("textLayerImagePlaceholder"))&&h(this,lo).div.contains(t)){const{isMac:r}=Ds.platform;if(e.button!==0||e.ctrlKey&&r)return;h(this,Vt).showAllEditors("highlight",!0,!0),h(this,lo).div.classList.add("free"),this.toggleDrawing(),CT.startHighlighting(this,h(this,Vt).direction==="ltr",{target:h(this,lo).div,x:e.x,y:e.y}),h(this,lo).div.addEventListener("pointerup",()=>{h(this,lo).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:h(this,Vt)._signal}),e.preventDefault()}},$c=function(){return h(oc,lg).get(h(this,Vt).getMode())},gM=function(e){const t=h(this,fi,$c);return t?new t.prototype.constructor(e):null},mM=function(){const{x:e,y:t,width:r,height:i}=this.boundingClientRect,o=Math.max(0,e),a=Math.max(0,t),l=Math.min(window.innerWidth,e+r),d=Math.min(window.innerHeight,t+i),c=(o+l)/2-e,u=(a+d)/2-t,[f,p]=this.viewport.rotation%180===0?[c,u]:[u,c];return{offsetX:f,offsetY:p}},pA=function(){for(const e of h(this,Ka).values())e.isEmpty()&&e.remove()},ve(oc,"_initialized",!1),N(oc,lg,new Map([XI,iM,uM,CT,cM].map(e=>[e._editorType,e])));let fM=oc;var Sc,ba,r0,z_,JT,_K,Wu,xM,CK,bM;const Bs=class Bs{constructor(){N(this,Wu);N(this,Sc,null);N(this,ba,new Map);N(this,r0,new Map)}setParent(e){if(!h(this,Sc)){R(this,Sc,e);return}if(h(this,Sc)!==e){if(h(this,ba).size>0)for(const t of h(this,ba).values())t.remove(),e.append(t);R(this,Sc,e)}}static get _svgFactory(){return Cn(this,"_svgFactory",new kT)}draw(e,t=!1,r=!1){const i=Gi(Bs,z_)._++,o=q(this,Wu,xM).call(this),a=Bs._svgFactory.createElement("defs");o.append(a);const l=Bs._svgFactory.createElement("path");a.append(l);const d=`path_${i}`;l.setAttribute("id",d),l.setAttribute("vector-effect","non-scaling-stroke"),t&&h(this,r0).set(i,l);const c=r?q(this,Wu,CK).call(this,a,d):null,u=Bs._svgFactory.createElement("use");return o.append(u),u.setAttribute("href",`#${d}`),this.updateProperties(o,e),h(this,ba).set(i,o),{id:i,clipPathId:`url(#${c})`}}drawOutline(e,t){const r=Gi(Bs,z_)._++,i=q(this,Wu,xM).call(this),o=Bs._svgFactory.createElement("defs");i.append(o);const a=Bs._svgFactory.createElement("path");o.append(a);const l=`path_${r}`;a.setAttribute("id",l),a.setAttribute("vector-effect","non-scaling-stroke");let d;if(t){const f=Bs._svgFactory.createElement("mask");o.append(f),d=`mask_${r}`,f.setAttribute("id",d),f.setAttribute("maskUnits","objectBoundingBox");const p=Bs._svgFactory.createElement("rect");f.append(p),p.setAttribute("width","1"),p.setAttribute("height","1"),p.setAttribute("fill","white");const g=Bs._svgFactory.createElement("use");f.append(g),g.setAttribute("href",`#${l}`),g.setAttribute("stroke","none"),g.setAttribute("fill","black"),g.setAttribute("fill-rule","nonzero"),g.classList.add("mask")}const c=Bs._svgFactory.createElement("use");i.append(c),c.setAttribute("href",`#${l}`),d&&c.setAttribute("mask",`url(#${d})`);const u=c.cloneNode();return i.append(u),c.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.updateProperties(i,e),h(this,ba).set(r,i),r}finalizeDraw(e,t){h(this,r0).delete(e),this.updateProperties(e,t)}updateProperties(e,t){var d;if(!t)return;const{root:r,bbox:i,rootClass:o,path:a}=t,l=typeof e=="number"?h(this,ba).get(e):e;if(l){if(r&&q(this,Wu,bM).call(this,l,r),i&&q(d=Bs,JT,_K).call(d,l,i),o){const{classList:c}=l;for(const[u,f]of Object.entries(o))c.toggle(u,f)}if(a){const u=l.firstElementChild.firstElementChild;q(this,Wu,bM).call(this,u,a)}}}updateParent(e,t){if(t===this)return;const r=h(this,ba).get(e);r&&(h(t,Sc).append(r),h(this,ba).delete(e),h(t,ba).set(e,r))}remove(e){h(this,r0).delete(e),h(this,Sc)!==null&&(h(this,ba).get(e).remove(),h(this,ba).delete(e))}destroy(){R(this,Sc,null);for(const e of h(this,ba).values())e.remove();h(this,ba).clear(),h(this,r0).clear()}};Sc=new WeakMap,ba=new WeakMap,r0=new WeakMap,z_=new WeakMap,JT=new WeakSet,_K=function(e,[t,r,i,o]){const{style:a}=e;a.top=`${100*r}%`,a.left=`${100*t}%`,a.width=`${100*i}%`,a.height=`${100*o}%`},Wu=new WeakSet,xM=function(){const e=Bs._svgFactory.create(1,1,!0);return h(this,Sc).append(e),e.setAttribute("aria-hidden",!0),e},CK=function(e,t){const r=Bs._svgFactory.createElement("clipPath");e.append(r);const i=`clip_${t}`;r.setAttribute("id",i),r.setAttribute("clipPathUnits","objectBoundingBox");const o=Bs._svgFactory.createElement("use");return r.append(o),o.setAttribute("href",`#${t}`),o.classList.add("clip"),i},bM=function(e,t){for(const[r,i]of Object.entries(t))i===null?e.removeAttribute(r):e.setAttribute(r,i)},N(Bs,JT),N(Bs,z_,0);let yM=Bs;function Z2(n){return`${(n*100).toFixed(2)}%`}var Kv,O_,L_,Xv,ju,ku,N_,eF,AK;const oj=class oj{constructor(e,t,r,i){N(this,eF);N(this,Kv,[]);N(this,O_,new Map);N(this,L_,null);N(this,Xv,0);N(this,ju,0);N(this,ku,0);R(this,Xv,e),R(this,Kv,t),R(this,ju,r.rawDims.pageWidth),R(this,ku,r.rawDims.pageHeight),R(this,L_,i)}render(){const e=document.createElement("div");e.className="textLayerImages";for(let t=0;t{var x;if(!(t.target instanceof HTMLCanvasElement))return;const r=t.target,i=h(this,O_).get(r);if(!i)return;const o=(x=h(oj,N_))==null?void 0:x.deref();if(o===r)return;o&&(o.width=0,o.height=0),R(oj,N_,new WeakRef(r));const{inverseTransform:a,x1:l,y1:d,width:c,height:u}=i,f=h(this,L_).call(this),p=Math.ceil(l*f.width),g=Math.ceil(d*f.height),m=Math.floor((l+c/h(this,ju))*f.width),y=Math.floor((d+u/h(this,ku))*f.height);r.width=m-p,r.height=y-g;const v=r.getContext("2d");v.setTransform(...a),v.translate(-p,-g),v.drawImage(f,0,0)}),e}};Kv=new WeakMap,O_=new WeakMap,L_=new WeakMap,Xv=new WeakMap,ju=new WeakMap,ku=new WeakMap,N_=new WeakMap,eF=new WeakSet,AK=function([e,t,r,i,o,a]){const l=Math.hypot((o-e)*h(this,ju),(a-t)*h(this,ku)),d=Math.hypot((r-e)*h(this,ju),(i-t)*h(this,ku));if(l{const i=setTimeout(()=>{r(n)},e);return()=>{clearTimeout(i)}},[n,e]),t}function wM(){const n=new Date,e=new Date(n);return e.setDate(e.getDate()-90),{from:e.toISOString().split("T")[0],to:n.toISOString().split("T")[0]}}function Cm(n){if(!n)return"-";try{return new Date(n).toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return n}}function Td(n){if(n==null)return"-";const e=typeof n=="string"?parseFloat(n):n;return isNaN(e)?"-":`£${e.toFixed(2)}`}function qhe(n){if(n==null)return"-";const e=typeof n=="string"?parseFloat(n):n;return isNaN(e)?"-":`${e>=0?"+":""}${e.toFixed(1)}%`}function Ex(n,e=1){if(n==null)return"-";const t=typeof n=="string"?parseFloat(n):n;return isNaN(t)?"-":t.toFixed(e)}function Vhe(n,e){try{const t=sessionStorage.getItem(n);return t===null?e:JSON.parse(t)}catch{return e}}function Ghe(n,e){try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}}function co(n,e){const[t,r]=k.useState(()=>Vhe(n,e));return k.useEffect(()=>{Ghe(n,t)},[n,t]),[t,r]}const qP={consistent:{icon:"✓",color:"#22c55e",label:"Price consistent"},amber:{icon:"?",color:"#f59e0b",label:"Small price change"},red:{icon:"!",color:"#ef4444",label:"Large price change"},acknowledged:{icon:"✓",color:"#22c55e",label:"Price acknowledged"},no_history:{icon:null,color:"#9ca3af",label:"No price history"}};function Khe(n){return n&&qP[n]||qP.no_history}function FK({isOpen:n,onClose:e,productCode:t,description:r,unit:i,supplierId:o,supplierName:a,currentPrice:l,sourceInvoiceId:d,sourceLineItemId:c,onAcknowledge:u}){const{token:f}=gn(),p=pi(),g=k.useMemo(()=>{const D=new Date,P=new Date(D);return P.setFullYear(P.getFullYear()-1),{from:P.toISOString().split("T")[0],to:D.toISOString().split("T")[0]}},[]),[m,y]=k.useState(g.from),[v,x]=k.useState(g.to),{data:w,isLoading:S,error:_}=Oe({queryKey:["line-item-history",o,t,r,i,m,v],queryFn:async()=>{const D=new URLSearchParams;D.set("supplier_id",o.toString()),t&&D.set("product_code",t),r&&D.set("description",r),i&&D.set("unit",i),m&&D.set("date_from",m),v&&D.set("date_to",v);const P=await fetch(`/api/search/line-items/history?${D}`,{headers:{Authorization:`Bearer ${f}`}});if(!P.ok)throw new Error("Failed to fetch history");return P.json()},enabled:n&&!!f}),b=Ue({mutationFn:async()=>{const D=await fetch("/api/search/line-items/acknowledge-price",{method:"POST",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"},body:JSON.stringify({product_code:t,description:r,supplier_id:o,new_price:l||(w==null?void 0:w.current_price),source_invoice_id:d,source_line_item_id:c})});if(!D.ok)throw new Error("Failed to acknowledge price");return D.json()},onSuccess:()=>{p.invalidateQueries({queryKey:["line-item-history"]}),p.invalidateQueries({queryKey:["search-line-items"]}),u&&u()}}),C=k.useMemo(()=>{if(!(w!=null&&w.price_history.length))return{min:0,max:100};const D=w.price_history.map(te=>typeof te.price=="string"?parseFloat(te.price):te.price),P=Math.min(...D),L=Math.max(...D),W=L-P,U=(P+L)/2*.2||1,M=Math.max(W,U),I=(P+L)/2,H=I-M/2,z=I+M/2,G=M*.1;return{min:Math.max(0,H-G),max:z+G}},[w]);if(!n)return null;const T=D=>{const P=C.max-C.min;return P===0?50:(D-C.min)/P*100},F=l??(w==null?void 0:w.current_price),A=(w==null?void 0:w.price_change_status)==="amber"||(w==null?void 0:w.price_change_status)==="red";return s.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:e,children:s.jsxs("div",{style:{backgroundColor:"white",borderRadius:"12px",width:"90%",maxWidth:"800px",maxHeight:"90vh",overflow:"auto",padding:"24px"},onClick:D=>D.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"20px"},children:[s.jsxs("div",{children:[s.jsxs("h2",{style:{margin:0,fontSize:"18px"},children:["Price History: ",r||t||"Unknown",t&&r&&s.jsxs("span",{style:{color:"#6b7280",fontWeight:"normal"},children:[" (",t,")"]})]}),s.jsxs("p",{style:{margin:"4px 0 0",color:"#6b7280"},children:["Supplier: ",a]})]}),s.jsx("button",{onClick:e,style:{padding:"4px 12px",border:"none",backgroundColor:"#f1f5f9",borderRadius:"4px",cursor:"pointer",fontSize:"16px"},children:"✕"})]}),s.jsxs("div",{style:{display:"flex",gap:"12px",alignItems:"center",marginBottom:"20px",padding:"12px",backgroundColor:"#f8fafc",borderRadius:"8px"},children:[s.jsx("label",{style:{fontSize:"14px"},children:"Date Range:"}),s.jsx("input",{type:"date",value:m,onChange:D=>y(D.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}}),s.jsx("span",{children:"to"}),s.jsx("input",{type:"date",value:v,onChange:D=>x(D.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}})]}),S&&s.jsx("p",{children:"Loading..."}),_&&s.jsxs("p",{style:{color:"red"},children:["Error: ",_.message]}),w&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{marginBottom:"24px",padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px"},children:[s.jsx("h3",{style:{margin:"0 0 16px",fontSize:"14px",fontWeight:600},children:"Price History"}),w.price_history.length===0?s.jsx("p",{style:{color:"#6b7280",textAlign:"center"},children:"No price history available for this period"}):s.jsxs("div",{children:[s.jsxs("div",{style:{height:"150px",display:"flex",alignItems:"flex-end",gap:"2px",padding:"0 0 20px",borderBottom:"1px solid #e5e7eb",position:"relative"},children:[s.jsxs("div",{style:{position:"absolute",left:0,top:0,bottom:20,width:"50px",display:"flex",flexDirection:"column",justifyContent:"space-between",fontSize:"10px",color:"#9ca3af"},children:[s.jsx("span",{children:Td(C.max)}),s.jsx("span",{children:Td(C.min)})]}),s.jsx("div",{style:{flex:1,marginLeft:"55px",display:"flex",alignItems:"flex-end",gap:"2px",height:"100%"},children:w.price_history.map((D,P)=>s.jsx("div",{style:{flex:1,maxWidth:"40px",height:`${T(D.price)}%`,backgroundColor:"#3b82f6",borderRadius:"2px 2px 0 0",cursor:"pointer",position:"relative"},title:`${Cm(D.date)}: ${Td(D.price)} (${D.invoice_number||"Invoice"})`},P))})]}),s.jsx("div",{style:{marginLeft:"55px",display:"flex",justifyContent:"space-between",fontSize:"10px",color:"#9ca3af",marginTop:"4px"},children:w.price_history.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Cm(w.price_history[0].date)}),s.jsx("span",{children:Cm(w.price_history[w.price_history.length-1].date)})]})}),s.jsx("div",{style:{marginTop:"16px",maxHeight:"150px",overflowY:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"13px"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f8fafc"},children:[s.jsx("th",{style:{padding:"8px",textAlign:"left",width:"90px"},children:"Date"}),s.jsx("th",{style:{padding:"8px",textAlign:"left",minWidth:"200px"},children:"Description"}),s.jsx("th",{style:{padding:"8px",textAlign:"left",width:"80px"},children:"Unit"}),s.jsx("th",{style:{padding:"8px",textAlign:"right",width:"80px"},children:"Qty"}),s.jsx("th",{style:{padding:"8px",textAlign:"right",width:"80px"},children:"Price"})]})}),s.jsx("tbody",{children:w.price_history.slice().reverse().map((D,P)=>s.jsxs("tr",{style:{borderBottom:"1px solid #f1f5f9"},children:[s.jsx("td",{style:{padding:"8px",whiteSpace:"nowrap"},children:Cm(D.date)}),s.jsx("td",{style:{padding:"8px",maxWidth:"300px"},children:s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w.description||"-"}),s.jsxs("a",{href:`/invoice/${D.invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none",whiteSpace:"nowrap",flexShrink:0,fontSize:"12px"},children:[D.invoice_number||"View"," ↗"]})]})}),s.jsx("td",{style:{padding:"8px"},children:i||"-"}),s.jsx("td",{style:{padding:"8px",textAlign:"right"},children:Ex(D.quantity)}),s.jsx("td",{style:{padding:"8px",textAlign:"right"},children:Td(D.price)})]},P))})]})})]})]}),s.jsxs("div",{style:{marginBottom:"24px",padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px"},children:[s.jsx("h3",{style:{margin:"0 0 12px",fontSize:"14px",fontWeight:600},children:"Stats for Period"}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:"12px"},children:[s.jsx(Kw,{label:"Total Occurrences",value:String(w.total_occurrences)}),s.jsx(Kw,{label:"Total Quantity",value:Ex(w.total_quantity)}),s.jsx(Kw,{label:"Avg Qty per Invoice",value:Ex(w.avg_qty_per_invoice,2)}),s.jsx(Kw,{label:"Avg Qty per Week",value:Ex(w.avg_qty_per_week,2)}),s.jsx(Kw,{label:"Avg Qty per Month",value:Ex(w.avg_qty_per_month,2)})]})]}),F&&s.jsxs("div",{style:{padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px",backgroundColor:w.price_change_status==="red"?"#fef2f2":w.price_change_status==="amber"?"#fffbeb":"#f0fdf4"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{children:[s.jsx("span",{style:{fontWeight:600},children:"Current Price: "}),s.jsx("span",{style:{fontSize:"18px"},children:Td(F)}),w.price_history.length>1&&s.jsx("span",{style:{marginLeft:"8px",color:w.price_change_status==="red"?"#dc2626":w.price_change_status==="amber"?"#d97706":"#16a34a"},children:(()=>{var L;const D=(L=w.price_history[w.price_history.length-2])==null?void 0:L.price;if(!D)return"";const P=(F-D)/D*100;return`(${qhe(P)} from previous ${Td(D)})`})()})]}),A&&s.jsx("button",{onClick:()=>b.mutate(),disabled:b.isPending,style:{padding:"8px 16px",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",cursor:b.isPending?"not-allowed":"pointer",opacity:b.isPending?.7:1},children:b.isPending?"Acknowledging...":"Acknowledge Price Change"})]}),b.isSuccess&&s.jsx("p",{style:{marginTop:"8px",color:"#16a34a",fontSize:"14px"},children:"✓ Price change acknowledged"})]})]})]})})}function Kw({label:n,value:e}){return s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"12px",color:"#6b7280"},children:n}),s.jsx("div",{style:{fontSize:"16px",fontWeight:600},children:e})]})}function Xhe({invoiceId:n,invoiceNumber:e,supplierId:t,supplierName:r,lineItems:i=[],onClose:o,onSuccess:a}){var W;const{token:l}=gn(),d=pi(),[c,u]=k.useState("price_discrepancy"),[f,p]=k.useState("medium"),[g,m]=k.useState(""),[y,v]=k.useState(""),[x,w]=k.useState(""),[S,_]=k.useState(""),[b,C]=k.useState(new Set),[T,F]=k.useState(""),A=Ue({mutationFn:async O=>{const U=await fetch("/api/disputes",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(O)});if(!U.ok){const M=await U.json();throw new Error(M.detail||"Failed to create dispute")}return U.json()},onSuccess:()=>{d.invalidateQueries({queryKey:["disputes"]}),d.invalidateQueries({queryKey:["dispute-stats"]}),d.invalidateQueries({queryKey:["invoice",n]}),a&&a(),o()}}),D=O=>{if(O.preventDefault(),!g.trim()){alert("Please enter a dispute title");return}if(!x){alert("Please enter a disputed amount");return}const U={invoice_id:n,dispute_type:c,priority:f,title:g.trim(),disputed_amount:parseFloat(x)};y.trim()&&(U.description=y.trim()),S&&(U.expected_amount=parseFloat(S)),b.size>0&&(U.line_items=Array.from(b).map(M=>{const I=i.find(z=>z.id===M);return I?{invoice_line_item_id:I.id,product_name:I.description||I.product_code||"Unnamed item",product_code:I.product_code||void 0,quantity_ordered:I.quantity||void 0,unit_price_charged:I.unit_price||void 0,total_charged:I.amount||0}:null}).filter(M=>M!==null)),A.mutate(U)},P=O=>{const U=new Set(b);U.has(O)?U.delete(O):U.add(O),C(U);const I=i.filter(H=>U.has(H.id)).reduce((H,z)=>H+(z.amount||0),0);I>0?w(I.toFixed(2)):U.size===0&&w("")},L=i.filter(O=>{if(!T)return!0;const U=T.toLowerCase(),M=(O.description||"").toLowerCase(),I=(O.product_code||"").toLowerCase();return M.includes(U)||I.includes(U)});return s.jsx("div",{style:bn.modalOverlay,onClick:o,children:s.jsxs("div",{style:bn.modal,onClick:O=>O.stopPropagation(),children:[s.jsxs("div",{style:bn.modalHeader,children:[s.jsx("h2",{style:bn.modalTitle,children:"Create Dispute"}),s.jsx("button",{style:bn.closeBtn,onClick:o,type:"button",children:"✕"})]}),s.jsxs("form",{onSubmit:D,style:bn.form,children:[s.jsx("div",{style:bn.formRow,children:s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Invoice"}),s.jsxs("div",{style:bn.staticValue,children:["#",e||n,r&&s.jsxs("span",{style:bn.supplier,children:[" - ",r]})]})]})}),s.jsxs("div",{style:bn.formRow,children:[s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Dispute Type *"}),s.jsxs("select",{value:c,onChange:O=>u(O.target.value),style:bn.select,required:!0,children:[s.jsx("option",{value:"price_discrepancy",children:"Price Discrepancy"}),s.jsx("option",{value:"short_delivery",children:"Short Delivery"}),s.jsx("option",{value:"wrong_product",children:"Wrong Product"}),s.jsx("option",{value:"quality_issue",children:"Quality Issue"}),s.jsx("option",{value:"calculation_error",children:"Calculation Error"}),s.jsx("option",{value:"missing_items",children:"Missing Items"}),s.jsx("option",{value:"damaged_goods",children:"Damaged Goods"}),s.jsx("option",{value:"other",children:"Other"})]})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Priority *"}),s.jsxs("select",{value:f,onChange:O=>p(O.target.value),style:bn.select,required:!0,children:[s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"urgent",children:"Urgent"})]})]})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Title *"}),s.jsx("input",{type:"text",value:g,onChange:O=>m(O.target.value),style:bn.input,placeholder:"Brief summary of the issue",required:!0,maxLength:200})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Description"}),s.jsx("textarea",{value:y,onChange:O=>v(O.target.value),style:bn.textarea,placeholder:"Detailed description of the dispute (optional)...",rows:4})]}),s.jsxs("div",{style:bn.formRow,children:[s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Disputed Amount (£) *"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:x,onChange:O=>w(O.target.value),style:bn.input,placeholder:"0.00",required:!0}),s.jsx("div",{style:bn.fieldHint,children:"Auto-fills when you select line items"})]}),s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Expected Amount (£)"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:S,onChange:O=>_(O.target.value),style:bn.input,placeholder:"0.00"})]})]}),i.length>0&&s.jsxs("div",{style:bn.formGroup,children:[s.jsx("label",{style:bn.label,children:"Disputed Line Items (optional)"}),s.jsx("input",{type:"text",value:T,onChange:O=>F(O.target.value),style:bn.input,placeholder:"Search line items by description or code..."}),s.jsx("div",{style:bn.lineItemsContainer,children:L.length===0?s.jsx("div",{style:bn.noResults,children:"No items match your search"}):L.map(O=>s.jsxs("label",{style:bn.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:b.has(O.id),onChange:()=>P(O.id),style:bn.checkbox}),s.jsxs("span",{style:bn.lineItemText,children:[O.description||O.product_code||"Unnamed item",O.amount!=null&&s.jsxs("span",{style:bn.lineItemAmount,children:[" - £",Number(O.amount).toFixed(2)]})]})]},O.id))}),b.size>0&&s.jsxs("div",{style:bn.selectedSummary,children:[b.size," item(s) selected"]})]}),s.jsxs("div",{style:bn.footer,children:[s.jsx("button",{type:"button",onClick:o,style:bn.cancelBtn,disabled:A.isPending,children:"Cancel"}),s.jsx("button",{type:"submit",style:bn.submitBtn,disabled:A.isPending,children:A.isPending?"Creating...":"Create Dispute"})]}),A.isError&&s.jsxs("div",{style:bn.error,children:["Error: ",((W=A.error)==null?void 0:W.message)||"Failed to create dispute"]})]})]})})}const bn={modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3,padding:"1rem"},modal:{background:"white",borderRadius:"12px",maxWidth:"700px",width:"100%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},modalTitle:{margin:0,color:"#1a1a2e"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},form:{padding:"1.5rem",flex:1,overflow:"auto"},formRow:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1rem",marginBottom:"1rem"},formGroup:{marginBottom:"1rem"},label:{display:"block",marginBottom:"0.5rem",fontWeight:"bold",color:"#1a1a2e",fontSize:"0.9rem"},staticValue:{padding:"0.75rem",background:"#f5f5f5",borderRadius:"8px",color:"#666"},supplier:{color:"#999",fontSize:"0.9rem"},input:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box"},select:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box"},textarea:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit"},lineItemsContainer:{maxHeight:"200px",overflow:"auto",border:"1px solid #eee",borderRadius:"8px",padding:"0.5rem",marginTop:"0.5rem"},checkboxLabel:{display:"flex",alignItems:"center",padding:"0.5rem",cursor:"pointer",borderRadius:"4px"},checkbox:{marginRight:"0.75rem",cursor:"pointer"},lineItemText:{fontSize:"0.9rem",color:"#333"},lineItemAmount:{color:"#666",fontWeight:"bold"},footer:{display:"flex",justifyContent:"flex-end",gap:"1rem",marginTop:"1.5rem",paddingTop:"1rem",borderTop:"1px solid #eee"},cancelBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",color:"#666",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},submitBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"none",background:"#e94560",color:"white",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},error:{marginTop:"1rem",padding:"0.75rem",background:"#fee",color:"#c00",borderRadius:"8px",fontSize:"0.9rem"},noResults:{padding:"1rem",textAlign:"center",color:"#999",fontStyle:"italic"},selectedSummary:{marginTop:"0.5rem",padding:"0.5rem",background:"#e8f4f8",borderRadius:"4px",fontSize:"0.85rem",color:"#1565c0",fontWeight:"bold"},fieldHint:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem",fontStyle:"italic"}},Yhe=[{value:"new",label:"New"},{value:"contacted",label:"Contacted"},{value:"awaiting_credit",label:"Awaiting Credit"},{value:"awaiting_replacement",label:"Awaiting Replacement"},{value:"resolved",label:"Resolved"}],Qhe=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}],$he={new:"#e94560",contacted:"#f0ad4e",awaiting_credit:"#9b59b6",awaiting_replacement:"#8b7ec8",resolved:"#5cb85c"},Zhe={low:"#5cb85c",medium:"#5bc0de",high:"#f0ad4e",urgent:"#e94560"};function DK({disputeId:n,onClose:e,onUpdate:t}){var ee;const{token:r,user:i}=gn(),o=pi(),[a,l]=k.useState(""),[d,c]=k.useState(!1),[u,f]=k.useState(!1),[p,g]=k.useState(""),[m,y]=k.useState(""),[v,x]=k.useState(null),[w,S]=k.useState(""),[_,b]=k.useState(!1),[C,T]=k.useState(null),[F,A]=k.useState(!1),[D,P]=k.useState(""),[L,W]=k.useState(""),[O,U]=k.useState(null),{data:M}=Oe({queryKey:["settings"],queryFn:async()=>{const Z=await fetch("/api/settings",{headers:{Authorization:`Bearer ${r}`}});return Z.ok?Z.json():{}},enabled:!!r,staleTime:6e4}),{data:I,isLoading:H,error:z}=Oe({queryKey:["dispute",n],queryFn:async()=>{const Z=await fetch(`/api/disputes/${n}`,{headers:{Authorization:`Bearer ${r}`}});if(!Z.ok)throw new Error("Failed to fetch dispute");return Z.json()},enabled:!!r}),G=Ue({mutationFn:async Z=>{const ge=await fetch(`/api/disputes/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(Z)});if(!ge.ok){const Te=await ge.json();throw new Error(Te.detail||"Failed to update dispute")}return ge.json()},onSuccess:()=>{o.invalidateQueries({queryKey:["dispute",n]}),o.invalidateQueries({queryKey:["disputes"]}),o.invalidateQueries({queryKey:["dispute-stats"]}),t&&t(),l("")}}),te=Ue({mutationFn:async()=>{const Z=await fetch(`/api/disputes/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}});if(!Z.ok){const ge=await Z.json();throw new Error(ge.detail||"Failed to delete dispute")}return Z.json()},onSuccess:()=>{o.invalidateQueries({queryKey:["disputes"]}),o.invalidateQueries({queryKey:["dispute-stats"]}),t&&t(),e()}}),re=Z=>{G.mutate({status:Z.toUpperCase()})},me=Z=>{G.mutate({priority:Z.toLowerCase()})},J=()=>{if(!a.trim()){alert("Please enter a note");return}G.mutate({supplier_response:a.trim()})},ne=()=>{confirm(`Are you sure you want to permanently delete this dispute? - -Dispute: ${I==null?void 0:I.title} -Invoice #${I==null?void 0:I.invoice_number} - -This action cannot be undone.`)&&te.mutate()},ye=()=>{I&&(g(I.title),y(I.description||""),f(!0))},ke=()=>{f(!1),g(""),y("")},Ye=()=>{if(!p.trim()){alert("Title cannot be empty");return}G.mutate({title:p.trim(),description:m.trim()||void 0}),f(!1)},De=async()=>{A(!0),U(null),P(""),W("");try{const Z=await fetch(`/api/disputes/${n}/draft-email`,{method:"POST",headers:{Authorization:`Bearer ${r}`}});if(!Z.ok){const Te=await Z.json();throw new Error(Te.detail||"Failed to draft email")}const ge=await Z.json();ge.llm_status==="success"||ge.llm_status==="cached"?(P(ge.email_subject||""),W(ge.email_body||"")):U(ge.error||"AI drafting unavailable")}catch(Z){U(Z instanceof Error?Z.message:"Failed to draft email")}finally{A(!1)}},qe=async()=>{if(!v){alert("Please select a file");return}b(!0);try{const Z=new FormData;Z.append("file",v);const ge=new URLSearchParams;ge.append("attachment_type","photo"),w.trim()&&ge.append("description",w.trim());const Te=await fetch(`/api/disputes/${n}/attachments?${ge}`,{method:"POST",headers:{Authorization:`Bearer ${r}`},body:Z});if(!Te.ok){const Be=await Te.json();throw new Error(Be.detail||"Failed to upload attachment")}o.invalidateQueries({queryKey:["dispute",n]}),t&&t(),x(null),S(""),c(!1)}catch(Z){alert(Z instanceof Error?Z.message:"Upload failed")}finally{b(!1)}},ue=Z=>{if(!Z.public_url)return;const ge=`${window.location.origin}${Z.public_url}`;navigator.clipboard.writeText(ge).then(()=>{T(Z.public_hash),setTimeout(()=>T(null),2e3)}).catch(()=>{const Te=document.createElement("textarea");Te.value=ge,document.body.appendChild(Te),Te.select(),document.execCommand("copy"),document.body.removeChild(Te),T(Z.public_hash),setTimeout(()=>T(null),2e3)})},Ze=Z=>{Z.public_url&&window.open(Z.public_url,"_blank")};return H?s.jsx("div",{style:at.modalOverlay,onClick:e,children:s.jsx("div",{style:at.modal,onClick:Z=>Z.stopPropagation(),children:s.jsx("div",{style:at.loading,children:"Loading dispute details..."})})}):z||!I?s.jsx("div",{style:at.modalOverlay,onClick:e,children:s.jsx("div",{style:at.modal,onClick:Z=>Z.stopPropagation(),children:s.jsxs("div",{style:at.error,children:["Error loading dispute: ",(z==null?void 0:z.message)||"Unknown error"]})})}):s.jsx("div",{style:at.modalOverlay,onClick:e,children:s.jsxs("div",{style:at.modal,onClick:Z=>Z.stopPropagation(),children:[s.jsxs("div",{style:at.modalHeader,children:[s.jsxs("div",{children:[s.jsxs("div",{style:at.modalSubtitle,children:[I.supplier_name," - ",s.jsxs("a",{href:`/invoice/${I.invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:at.invoiceLink,children:["Invoice #",I.invoice_number||I.invoice_id]})," - ",s.jsx("span",{style:at.disputeTypeHeader,children:I.dispute_type.replace(/_/g," ").toUpperCase()})]}),u?s.jsx("input",{type:"text",value:p,onChange:Z=>g(Z.target.value),style:{...at.modalTitle,border:"2px solid #e94560",padding:"0.5rem"},maxLength:200}):s.jsx("h2",{style:at.modalTitle,children:I.title})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[u?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:Ye,disabled:G.isPending,style:{...at.deleteBtn,background:"#5cb85c"},type:"button",children:G.isPending?"Saving...":"✓ Save"}),s.jsx("button",{onClick:ke,disabled:G.isPending,style:at.deleteBtn,type:"button",children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:ye,style:{...at.deleteBtn,background:"#5bc0de"},type:"button",title:"Edit title and description",children:"✏️ Edit"}),(i==null?void 0:i.is_admin)&&s.jsx("button",{onClick:ne,disabled:te.isPending,style:at.deleteBtn,type:"button",title:"Delete dispute (Admin only)",children:te.isPending?"...":"🗑️ Delete"})]}),s.jsx("button",{style:at.closeBtn,onClick:e,type:"button",children:"✕"})]})]}),s.jsxs("div",{style:at.modalBody,children:[s.jsxs("div",{style:at.section,children:[s.jsx("div",{style:at.actionGroup,children:s.jsx("div",{style:at.buttonRow,children:Yhe.map(Z=>s.jsx("button",{onClick:()=>re(Z.value),disabled:G.isPending||I.status.toLowerCase()===Z.value,style:{...at.statusButton,...I.status.toLowerCase()===Z.value?{background:$he[Z.value]||"#999",color:"white",fontWeight:"bold"}:{}},children:Z.label},Z.value))})}),s.jsx("div",{style:at.actionGroup,children:s.jsx("div",{style:at.buttonRow,children:Qhe.map(Z=>s.jsx("button",{onClick:()=>me(Z.value),disabled:G.isPending||I.priority.toLowerCase()===Z.value,style:{...at.statusButton,...I.priority.toLowerCase()===Z.value?{background:Zhe[Z.value]||"#999",color:"white",fontWeight:"bold"}:{}},children:Z.label},Z.value))})})]}),s.jsxs("div",{style:at.section,children:[s.jsx("h3",{style:at.sectionTitle,children:"Financial Impact"}),s.jsxs("div",{style:at.financialGrid,children:[s.jsxs("div",{style:at.financialCard,children:[s.jsx("div",{style:at.financialLabel,children:"Disputed Amount"}),s.jsxs("div",{style:at.financialValue,children:["£",Number(I.disputed_amount).toFixed(2)]})]}),I.expected_amount!=null&&s.jsxs("div",{style:at.financialCard,children:[s.jsx("div",{style:at.financialLabel,children:"Expected Amount"}),s.jsxs("div",{style:at.financialValue,children:["£",Number(I.expected_amount).toFixed(2)]})]}),s.jsxs("div",{style:at.financialCard,children:[s.jsx("div",{style:at.financialLabel,children:"Difference"}),s.jsxs("div",{style:{...at.financialValue,color:"#e94560"},children:["£",Number(Math.abs(I.difference_amount)).toFixed(2)]})]})]})]}),(M==null?void 0:M.llm_enabled)&&(M==null?void 0:M.anthropic_api_key_set)&&s.jsxs("div",{style:at.section,children:[s.jsxs("div",{style:at.sectionHeader,children:[s.jsx("h3",{style:at.sectionTitle,children:"Draft Supplier Email"}),s.jsx("button",{onClick:De,disabled:F,style:{...at.secondaryBtn,background:"#7952b3",color:"white",border:"none",opacity:F?.6:1},children:F?"Drafting...":"✨ Draft Email"})]}),O&&s.jsx("div",{style:{padding:"0.5rem 0.75rem",background:"#fee",color:"#c00",borderRadius:"6px",fontSize:"0.85rem",marginBottom:"0.75rem"},children:O}),D&&s.jsxs("div",{style:{background:"#f3effc",borderRadius:"8px",padding:"1rem",border:"1px solid #d4c5f0"},children:[s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("label",{style:{...at.label,fontSize:"0.8rem",color:"#7952b3"},children:"Subject"}),s.jsx("input",{type:"text",value:D,onChange:Z=>P(Z.target.value),style:{...at.input,marginBottom:0,borderColor:"#d4c5f0"}})]}),s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("label",{style:{...at.label,fontSize:"0.8rem",color:"#7952b3"},children:"Body"}),s.jsx("textarea",{value:L,onChange:Z=>W(Z.target.value),style:{...at.textarea,minHeight:"180px",marginBottom:0,borderColor:"#d4c5f0"}})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`Subject: ${D} - -${L}`)},style:{...at.secondaryBtn,fontSize:"0.85rem"},children:"Copy to Clipboard"}),s.jsx("button",{onClick:()=>{window.open(`mailto:?subject=${encodeURIComponent(D)}&body=${encodeURIComponent(L)}`)},style:{...at.primaryBtn,fontSize:"0.85rem",padding:"0.5rem 1rem"},children:"Open in Email Client"})]}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#7952b3",marginTop:"0.5rem",fontStyle:"italic"},children:"AI-generated draft — review and edit before sending"})]})]}),s.jsxs("div",{style:at.section,children:[s.jsx("h3",{style:at.sectionTitle,children:"Description"}),u?s.jsx("textarea",{value:m,onChange:Z=>y(Z.target.value),style:{...at.textarea,width:"100%",minHeight:"100px"},placeholder:"Detailed description of the dispute (optional)..."}):s.jsx("p",{style:at.description,children:I.description||"No description provided"})]}),I.line_items.length>0&&s.jsxs("div",{style:at.section,children:[s.jsxs("h3",{style:at.sectionTitle,children:["Disputed Line Items (",I.line_items.length,")"]}),s.jsx("div",{style:at.tableContainer,children:s.jsxs("table",{style:at.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:at.th,children:"Product"}),s.jsx("th",{style:at.th,children:"Qty"}),s.jsx("th",{style:at.th,children:"Unit Price"}),s.jsx("th",{style:at.th,children:"Total"})]})}),s.jsx("tbody",{children:I.line_items.map(Z=>s.jsxs("tr",{children:[s.jsxs("td",{style:at.td,children:[s.jsx("div",{children:Z.product_name}),Z.product_code&&s.jsx("div",{style:at.productCode,children:Z.product_code})]}),s.jsx("td",{style:at.td,children:Z.quantity_ordered!=null?Number(Z.quantity_ordered).toFixed(2):"-"}),s.jsx("td",{style:at.td,children:Z.unit_price_charged!=null?`£${Number(Z.unit_price_charged).toFixed(2)}`:"-"}),s.jsxs("td",{style:at.td,children:["£",Number(Z.total_charged).toFixed(2)]})]},Z.id))})]})})]}),s.jsxs("div",{style:at.section,children:[s.jsxs("div",{style:at.sectionHeader,children:[s.jsxs("h3",{style:at.sectionTitle,children:["Attachments (",I.attachments.length,")"]}),s.jsx("button",{style:at.secondaryBtn,onClick:()=>c(!d),children:d?"Cancel":"+ Upload"})]}),d&&s.jsx("div",{style:at.uploadSection,children:s.jsxs("div",{style:at.uploadForm,children:[s.jsxs("div",{style:at.formGroup,children:[s.jsx("input",{type:"file",onChange:Z=>{var ge;return x(((ge=Z.target.files)==null?void 0:ge[0])||null)},accept:"image/*,.pdf,.doc,.docx,.eml,.msg",style:at.fileInput}),v&&s.jsxs("span",{style:at.selectedFile,children:["Selected: ",v.name," (",(v.size/1024).toFixed(1)," KB)"]})]}),s.jsx("div",{style:at.formGroup,children:s.jsx("input",{type:"text",value:w,onChange:Z=>S(Z.target.value),placeholder:"Description (optional)",style:at.input})}),s.jsx("button",{onClick:qe,disabled:!v||_,style:{...at.primaryBtn,opacity:!v||_?.6:1},children:_?"Uploading...":"Upload"})]})}),I.attachments.length===0?s.jsx("p",{style:at.empty,children:"No attachments yet. Upload photos of damaged items to share with suppliers."}):s.jsx("div",{style:at.attachmentList,children:I.attachments.map(Z=>s.jsxs("div",{style:at.attachmentItem,children:[s.jsxs("div",{style:at.attachmentInfo,children:[s.jsxs("span",{style:at.attachmentName,children:[Z.file_type.startsWith("image/")?"🖼️":"📎"," ",Z.file_name]}),s.jsxs("span",{style:at.attachmentMeta,children:[(Z.file_size_bytes/1024).toFixed(1)," KB •",new Date(Z.uploaded_at).toLocaleDateString()," by ",Z.uploaded_by_username||"Unknown"]}),Z.description&&s.jsx("span",{style:at.attachmentDesc,children:Z.description})]}),s.jsx("div",{style:at.attachmentActions,children:Z.public_url&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>Ze(Z),style:at.actionBtn,title:"View in new tab",children:"View"}),s.jsx("button",{onClick:()=>ue(Z),style:{...at.actionBtn,background:C===Z.public_hash?"#5cb85c":"#e94560"},title:"Copy shareable link for email",children:C===Z.public_hash?"Copied!":"Copy Link"})]})})]},Z.id))}),I.attachments.length>0&&s.jsx("p",{style:at.attachmentHint,children:'Use "Copy Link" to get a shareable URL that can be included in emails to suppliers.'})]}),s.jsxs("div",{style:at.section,children:[s.jsx("h3",{style:at.sectionTitle,children:"Activity & Notes"}),I.activity_log.length===0?s.jsx("p",{style:at.empty,children:"No activity logged"}):s.jsx("div",{style:at.chatLog,children:I.activity_log.map(Z=>Z.activity_type==="status_change"||Z.activity_type==="priority_change"||Z.activity_type==="created"?s.jsxs("div",{style:at.logItem,children:[s.jsx("span",{style:at.logMessage,children:Z.description}),s.jsxs("span",{style:at.logMeta,children:[new Date(Z.created_at).toLocaleString()," - ",Z.created_by_username||"System"]})]},Z.id):s.jsxs("div",{style:at.chatItem,children:[s.jsx("div",{style:at.chatMessage,children:Z.description}),s.jsxs("div",{style:at.chatFooter,children:[s.jsx("span",{style:at.chatTime,children:new Date(Z.created_at).toLocaleString()}),s.jsxs("span",{style:at.chatUser,children:[" - ",Z.created_by_username||"System"]})]})]},Z.id))}),s.jsxs("div",{style:at.addNoteSection,children:[s.jsx("label",{style:at.label,children:"Add Note"}),s.jsx("textarea",{value:a,onChange:Z=>l(Z.target.value),style:at.textarea,placeholder:"Add a note about this dispute...",rows:3}),s.jsx("button",{style:at.primaryBtn,onClick:J,disabled:G.isPending||!a.trim(),children:"Add Note"})]})]}),G.isError&&s.jsxs("div",{style:at.errorBox,children:["Error: ",((ee=G.error)==null?void 0:ee.message)||"Failed to update dispute"]})]})]})})}const at={modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3,padding:"1rem"},modal:{background:"white",borderRadius:"12px",maxWidth:"900px",width:"100%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",padding:"1.5rem",borderBottom:"1px solid #eee",position:"sticky",top:0,background:"white",zIndex:1},modalTitle:{margin:0,marginTop:"0.5rem",color:"#1a1a2e",fontSize:"1.25rem"},modalSubtitle:{color:"#666",fontSize:"0.9rem"},invoiceLink:{color:"#e94560",textDecoration:"none",fontWeight:"bold"},disputeTypeHeader:{fontSize:"0.7rem",fontWeight:"bold",color:"#666",letterSpacing:"0.5px"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},deleteBtn:{background:"#dc3545",color:"white",border:"none",padding:"0.5rem 1rem",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem",fontWeight:500,transition:"background 0.2s"},modalBody:{padding:"1.5rem",flex:1,overflow:"auto"},loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px",margin:"1rem"},section:{marginBottom:"2rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},sectionTitle:{margin:0,marginBottom:"1rem",color:"#1a1a2e",fontSize:"1rem",fontWeight:"bold"},financialGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(180px, 1fr))",gap:"1rem"},financialCard:{display:"flex",flexDirection:"column",padding:"1.25rem",background:"white",border:"1px solid #e0e0e0",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.08)"},financialLabel:{fontSize:"0.75rem",color:"#666",marginBottom:"0.5rem",textTransform:"uppercase",fontWeight:"600",letterSpacing:"0.5px"},financialValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#1a1a2e"},description:{margin:0,color:"#333",lineHeight:1.6},tableContainer:{overflowX:"auto"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{textAlign:"left",padding:"0.75rem",background:"#f5f5f5",fontWeight:"bold",color:"#1a1a2e",borderBottom:"2px solid #ddd"},td:{padding:"0.75rem",borderBottom:"1px solid #eee",color:"#333"},productCode:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},empty:{padding:"1rem",textAlign:"center",color:"#999",fontStyle:"italic"},attachmentList:{display:"flex",flexDirection:"column",gap:"0.5rem"},attachmentItem:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem",background:"#f9f9f9",borderRadius:"8px"},attachmentName:{color:"#1a1a2e",fontWeight:"500"},attachmentMeta:{fontSize:"0.8rem",color:"#666"},chatLog:{display:"flex",flexDirection:"column",gap:"0.75rem",marginBottom:"1.5rem",padding:"1rem",background:"#f5f5f5",borderRadius:"8px"},logItem:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.5rem 0",fontSize:"0.8rem",color:"#999"},logMessage:{color:"#666",fontSize:"0.8rem"},logMeta:{fontSize:"0.7rem",color:"#999",whiteSpace:"nowrap",marginLeft:"1rem"},chatItem:{padding:"1rem",background:"white",borderRadius:"8px",border:"1px solid #e0e0e0",boxShadow:"0 1px 3px rgba(0,0,0,0.05)"},chatMessage:{color:"#1a1a2e",fontSize:"1rem",lineHeight:1.5,marginBottom:"0.5rem"},chatFooter:{display:"flex",justifyContent:"flex-end",alignItems:"center",fontSize:"0.75rem",color:"#999"},chatUser:{fontSize:"0.75rem",color:"#999"},chatTime:{fontSize:"0.75rem",color:"#999"},addNoteSection:{marginTop:"1.5rem",paddingTop:"1.5rem",borderTop:"1px solid #eee"},buttonRow:{display:"flex",gap:"0.75rem",flexWrap:"wrap",justifyContent:"center"},statusButton:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",cursor:"pointer",fontSize:"1rem",fontWeight:"500",transition:"all 0.2s",color:"#333"},actionGroup:{marginBottom:"1.5rem"},label:{display:"block",marginBottom:"0.5rem",fontWeight:"bold",color:"#1a1a2e",fontSize:"0.9rem"},input:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box",marginBottom:"0.75rem"},textarea:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit",marginBottom:"0.75rem"},primaryBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"none",background:"#e94560",color:"white",cursor:"pointer",fontWeight:"bold",fontSize:"1rem",whiteSpace:"nowrap"},secondaryBtn:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",color:"#666",cursor:"pointer",fontWeight:"bold",fontSize:"0.9rem"},errorBox:{marginTop:"1rem",padding:"0.75rem",background:"#fee",color:"#c00",borderRadius:"8px",fontSize:"0.9rem"},uploadSection:{padding:"1rem",background:"#f9f9f9",borderRadius:"8px",marginBottom:"1rem"},uploadForm:{display:"flex",flexDirection:"column",gap:"1rem"},formGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},fileInput:{padding:"0.5rem",border:"2px dashed #ccc",borderRadius:"8px",background:"white",cursor:"pointer"},selectedFile:{fontSize:"0.85rem",color:"#666",fontStyle:"italic"},attachmentInfo:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},attachmentDesc:{fontSize:"0.8rem",color:"#666",fontStyle:"italic"},attachmentActions:{display:"flex",gap:"0.5rem",flexShrink:0},actionBtn:{padding:"0.4rem 0.75rem",borderRadius:"6px",border:"none",background:"#e94560",color:"white",cursor:"pointer",fontSize:"0.8rem",fontWeight:"500",whiteSpace:"nowrap",transition:"background 0.2s"},attachmentHint:{marginTop:"1rem",padding:"0.75rem",background:"#e8f4f8",borderRadius:"6px",fontSize:"0.85rem",color:"#0c5460",fontStyle:"italic"}},Jhe={price_discrepancy:"Price Discrepancy",short_delivery:"Short Delivery",wrong_product:"Wrong Product",quality_issue:"Quality Issue",calculation_error:"Calculation Error",missing_items:"Missing Items",damaged_goods:"Damaged Goods",other:"Other"},efe={NEW:"#17a2b8",OPEN:"#17a2b8",CONTACTED:"#6c757d",IN_PROGRESS:"#ffc107",AWAITING_CREDIT:"#fd7e14",AWAITING_REPLACEMENT:"#fd7e14",ESCALATED:"#dc3545"};function tfe({supplierId:n,supplierName:e,creditNoteInvoiceId:t,creditNoteNumber:r,creditNoteAmount:i,onClose:o,onSuccess:a}){var _;const{token:l}=gn(),d=pi(),[c,u]=k.useState(null),[f,p]=k.useState(i?Math.abs(i).toFixed(2):""),[g,m]=k.useState(""),{data:y,isLoading:v}=Oe({queryKey:["open-disputes",n],queryFn:async()=>{const b=await fetch(`/api/disputes/supplier/${n}/open`,{headers:{Authorization:`Bearer ${l}`}});if(!b.ok)throw new Error("Failed to fetch disputes");return b.json()},enabled:!!n}),x=Ue({mutationFn:async()=>{if(!c)throw new Error("No dispute selected");const b=await fetch(`/api/disputes/${c}/link-credit-note`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify({credit_note_invoice_id:t,resolved_amount:f?parseFloat(f):void 0,resolution_notes:g||void 0})});if(!b.ok){const C=await b.json();throw new Error(C.detail||"Failed to link dispute")}return b.json()},onSuccess:()=>{d.invalidateQueries({queryKey:["disputes"]}),d.invalidateQueries({queryKey:["dispute-stats"]}),d.invalidateQueries({queryKey:["open-disputes",n]}),d.invalidateQueries({queryKey:["invoice",t]}),d.invalidateQueries({queryKey:["invoices"]}),a&&a(),o()}}),w=b=>{if(b.preventDefault(),!c){alert("Please select a dispute to link");return}x.mutate()},S=b=>new Date(b).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"});return s.jsx("div",{style:kn.modalOverlay,onClick:o,children:s.jsxs("div",{style:kn.modal,onClick:b=>b.stopPropagation(),children:[s.jsxs("div",{style:kn.modalHeader,children:[s.jsx("h2",{style:kn.modalTitle,children:"Link Credit Note to Dispute"}),s.jsx("button",{style:kn.closeBtn,onClick:o,type:"button",children:"✕"})]}),s.jsxs("div",{style:kn.content,children:[s.jsxs("div",{style:kn.infoBox,children:[s.jsxs("div",{style:kn.infoRow,children:[s.jsx("span",{style:kn.infoLabel,children:"Credit Note:"}),s.jsxs("span",{style:kn.infoValue,children:["#",r||t]})]}),s.jsxs("div",{style:kn.infoRow,children:[s.jsx("span",{style:kn.infoLabel,children:"Supplier:"}),s.jsx("span",{style:kn.infoValue,children:e||"Unknown"})]}),i&&s.jsxs("div",{style:kn.infoRow,children:[s.jsx("span",{style:kn.infoLabel,children:"Amount:"}),s.jsxs("span",{style:kn.infoValue,children:["£",Math.abs(i).toFixed(2)]})]})]}),s.jsxs("div",{style:kn.section,children:[s.jsx("h3",{style:kn.sectionTitle,children:"Select Open Dispute"}),v?s.jsx("div",{style:kn.loading,children:"Loading disputes..."}):!y||y.length===0?s.jsx("div",{style:kn.emptyState,children:"No open disputes found for this supplier."}):s.jsx("div",{style:kn.disputeList,children:y.map(b=>s.jsxs("label",{style:{...kn.disputeItem,borderColor:c===b.id?"#e94560":"#eee",background:c===b.id?"#fff5f7":"white"},children:[s.jsx("input",{type:"radio",name:"dispute",value:b.id,checked:c===b.id,onChange:()=>u(b.id),style:kn.radio}),s.jsxs("div",{style:kn.disputeContent,children:[s.jsxs("div",{style:kn.disputeHeader,children:[s.jsx("span",{style:kn.disputeTitle,children:b.title}),s.jsx("span",{style:{...kn.statusBadge,background:efe[b.status]||"#6c757d"},children:b.status.replace("_"," ")})]}),s.jsxs("div",{style:kn.disputeMeta,children:[s.jsx("span",{style:kn.disputeType,children:Jhe[b.dispute_type]||b.dispute_type}),s.jsxs("span",{style:kn.disputeAmount,children:["£",b.disputed_amount.toFixed(2)]}),s.jsxs("span",{style:kn.disputeDate,children:["Opened ",S(b.opened_at)]}),b.invoice_number&&s.jsxs("span",{style:kn.invoiceRef,children:["Invoice #",b.invoice_number]})]})]})]},b.id))})]}),c&&s.jsxs("div",{style:kn.section,children:[s.jsxs("div",{style:kn.formGroup,children:[s.jsx("label",{style:kn.label,children:"Resolved Amount (£)"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:f,onChange:b=>p(b.target.value),style:kn.input,placeholder:"0.00"}),s.jsx("div",{style:kn.hint,children:"Leave as-is to use credit note amount"})]}),s.jsxs("div",{style:kn.formGroup,children:[s.jsx("label",{style:kn.label,children:"Resolution Notes (optional)"}),s.jsx("textarea",{value:g,onChange:b=>m(b.target.value),style:kn.textarea,placeholder:"Any additional notes about the resolution...",rows:3})]})]})]}),s.jsxs("div",{style:kn.footer,children:[s.jsx("button",{type:"button",onClick:o,style:kn.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:w,style:{...kn.submitBtn,opacity:!c||x.isPending?.5:1,cursor:!c||x.isPending?"not-allowed":"pointer"},disabled:!c||x.isPending,children:x.isPending?"Linking...":"Link & Resolve Dispute"})]}),x.isError&&s.jsxs("div",{style:kn.error,children:["Error: ",((_=x.error)==null?void 0:_.message)||"Failed to link dispute"]})]})})}const kn={modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3,padding:"1rem"},modal:{background:"white",borderRadius:"12px",maxWidth:"600px",width:"100%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},modalTitle:{margin:0,color:"#1a1a2e",fontSize:"1.25rem"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},content:{padding:"1.5rem",flex:1,overflow:"auto"},infoBox:{background:"#f8f9fa",padding:"1rem",borderRadius:"8px",marginBottom:"1.5rem",border:"1px solid #e9ecef"},infoRow:{display:"flex",justifyContent:"space-between",marginBottom:"0.5rem"},infoLabel:{color:"#666",fontWeight:"500"},infoValue:{fontWeight:"600",color:"#1a1a2e"},section:{marginBottom:"1.5rem"},sectionTitle:{fontSize:"1rem",fontWeight:"600",color:"#1a1a2e",marginBottom:"0.75rem"},loading:{padding:"2rem",textAlign:"center",color:"#666"},emptyState:{padding:"2rem",textAlign:"center",color:"#666",background:"#f8f9fa",borderRadius:"8px",fontStyle:"italic"},disputeList:{display:"flex",flexDirection:"column",gap:"0.75rem",maxHeight:"250px",overflow:"auto"},disputeItem:{display:"flex",alignItems:"flex-start",padding:"1rem",border:"2px solid #eee",borderRadius:"8px",cursor:"pointer",transition:"border-color 0.2s, background 0.2s"},radio:{marginRight:"1rem",marginTop:"0.25rem",cursor:"pointer"},disputeContent:{flex:1},disputeHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"0.5rem",gap:"0.5rem"},disputeTitle:{fontWeight:"600",color:"#1a1a2e",flex:1},statusBadge:{padding:"0.2rem 0.5rem",borderRadius:"4px",fontSize:"0.7rem",fontWeight:"600",color:"white",textTransform:"uppercase",whiteSpace:"nowrap"},disputeMeta:{display:"flex",flexWrap:"wrap",gap:"0.75rem",fontSize:"0.85rem",color:"#666"},disputeType:{background:"#e9ecef",padding:"0.15rem 0.5rem",borderRadius:"4px"},disputeAmount:{fontWeight:"600",color:"#dc3545"},disputeDate:{color:"#999"},invoiceRef:{color:"#666"},formGroup:{marginBottom:"1rem"},label:{display:"block",marginBottom:"0.5rem",fontWeight:"600",color:"#1a1a2e",fontSize:"0.9rem"},input:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",boxSizing:"border-box"},textarea:{width:"100%",padding:"0.75rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit"},hint:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem",fontStyle:"italic"},footer:{display:"flex",justifyContent:"flex-end",gap:"1rem",padding:"1rem 1.5rem",borderTop:"1px solid #eee",flexShrink:0},cancelBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"1px solid #ccc",background:"white",color:"#666",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},submitBtn:{padding:"0.75rem 1.5rem",borderRadius:"8px",border:"none",background:"#28a745",color:"white",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},error:{margin:"0 1.5rem 1rem",padding:"0.75rem",background:"#fee",color:"#c00",borderRadius:"8px",fontSize:"0.9rem"}};function TT({isOpen:n,onClose:e,onSaved:t,poId:r,defaultSupplierId:i,defaultDate:o}){const{token:a}=gn(),[l,d]=k.useState([]),[c,u]=k.useState(i||0),[f,p]=k.useState(o||new Date().toISOString().slice(0,10)),[g,m]=k.useState("itemised"),[y,v]=k.useState("DRAFT"),[x,w]=k.useState(null),[S,_]=k.useState(""),[b,C]=k.useState(""),[T,F]=k.useState([]),[A,D]=k.useState(null),[P,L]=k.useState(""),[W,O]=k.useState([]),[U,M]=k.useState(!1),[I,H]=k.useState(!1),[z,G]=k.useState(null),[te,re]=k.useState(null),[me,J]=k.useState(!1),[ne,ye]=k.useState(!1),ke=k.useRef(null),Ye=k.useRef(null);k.useEffect(()=>{a&&fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${a}`}}).then(Q=>Q.json()).then(Q=>d(Q.suppliers||Q||[])).catch(()=>{})},[a]),k.useEffect(()=>{a&&fetch("/api/settings/",{headers:{Authorization:`Bearer ${a}`}}).then(Q=>Q.json()).then(Q=>ye(!!(Q.smtp_host&&Q.smtp_from_email))).catch(()=>ye(!1))},[a]),k.useEffect(()=>{!r||!a||(J(!0),fetch(`/api/purchase-orders/${r}`,{headers:{Authorization:`Bearer ${a}`}}).then(Q=>{if(!Q.ok)throw new Error("Failed to load");return Q.json()}).then(Q=>{u(Q.supplier_id),p(Q.order_date),m(Q.order_type),v(Q.status),w(Q.total_amount),_(Q.order_reference||""),C(Q.notes||""),D(Q.attachment_original_name||null),F((Q.line_items||[]).map((X,pe)=>({id:X.id,product_id:X.product_id,product_code:X.product_code,description:X.description,unit:X.unit,unit_price:X.unit_price,quantity:X.quantity,total:X.total,line_number:X.line_number??pe,source:X.source||"manual"})))}).catch(()=>re("Failed to load purchase order")).finally(()=>J(!1)))},[r,a]),k.useEffect(()=>{n&&!r&&(u(i||0),p(o||new Date().toISOString().slice(0,10)),m("itemised"),v("DRAFT"),w(null),_(""),C(""),F([]),D(null),re(null),L(""),O([]))},[n,r,i,o]),k.useEffect(()=>{if(ke.current&&clearTimeout(ke.current),!P||P.length<2||!a){O([]);return}return ke.current=setTimeout(()=>{const Q=new URLSearchParams({query:P});c&&Q.append("supplier_id",String(c)),fetch(`/api/purchase-orders/products/search?${Q}`,{headers:{Authorization:`Bearer ${a}`}}).then(X=>X.json()).then(O).catch(()=>{})},300),()=>{ke.current&&clearTimeout(ke.current)}},[P,c,a]);const De=()=>{F(Q=>[...Q,{description:"",unit_price:0,quantity:1,total:0,line_number:Q.length,source:"manual"}])},qe=Q=>{F(X=>[...X,{product_id:Q.id||null,product_code:Q.product_code,description:Q.name,unit:Q.unit,unit_price:Q.last_price||0,quantity:1,total:Q.last_price||0,line_number:X.length,source:"search"}]),L(""),O([])},ue=(Q,X,pe)=>{F(we=>{const Ne=[...we],st={...Ne[Q],[X]:pe};return(X==="unit_price"||X==="quantity")&&(st.total=parseFloat((st.unit_price*st.quantity).toFixed(2))),Ne[Q]=st,Ne})},Ze=Q=>{F(X=>X.filter((pe,we)=>we!==Q))},ee=k.useCallback(()=>g==="single_value"?x||0:T.reduce((Q,X)=>Q+(X.total||0),0),[g,x,T]),Z=async Q=>{if(!a||!c||!f){re("Please fill in supplier and date");return}if(g==="itemised"&&T.length===0){re("Please add at least one line item");return}if(g==="single_value"&&(!x||x<=0)){re("Please enter a valid order value");return}M(!0),re(null);const X={supplier_id:c,order_date:f,order_type:g,status:Q||y,order_reference:S||null,notes:b||null,line_items:g==="itemised"?T.map((pe,we)=>({product_id:pe.product_id||null,product_code:pe.product_code||null,description:pe.description,unit:pe.unit||null,unit_price:pe.unit_price,quantity:pe.quantity,total:pe.total,line_number:we,source:pe.source})):[]};g==="single_value"&&(X.total_amount=x);try{const pe=r?`/api/purchase-orders/${r}`:"/api/purchase-orders/",Ne=await fetch(pe,{method:r?"PUT":"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(X)});if(!Ne.ok){const st=await Ne.json().catch(()=>({}));throw new Error(st.detail||"Failed to save")}t(),e()}catch(pe){re(pe.message||"Failed to save purchase order")}finally{M(!1)}},ge=async Q=>{var we;const X=(we=Q.target.files)==null?void 0:we[0];if(!X||!r||!a)return;const pe=new FormData;pe.append("file",X);try{const Ne=await fetch(`/api/purchase-orders/${r}/attachment`,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:pe});if(!Ne.ok)throw new Error("Upload failed");const st=await Ne.json();D(st.attachment_original_name)}catch{re("Failed to upload attachment")}},Te=async()=>{if(!(!r||!a))try{await fetch(`/api/purchase-orders/${r}/attachment`,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}}),D(null)}catch{re("Failed to remove attachment")}},Be=async()=>{if(!(!r||!a)&&confirm("Delete this purchase order?"))try{const Q=await fetch(`/api/purchase-orders/${r}`,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!Q.ok){const X=await Q.json().catch(()=>({}));throw new Error(X.detail||"Delete failed")}t(),e()}catch(Q){re(Q.message||"Failed to delete")}},he=async()=>{if(a)if(r)await Z(),window.open(`/api/purchase-orders/${r}/preview?token=${encodeURIComponent(a||"")}`,"_blank");else{if(!c||!f){re("Please fill in supplier and date");return}M(!0),re(null);const Q={supplier_id:c,order_date:f,order_type:g,status:"DRAFT",order_reference:S||null,notes:b||null,line_items:g==="itemised"?T.map((X,pe)=>({product_id:X.product_id||null,product_code:X.product_code||null,description:X.description,unit:X.unit||null,unit_price:X.unit_price,quantity:X.quantity,total:X.total,line_number:pe,source:X.source})):[],...g==="single_value"?{total_amount:x}:{}};try{const X=await fetch("/api/purchase-orders/",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!X.ok)throw new Error("Failed to save");const pe=await X.json();window.open(`/api/purchase-orders/${pe.id}/preview?token=${encodeURIComponent(a||"")}`,"_blank"),t(),e()}catch(X){re(X.message||"Failed to save")}finally{M(!1)}}},He=async()=>{if(!a||!c||!f){re("Please fill in supplier and date");return}H(!0),re(null),G(null);const Q={supplier_id:c,order_date:f,order_type:g,status:y==="DRAFT"?"DRAFT":y,order_reference:S||null,notes:b||null,line_items:g==="itemised"?T.map((X,pe)=>({product_id:X.product_id||null,product_code:X.product_code||null,description:X.description,unit:X.unit||null,unit_price:X.unit_price,quantity:X.quantity,total:X.total,line_number:pe,source:X.source})):[],...g==="single_value"?{total_amount:x}:{}};try{const X=r?`/api/purchase-orders/${r}`:"/api/purchase-orders/",we=await fetch(X,{method:r?"PUT":"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!we.ok)throw new Error("Failed to save PO");const Ne=await we.json(),st=await fetch(`/api/purchase-orders/${Ne.id}/send-email`,{method:"POST",headers:{Authorization:`Bearer ${a}`}});if(!st.ok){const Re=await st.json().catch(()=>({}));throw new Error(Re.detail||"Failed to send email")}const Ve=await st.json();G(Ve.message||"Email sent successfully"),t(),setTimeout(()=>e(),1500)}catch(X){re(X.message||"Failed to send email")}finally{H(!1)}},Ge=l.find(Q=>Q.id===c),K=!!(Ge!=null&&Ge.order_email)&≠if(!n)return null;const de=!r||y==="DRAFT"||y==="PENDING",Y=ee();return s.jsx("div",{style:At.overlay,onClick:e,children:s.jsxs("div",{style:At.modal,onClick:Q=>Q.stopPropagation(),children:[s.jsxs("div",{style:At.header,children:[s.jsxs("h2",{style:At.title,children:[r?`Purchase Order #${r}`:"New Purchase Order",r&&s.jsx("span",{style:{...At.statusBadge,...nfe(y)},children:y})]}),s.jsx("button",{style:At.closeBtn,onClick:e,children:"×"})]}),s.jsx("div",{style:At.body,children:me?s.jsx("p",{children:"Loading..."}):s.jsxs(s.Fragment,{children:[te&&s.jsx("div",{style:At.error,children:te}),z&&s.jsx("div",{style:At.success,children:z}),s.jsxs("div",{style:At.fieldRow,children:[s.jsxs("div",{style:At.field,children:[s.jsx("label",{style:At.label,children:"Date"}),s.jsx("input",{type:"date",value:f,onChange:Q=>p(Q.target.value),style:At.input,disabled:!de})]}),s.jsxs("div",{style:At.field,children:[s.jsx("label",{style:At.label,children:"Supplier"}),s.jsxs("select",{value:c,onChange:Q=>u(Number(Q.target.value)),style:At.input,disabled:!de,children:[s.jsx("option",{value:0,children:"Select supplier..."}),l.map(Q=>s.jsx("option",{value:Q.id,children:Q.name},Q.id))]})]})]}),s.jsx("div",{style:At.fieldRow,children:s.jsxs("div",{style:{...At.field,flex:1},children:[s.jsx("label",{style:At.label,children:"Notes"}),s.jsx("textarea",{value:b,onChange:Q=>C(Q.target.value),style:{...At.input,minHeight:"50px",resize:"vertical"},disabled:!de,placeholder:"Optional notes..."})]})}),s.jsxs("div",{style:At.tabs,children:[s.jsx("button",{style:{...At.tab,...g==="itemised"?At.tabActive:{}},onClick:()=>de&&m("itemised"),disabled:!de,children:"Itemised Order"}),s.jsx("button",{style:{...At.tab,...g==="single_value"?At.tabActive:{}},onClick:()=>de&&m("single_value"),disabled:!de,children:"Single Value"})]}),g==="itemised"?s.jsxs(s.Fragment,{children:[T.length>0&&s.jsx("div",{style:At.tableWrap,children:s.jsxs("table",{style:At.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:At.th,children:"Product"}),s.jsx("th",{style:{...At.th,width:"90px"},children:"Price"}),s.jsx("th",{style:{...At.th,width:"70px"},children:"Qty"}),s.jsx("th",{style:{...At.th,width:"90px"},children:"Total"}),de&&s.jsx("th",{style:{...At.th,width:"36px"}})]})}),s.jsx("tbody",{children:T.map((Q,X)=>s.jsxs("tr",{children:[s.jsx("td",{style:At.td,children:Q.source==="search"?s.jsxs("span",{children:[Q.product_code?`${Q.product_code} - `:"",Q.description]}):s.jsx("input",{value:Q.description,onChange:pe=>ue(X,"description",pe.target.value),style:At.cellInput,placeholder:"Description",disabled:!de})}),s.jsx("td",{style:At.td,children:s.jsx("input",{type:"number",step:"0.01",value:Q.unit_price,onChange:pe=>ue(X,"unit_price",parseFloat(pe.target.value)||0),style:{...At.cellInput,textAlign:"right"},disabled:!de})}),s.jsx("td",{style:At.td,children:s.jsx("input",{type:"number",step:"0.001",value:Q.quantity,onChange:pe=>ue(X,"quantity",parseFloat(pe.target.value)||0),style:{...At.cellInput,textAlign:"right"},disabled:!de})}),s.jsxs("td",{style:{...At.td,textAlign:"right",fontWeight:500},children:["£",Q.total.toFixed(2)]}),de&&s.jsx("td",{style:At.td,children:s.jsx("button",{style:At.removeBtn,onClick:()=>Ze(X),children:"×"})})]},X))})]})}),de&&s.jsxs(s.Fragment,{children:[s.jsx("button",{style:At.addBtn,onClick:De,children:"+ Add Manual Item"}),s.jsxs("div",{style:At.searchSection,children:[s.jsx("label",{style:At.label,children:"Search Products (filtered to supplier)"}),s.jsx("input",{value:P,onChange:Q=>L(Q.target.value),style:At.input,placeholder:"Search by name or code..."}),W.length>0&&s.jsx("div",{style:At.searchResults,children:s.jsxs("table",{style:At.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:At.th,children:"Code"}),s.jsx("th",{style:At.th,children:"Product"}),s.jsx("th",{style:At.th,children:"Unit"}),s.jsx("th",{style:At.th,children:"Price"}),s.jsx("th",{style:At.th})]})}),s.jsx("tbody",{children:W.map((Q,X)=>s.jsxs("tr",{children:[s.jsx("td",{style:At.td,children:Q.product_code||"-"}),s.jsx("td",{style:At.td,children:Q.name}),s.jsx("td",{style:At.td,children:Q.unit||"-"}),s.jsx("td",{style:At.td,children:Q.last_price!=null?`£${Q.last_price.toFixed(2)}`:"-"}),s.jsx("td",{style:At.td,children:s.jsx("button",{style:At.addSearchBtn,onClick:()=>qe(Q),children:"Add"})})]},X))})]})})]})]})]}):s.jsxs("div",{style:{marginTop:"1rem"},children:[s.jsxs("div",{style:At.fieldRow,children:[s.jsxs("div",{style:At.field,children:[s.jsxs("label",{style:At.label,children:["Order Value (","£",")"]}),s.jsx("input",{type:"number",step:"0.01",value:x??"",onChange:Q=>w(parseFloat(Q.target.value)||null),style:At.input,disabled:!de})]}),s.jsxs("div",{style:At.field,children:[s.jsx("label",{style:At.label,children:"Order Ref"}),s.jsx("input",{value:S,onChange:Q=>_(Q.target.value),style:At.input,disabled:!de,placeholder:"Optional"})]})]}),r&&s.jsxs("div",{style:{marginTop:"0.75rem"},children:[s.jsx("label",{style:At.label,children:"Attachment"}),A?s.jsxs("div",{style:At.attachRow,children:[s.jsx("span",{children:A}),de&&s.jsx("button",{style:At.removeBtn,onClick:Te,children:"Remove"})]}):de?s.jsxs(s.Fragment,{children:[s.jsx("button",{style:At.addBtn,onClick:()=>{var Q;return(Q=Ye.current)==null?void 0:Q.click()},children:"Upload File"}),s.jsx("input",{ref:Ye,type:"file",style:{display:"none"},onChange:ge})]}):null]})]}),s.jsx("div",{style:At.totalRow,children:s.jsxs("strong",{children:["Total: ","£",Y.toFixed(2)]})})]})}),s.jsxs("div",{style:At.footer,children:[s.jsx("div",{style:{display:"flex",gap:"0.5rem"},children:r&&de&&(y==="DRAFT"||y==="PENDING")&&s.jsx("button",{style:At.deleteBtn,onClick:Be,children:"Delete"})}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsx("button",{style:At.cancelBtn,onClick:e,children:"Cancel"}),de&&s.jsxs(s.Fragment,{children:[s.jsx("button",{style:At.previewBtn,onClick:he,disabled:U||I,children:U?"Saving...":"Preview"}),K&&s.jsx("button",{style:At.emailBtn,onClick:He,disabled:U||I,children:I?"Sending...":"Save & Email"}),s.jsx("button",{style:At.draftBtn,onClick:()=>Z("DRAFT"),disabled:U||I,children:U?"Saving...":"Save Draft"}),s.jsx("button",{style:At.submitBtn,onClick:()=>Z("PENDING"),disabled:U||I,children:U?"Saving...":"Save & Submit"})]}),!de&&r&&s.jsx("button",{style:At.previewBtn,onClick:()=>window.open(`/api/purchase-orders/${r}/preview?token=${encodeURIComponent(a||"")}`,"_blank"),children:"Preview"})]})]})]})})}function nfe(n){switch(n){case"DRAFT":return{background:"#e0e0e0",color:"#555"};case"PENDING":return{background:"#e3f2fd",color:"#1565c0"};case"LINKED":return{background:"#d4edda",color:"#155724"};case"CLOSED":return{background:"#f5f5f5",color:"#666"};case"CANCELLED":return{background:"#ffebee",color:"#c62828"};default:return{}}}const At={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",maxWidth:"800px",width:"95%",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.2)",display:"flex",flexDirection:"column"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1.5rem",borderBottom:"1px solid #eee",flexShrink:0},title:{margin:0,color:"#1a1a2e",display:"flex",alignItems:"center",gap:"0.75rem",fontSize:"1.2rem"},statusBadge:{fontSize:"0.75rem",padding:"0.2rem 0.6rem",borderRadius:"12px",fontWeight:600},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666",padding:"0.25rem",lineHeight:1},body:{padding:"1.5rem",overflowY:"auto",flex:1},footer:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.5rem",borderTop:"1px solid #eee",flexShrink:0},error:{background:"#ffebee",color:"#c62828",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},fieldRow:{display:"flex",gap:"1rem",marginBottom:"0.75rem"},field:{flex:1},label:{display:"block",fontSize:"0.85rem",fontWeight:600,color:"#555",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},tabs:{display:"flex",gap:"0.5rem",marginTop:"1rem",marginBottom:"0.75rem"},tab:{padding:"0.5rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"#f9f9f9",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},tabActive:{background:"#1a1a2e",color:"white",borderColor:"#1a1a2e"},tableWrap:{overflowX:"auto",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{textAlign:"left",padding:"0.5rem",borderBottom:"2px solid #eee",fontWeight:600,color:"#666",fontSize:"0.8rem"},td:{padding:"0.4rem 0.5rem",borderBottom:"1px solid #f0f0f0",verticalAlign:"middle"},cellInput:{width:"100%",padding:"0.3rem 0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.85rem",boxSizing:"border-box"},removeBtn:{background:"none",border:"none",color:"#c62828",cursor:"pointer",fontSize:"1.1rem",fontWeight:"bold",padding:"0 0.25rem"},addBtn:{background:"none",border:"1px dashed #999",borderRadius:"6px",padding:"0.4rem 0.75rem",cursor:"pointer",color:"#555",fontSize:"0.85rem",marginBottom:"0.75rem"},searchSection:{marginTop:"0.5rem",padding:"0.75rem",background:"#fafafa",borderRadius:"6px",border:"1px solid #eee"},searchResults:{marginTop:"0.5rem",maxHeight:"200px",overflowY:"auto"},addSearchBtn:{background:"#1a1a2e",color:"white",border:"none",borderRadius:"4px",padding:"0.25rem 0.5rem",cursor:"pointer",fontSize:"0.8rem"},totalRow:{textAlign:"right",marginTop:"1rem",fontSize:"1.1rem",padding:"0.75rem",background:"#f5f5f5",borderRadius:"6px"},attachRow:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",background:"#f5f5f5",borderRadius:"6px",fontSize:"0.9rem"},cancelBtn:{padding:"0.5rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"white",cursor:"pointer",fontSize:"0.9rem"},draftBtn:{padding:"0.5rem 1rem",border:"1px solid #999",borderRadius:"6px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},submitBtn:{padding:"0.5rem 1rem",border:"none",borderRadius:"6px",background:"#1a1a2e",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},deleteBtn:{padding:"0.5rem 1rem",border:"1px solid #c62828",borderRadius:"6px",background:"#ffebee",color:"#c62828",cursor:"pointer",fontSize:"0.85rem"},previewBtn:{padding:"0.5rem 1rem",border:"1px solid #1565c0",borderRadius:"6px",background:"#e3f2fd",color:"#1565c0",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},emailBtn:{padding:"0.5rem 1rem",border:"1px solid #2e7d32",borderRadius:"6px",background:"#e8f5e9",color:"#2e7d32",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},success:{background:"#e8f5e9",color:"#2e7d32",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"}};function rfe({ingredientId:n,token:e,onChange:t,onDismissalsChange:r,ingredientName:i,productIngredients:o,lineItemDescription:a,scanSuggestions:l,llmSuggestions:d,llmAnalysing:c,autoApplyFlagIds:u,autoApplyNoneCategoryIds:f}){const p=pi(),[g,m]=k.useState(new Set),[y,v]=k.useState(new Set),[x,w]=k.useState(new Set),[S,_]=k.useState(new Set),[b,C]=k.useState(new Set),[T,F]=k.useState(!1),[A,D]=k.useState(!0),[P,L]=k.useState([]),[W,O]=k.useState(null),[U,M]=k.useState(""),[I,H]=k.useState(""),[z,G]=k.useState(!1),te=Rg(i||"",500),re=Rg(a||"",500),me=Rg(o||"",500),{data:J}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const ae=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():[]},enabled:!!e}),{data:ne}=Oe({queryKey:["ingredient-flags",n],queryFn:async()=>{const ae=await fetch(`/api/ingredients/${n}/flags`,{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():[]},enabled:!!e&&!!n}),{data:ye}=Oe({queryKey:["ingredient-flag-nones",n],queryFn:async()=>{const ae=await fetch(`/api/ingredients/${n}/flags/nones`,{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():{none_category_ids:[]}},enabled:!!e&&!!n}),{data:ke}=Oe({queryKey:["ingredient-flag-dismissals",n],queryFn:async()=>{const ae=await fetch(`/api/ingredients/${n}/flags/dismissals`,{headers:{Authorization:`Bearer ${e}`}});return ae.ok?ae.json():[]},enabled:!!e&&!!n}),{data:Ye}=Oe({queryKey:["allergen-suggestions",te,re,me],queryFn:async()=>{const ae=new URLSearchParams;te&&ae.set("name",te),re&&ae.set("line_item",re),me&&ae.set("text",me);const K=await fetch(`/api/food-flags/suggest?${ae}`,{headers:{Authorization:`Bearer ${e}`}});return K.ok?K.json():[]},enabled:!!e&&(te.length>=2||re.length>=2||me.length>=5)});k.useEffect(()=>{ne&&m(new Set(ne.map(ae=>ae.food_flag_id)))},[ne]),k.useEffect(()=>{ye&&v(new Set(ye.none_category_ids))},[ye]),k.useEffect(()=>{ke&&L(ke)},[ke]),k.useEffect(()=>{n||(m(new Set),v(new Set),C(new Set),D(!0),L([]),O(null),G(!1),_(new Set))},[n]),k.useEffect(()=>{if(!n&&(J!=null&&J.length)){const ae=J.filter(K=>K.required).map(K=>K.id);ae.length>0&&C(K=>{const de=new Set(K);for(const Y of ae)de.add(Y);return de})}},[n,J]),k.useEffect(()=>{if(!(u!=null&&u.length)||!(J!=null&&J.length))return;const ae=u.filter(Y=>!g.has(Y)&&!x.has(Y));if(ae.length===0)return;const K=new Set(g),de=new Set(y);for(const Y of ae){K.add(Y);const Q=J.find(X=>X.flags.some(pe=>pe.id===Y));Q&&de.delete(Q.id)}m(K),v(de),w(Y=>new Set([...Y,...ae])),t==null||t([...K],[...de]),n&&fetch(`/api/ingredients/${n}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:[...K]})}).then(()=>{p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredients"]})}).catch(()=>{})},[u,J]),k.useEffect(()=>{var Y,Q;if(!(f!=null&&f.length)||!(J!=null&&J.length))return;const ae=f.filter(X=>!y.has(X)&&!S.has(X));if(ae.length===0)return;const K=new Set(y),de=new Set(g);for(const X of ae)(((Y=J.find(Ne=>Ne.id===X))==null?void 0:Y.flags)||[]).some(Ne=>de.has(Ne.id))||K.add(X);if(v(K),_(X=>new Set([...X,...ae])),t==null||t([...de],[...K]),n){for(const X of ae)(((Q=J.find(Ne=>Ne.id===X))==null?void 0:Q.flags)||[]).some(Ne=>de.has(Ne.id))||fetch(`/api/ingredients/${n}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:X})}).catch(()=>{});p.invalidateQueries({queryKey:["ingredient-flag-nones",n]}),p.invalidateQueries({queryKey:["ingredients"]})}},[f,J]);const De=(ae,K)=>{const de=K.replace(/\s*free$/i,"").trim().toLowerCase(),Y=ae.toLowerCase();return!!(de===Y||de+"s"===Y||de===Y+"s"||Y.endsWith("s")&&de===Y.slice(0,-1))},qe=async(ae,K)=>{const de=new Set(g),Y=new Set(y);if(de.has(ae))de.delete(ae);else{const Q=J==null?void 0:J.find(pe=>pe.id===K),X=Q==null?void 0:Q.flags.find(pe=>pe.id===ae);if(Q&&X&&J){if(Q.propagation_type==="suitable_for"){for(const pe of J)if(pe.propagation_type==="contains"){for(const we of pe.flags)if(de.has(we.id)&&De(we.name,X.name)){alert(`Cannot set "${X.name}" — this ingredient contains ${we.name}. Remove the ${we.name} flag first.`);return}}}if(Q.propagation_type==="contains"){for(const pe of J)if(pe.propagation_type==="suitable_for")for(const we of pe.flags)de.has(we.id)&&De(X.name,we.name)&&de.delete(we.id)}}de.add(ae),Y.delete(K)}if(m(de),v(Y),t==null||t([...de],[...Y]),n){F(!0);try{await fetch(`/api/ingredients/${n}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:[...de]})}),p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredients"]})}catch{}F(!1)}},ue=async ae=>{var Y;const K=new Set(y),de=new Set(g);if(K.has(ae)?K.delete(ae):(K.add(ae),(((Y=J==null?void 0:J.find(X=>X.id===ae))==null?void 0:Y.flags)||[]).forEach(X=>de.delete(X.id))),v(K),m(de),t==null||t([...de],[...K]),n){F(!0);try{await fetch(`/api/ingredients/${n}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:ae})}),p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredient-flag-nones",n]}),p.invalidateQueries({queryKey:["ingredients"]})}catch{}F(!1)}},Ze=ae=>{const K=J==null?void 0:J.find(de=>de.flags.some(Y=>Y.id===ae.flag_id));K&&qe(ae.flag_id,K.id)},ee=async ae=>{if(!U.trim())return;const K={food_flag_id:ae.flag_id,flag_name:ae.flag_name,dismissed_by_name:U.trim(),reason:I.trim()||void 0,matched_keyword:ae.matched_keywords.join(", ")};if(n)try{const Y=await fetch(`/api/ingredients/${n}/flags/dismissals`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(K)});if(Y.ok){const Q=await Y.json();K.id=Q.id}}catch{}const de=[...P,K];L(de),O(null),H(""),r==null||r(de)},Z=async ae=>{const K=P.find(Y=>Y.food_flag_id===ae);if(!K)return;if(n&&K.id)try{await fetch(`/api/ingredients/${n}/flags/dismissals/${K.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}})}catch{}const de=P.filter(Y=>Y.food_flag_id!==ae);L(de),r==null||r(de)},ge=async()=>{const ae=new Set(g),K=new Set(y);for(const de of He){ae.add(de.flag_id);const Y=J==null?void 0:J.find(Q=>Q.flags.some(X=>X.id===de.flag_id));Y&&K.delete(Y.id)}if(m(ae),v(K),t==null||t([...ae],[...K]),n){F(!0);try{await fetch(`/api/ingredients/${n}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:[...ae]})}),p.invalidateQueries({queryKey:["ingredient-flags",n]}),p.invalidateQueries({queryKey:["ingredients"]})}catch{}F(!1)}};if(!(J!=null&&J.length))return null;const Te=[],Be=new Set;for(const ae of Ye||[])Be.has(ae.flag_id)||(Be.add(ae.flag_id),Te.push(ae));for(const ae of l||[])if(!Be.has(ae.flag_id)){Be.add(ae.flag_id);const K="source"in ae?ae.source:"",de=K&&{contains:"product data",dietary:"product data",keyword:"product data"}[K]||"label";Te.push({...ae,matched_keywords:ae.matched_keywords.map(Y=>`${Y} (${de})`)})}for(const ae of d||[])Be.has(ae.flag_id)||(Be.add(ae.flag_id),Te.push({...ae,matched_keywords:ae.matched_keywords.map(K=>`✨ ${K}`)}));const he=new Set(P.map(ae=>ae.food_flag_id)),He=Te.filter(ae=>!g.has(ae.flag_id)&&!he.has(ae.flag_id)),Ge=J.flatMap(ae=>ae.flags.filter(K=>g.has(K.id)).map(K=>({name:K.name,code:K.code,icon:K.icon,propagation_type:ae.propagation_type})));return s.jsxs("div",{style:{borderTop:"1px solid #eee",padding:"0.75rem 1.25rem"},children:[Ge.length>0&&s.jsx("div",{style:{display:"flex",gap:"3px",flexWrap:"wrap",marginBottom:"0.5rem"},children:Ge.map(ae=>s.jsxs("span",{style:{background:ae.propagation_type==="contains"?"#dc3545":"#28a745",color:"white",padding:"1px 5px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:600},title:ae.name,children:[ae.icon?`${ae.icon} `:"",ae.code||ae.name.substring(0,3)]},ae.name))}),He.length===0&&c&&s.jsxs("div",{style:{padding:"0.3rem 0.5rem",fontSize:"0.73rem",color:"#7c3aed"},children:["✨"," AI analysing ingredients..."]}),He.length>0&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.3rem 0.5rem",background:"#fffbeb",border:"1px solid #f59e0b",borderRadius:A?"6px 6px 0 0":"6px",cursor:"pointer"},onClick:()=>D(!A),children:[s.jsxs("span",{style:{fontSize:"0.73rem",color:"#b45309",fontWeight:600},children:["⚠"," ",He.length," allergen suggestion",He.length!==1?"s":"",c&&s.jsx("span",{style:{marginLeft:"0.4rem",fontSize:"0.68rem",color:"#7c3aed"},children:"\\u2728 AI analysing..."})]}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem",alignItems:"center"},children:[s.jsx("button",{onClick:ae=>{ae.stopPropagation(),ge()},disabled:T,style:{padding:"0.15rem 0.4rem",border:"1px solid #f59e0b",borderRadius:"4px",background:"#f59e0b",color:"white",cursor:T?"default":"pointer",fontSize:"0.68rem",fontWeight:600},children:"Apply All"}),s.jsx("span",{style:{fontSize:"0.7rem",color:"#b45309"},children:A?"▲":"▼"})]})]}),A&&s.jsx("div",{style:{padding:"0.4rem 0.5rem",background:"#fffef5",border:"1px solid #f59e0b",borderTop:"none",borderRadius:"0 0 6px 6px",display:"flex",flexDirection:"column",gap:"0.3rem"},children:He.map(ae=>s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("span",{style:{fontSize:"0.73rem",color:"#555",flex:1},children:[s.jsx("strong",{children:ae.flag_name}),ae.flag_code&&s.jsxs("span",{style:{color:"#888"},children:[" (",ae.flag_code,")"]}),s.jsxs("span",{style:{color:"#999",marginLeft:"0.3rem",fontSize:"0.68rem"},children:["matched: ",ae.matched_keywords.join(", ")]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem"},children:[s.jsx("button",{onClick:()=>{O(ae.flag_id),H("")},disabled:T,style:{padding:"0.1rem 0.35rem",border:"1px solid #dc3545",borderRadius:"4px",background:"white",cursor:T?"default":"pointer",fontSize:"0.68rem",color:"#dc3545"},children:"Dismiss"}),s.jsx("button",{onClick:()=>Ze(ae),disabled:T,style:{padding:"0.1rem 0.35rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:T?"default":"pointer",fontSize:"0.68rem",color:"#555"},children:"+ Apply"})]})]}),W===ae.flag_id&&s.jsxs("div",{style:{marginTop:"0.25rem",padding:"0.35rem 0.5rem",background:"#fff5f5",border:"1px solid #fca5a5",borderRadius:"4px",display:"flex",flexDirection:"column",gap:"0.25rem"},children:[s.jsx("div",{style:{display:"flex",gap:"0.3rem",alignItems:"center"},children:s.jsx("input",{type:"text",placeholder:"Your name (required)",value:U,onChange:K=>M(K.target.value),style:{flex:1,padding:"0.2rem 0.4rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.73rem"},autoFocus:!0})}),s.jsxs("div",{style:{display:"flex",gap:"0.3rem",alignItems:"center"},children:[s.jsx("input",{type:"text",placeholder:"Reason (optional)",value:I,onChange:K=>H(K.target.value),onKeyDown:K=>{K.key==="Enter"&&U.trim()&&ee(ae)},style:{flex:1,padding:"0.2rem 0.4rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.73rem"}}),s.jsx("button",{onClick:()=>ee(ae),disabled:!U.trim(),style:{padding:"0.15rem 0.4rem",border:"1px solid #dc3545",borderRadius:"4px",background:U.trim()?"#dc3545":"#f0f0f0",color:U.trim()?"white":"#999",cursor:U.trim()?"pointer":"default",fontSize:"0.68rem",fontWeight:600},children:"Confirm"}),s.jsx("button",{onClick:()=>O(null),style:{padding:"0.15rem 0.4rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.68rem",color:"#666"},children:"Cancel"})]})]})]},ae.flag_id))})]}),P.length>0&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsxs("div",{onClick:()=>G(!z),style:{padding:"0.2rem 0.5rem",background:"#f9fafb",border:"1px solid #e5e7eb",borderRadius:z?"6px 6px 0 0":"6px",cursor:"pointer",fontSize:"0.68rem",color:"#888"},children:[P.length," dismissed ",z?"▲":"▼"]}),z&&s.jsx("div",{style:{padding:"0.3rem 0.5rem",background:"#f9fafb",border:"1px solid #e5e7eb",borderTop:"none",borderRadius:"0 0 6px 6px",display:"flex",flexDirection:"column",gap:"0.2rem"},children:P.map(ae=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("span",{style:{fontSize:"0.7rem",color:"#999",textDecoration:"line-through"},children:[ae.flag_name||`Flag #${ae.food_flag_id}`,ae.dismissed_by_name&&s.jsxs("span",{style:{fontStyle:"italic",marginLeft:"0.3rem"},children:["by ",ae.dismissed_by_name]}),ae.reason&&s.jsxs("span",{style:{marginLeft:"0.3rem"},children:["— ",ae.reason]})]}),s.jsx("button",{onClick:()=>Z(ae.food_flag_id),style:{padding:"0.05rem 0.3rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.65rem",color:"#666"},children:"Undo"})]},ae.food_flag_id))})]}),s.jsx("div",{style:{display:"flex",gap:"0.35rem",flexWrap:"wrap",marginBottom:b.size>0?"0.5rem":0},children:J.map(ae=>{const K=ae.flags.filter(X=>g.has(X.id)).length,de=y.has(ae.id),Y=b.has(ae.id),Q=K>0||de;return s.jsxs("button",{onClick:()=>C(X=>{const pe=new Set(X);return pe.has(ae.id)?pe.delete(ae.id):pe.add(ae.id),pe}),style:{padding:"0.25rem 0.5rem",border:`1px solid ${Y?"#555":Q?"#ccc":ae.required?"#f59e0b":"#ddd"}`,borderRadius:"4px",background:Y?"#f0f0f0":"white",cursor:"pointer",fontSize:"0.75rem",fontWeight:Y?600:400,color:Q?"#333":ae.required?"#b45309":"#888"},children:[ae.name,K>0&&s.jsxs("span",{style:{marginLeft:"0.25rem",color:ae.propagation_type==="contains"?"#dc3545":"#28a745",fontWeight:600},children:["(",K,")"]}),de&&s.jsxs("span",{style:{marginLeft:"0.25rem",color:"#888"},children:["(","—",")"]}),!Q&&ae.required&&s.jsx("span",{style:{marginLeft:"0.25rem",color:"#f59e0b"},children:"?"})]},ae.id)})}),J.filter(ae=>b.has(ae.id)).map(ae=>{const K=y.has(ae.id);return s.jsxs("div",{style:{display:"flex",gap:"0.35rem",flexWrap:"wrap",padding:"0.5rem",background:"#fafafa",borderRadius:"6px",border:"1px solid #e0e0e0",alignItems:"center",opacity:T?.6:1,marginBottom:"0.35rem"},children:[s.jsxs("span",{style:{fontSize:"0.7rem",color:"#888",fontWeight:600,marginRight:"0.25rem"},children:[ae.name," (",ae.propagation_type,"):"]}),ae.flags.map(de=>{const Y=g.has(de.id),Q=ae.propagation_type==="contains"?"#dc3545":"#28a745";return s.jsxs("button",{onClick:()=>qe(de.id,ae.id),disabled:T||K,title:de.name,style:{padding:"0.2rem 0.5rem",border:`1.5px solid ${Y?Q:"#ccc"}`,borderRadius:"12px",background:Y?Q:"white",color:Y?"white":K?"#ccc":"#555",cursor:T||K?"default":"pointer",fontSize:"0.73rem",fontWeight:Y?600:400},children:[de.icon?`${de.icon} `:"",de.code||de.name]},de.id)}),s.jsx("button",{onClick:()=>ue(ae.id),disabled:T,style:{padding:"0.2rem 0.5rem",border:`1.5px dashed ${K?"#888":"#ccc"}`,borderRadius:"12px",background:K?"#888":"white",color:K?"white":"#888",cursor:T?"default":"pointer",fontSize:"0.73rem",fontWeight:K?600:400,marginLeft:"0.25rem"},title:"None of these apply",children:"None"})]},ae.id)})]})}function ife({imageFile:n,onCropped:e,onCancel:t}){const r=k.useRef(null),i=k.useRef(null),[o,a]=k.useState(!1),[l,d]=k.useState(!1),[c,u]=k.useState(null),[f,p]=k.useState(null),[g,m]=k.useState({width:0,height:0}),[y,v]=k.useState(0);k.useEffect(()=>{const D=new Image;return D.onload=()=>{i.current=D,a(!0)},D.src=URL.createObjectURL(n),()=>URL.revokeObjectURL(D.src)},[n]),k.useEffect(()=>{const D=i.current;if(!D||!o)return;const P=y===90||y===270,L=P?D.height:D.width,W=P?D.width:D.height,M=Math.min(700/L,500/W,1);m({width:L*M,height:W*M}),p(null)},[o,y]);const x=k.useCallback((D,P,L,W)=>{D.save(),D.translate(L/2,W/2),D.rotate(y*Math.PI/180);const O=y===90||y===270,U=O?W:L,M=O?L:W;D.drawImage(P,-U/2,-M/2,U,M),D.restore()},[y]),w=k.useCallback(()=>{const D=r.current,P=i.current;if(!D||!P)return;const L=D.getContext("2d");L&&(L.clearRect(0,0,D.width,D.height),x(L,P,D.width,D.height),f&&(L.fillStyle="rgba(0,0,0,0.4)",L.fillRect(0,0,D.width,D.height),L.clearRect(f.x,f.y,f.w,f.h),x(L,P,D.width,D.height),L.strokeStyle="#f59e0b",L.lineWidth=2,L.setLineDash([6,3]),L.strokeRect(f.x,f.y,f.w,f.h),L.setLineDash([]),L.fillStyle="rgba(0,0,0,0.4)",L.fillRect(0,0,D.width,f.y),L.fillRect(0,f.y+f.h,D.width,D.height-f.y-f.h),L.fillRect(0,f.y,f.x,f.h),L.fillRect(f.x+f.w,f.y,D.width-f.x-f.w,f.h)))},[f,x]);k.useEffect(()=>{o&&g.width>0&&w()},[o,w,g]);const S=D=>{const L=r.current.getBoundingClientRect(),W="touches"in D?D.touches[0].clientX:D.clientX,O="touches"in D?D.touches[0].clientY:D.clientY;return{x:W-L.left,y:O-L.top}},_=D=>{D.preventDefault();const P=S(D);u(P),p(null),d(!0)},b=D=>{if(!l||!c)return;D.preventDefault();const P=S(D);p({x:Math.min(c.x,P.x),y:Math.min(c.y,P.y),w:Math.abs(P.x-c.x),h:Math.abs(P.y-c.y)})},C=()=>{d(!1)},T=()=>{v(D=>(D+90)%360)},F=()=>{const D=i.current;if(!D||!f||f.w<10||f.h<10)return;const P=y===90||y===270,L=P?D.height:D.width,W=P?D.width:D.height,O=L/g.width,U=W/g.height,M=f.x*O,I=f.y*U,H=f.w*O,z=f.h*U,G=document.createElement("canvas");G.width=L,G.height=W;const te=G.getContext("2d");te.translate(L/2,W/2),te.rotate(y*Math.PI/180);const re=P?W:L,me=P?L:W;te.drawImage(D,-re/2,-me/2,re,me);const J=document.createElement("canvas");J.width=H,J.height=z,J.getContext("2d").drawImage(G,M,I,H,z,0,0,H,z),J.toBlob(ye=>{if(ye){const ke=new File([ye],n.name,{type:"image/jpeg"});e(ke)}},"image/jpeg",.92)},A=()=>{if(y===0){e(n);return}const D=i.current;if(!D){e(n);return}const P=y===90||y===270,L=P?D.height:D.width,W=P?D.width:D.height,O=document.createElement("canvas");O.width=L,O.height=W;const U=O.getContext("2d");U.translate(L/2,W/2),U.rotate(y*Math.PI/180);const M=P?W:L,I=P?L:W;U.drawImage(D,-M/2,-I/2,M,I),O.toBlob(H=>{H&&e(new File([H],n.name,{type:"image/jpeg"}))},"image/jpeg",.92)};return s.jsx("div",{style:Gf.overlay,children:s.jsxs("div",{style:Gf.modal,children:[s.jsxs("div",{style:Gf.header,children:[s.jsx("h3",{style:{margin:0,fontSize:"1rem"},children:"Select Ingredients Area"}),s.jsx("button",{onClick:t,style:Gf.closeBtn,children:"✕"})]}),s.jsxs("div",{style:{padding:"0.5rem",fontSize:"0.8rem",color:"#666",textAlign:"center",display:"flex",alignItems:"center",justifyContent:"center",gap:"0.75rem"},children:[s.jsx("span",{children:"Draw a rectangle around the ingredients list"}),s.jsxs("button",{onClick:T,style:Gf.rotateBtn,title:"Rotate 90°",children:["↻"," Rotate"]})]}),s.jsx("div",{style:{display:"flex",justifyContent:"center",padding:"0.5rem",background:"#f0f0f0"},children:o?s.jsx("canvas",{ref:r,width:g.width,height:g.height,style:{cursor:"crosshair",touchAction:"none",borderRadius:"4px"},onMouseDown:_,onMouseMove:b,onMouseUp:C,onMouseLeave:C,onTouchStart:_,onTouchMove:b,onTouchEnd:C}):s.jsx("div",{style:{padding:"2rem",color:"#888"},children:"Loading image..."})}),s.jsxs("div",{style:Gf.footer,children:[s.jsx("button",{onClick:A,style:Gf.skipBtn,children:"Use Full Image"}),s.jsx("button",{onClick:F,disabled:!f||f.w<10||f.h<10,style:{...Gf.cropBtn,opacity:f&&f.w>=10&&f.h>=10?1:.4,cursor:f&&f.w>=10&&f.h>=10?"pointer":"default"},children:"Crop & Scan"})]})]})})}const Gf={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1100},modal:{background:"white",borderRadius:"10px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.1rem",cursor:"pointer",color:"#888"},footer:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"0.75rem 1rem",borderTop:"1px solid #eee"},skipBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",color:"#333",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},cropBtn:{padding:"0.5rem 1rem",background:"#6366f1",color:"white",border:"none",borderRadius:"6px",fontWeight:600,fontSize:"0.85rem"},rotateBtn:{padding:"0.3rem 0.6rem",background:"white",color:"#555",border:"1px solid #ccc",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",whiteSpace:"nowrap"}},sfe={g:{g:1,kg:.001},kg:{g:1e3,kg:1},oz:{g:28.3495,kg:.0283495},ml:{ml:1,ltr:.001},cl:{ml:10,ltr:.01},ltr:{ml:1e3,ltr:1},each:{each:1}};function ofe(n,e,t,r,i){var u;if(!e||!t)return"";const o=(u=sfe[t])==null?void 0:u[r];if(!o)return t!==r?`Cannot convert ${t} → ${r}`:"";const a=n*e*o,l=i?i/a:null;let c=`${n>1?`${n} × ${e}${t} = `:""}${a.toFixed(a%1?2:0)} ${r}`;return l&&(c+=` → £${l.toFixed(4)} per ${r}`,r==="g"?c+=` (£${(l*1e3).toFixed(2)}/kg)`:r==="ml"&&(c+=` (£${(l*1e3).toFixed(2)}/ltr)`)),c}function J2(n){const e=n.match(/(\d+)\s*[x\u00d7]\s*(\d+(?:\.\d+)?)\s*(g|kg|ml|ltr|l|oz|cl|gm|gms)\b/i);if(e){let r=e[3].toLowerCase();return r==="l"&&(r="ltr"),(r==="gm"||r==="gms")&&(r="g"),{qty:parseInt(e[1]),size:e[2],type:r}}const t=n.match(/(\d+(?:\.\d+)?)\s*(g|kg|ml|ltr|l|oz|cl|gm|gms|gram|grams|kilo|kilos|kilogram|litre|litres|liter)\b/i);if(t){let r=t[2].toLowerCase();return(r==="l"||r==="litre"||r==="litres"||r==="liter")&&(r="ltr"),(r==="gm"||r==="gms"||r==="gram"||r==="grams")&&(r="g"),(r==="kilo"||r==="kilos"||r==="kilogram")&&(r="kg"),{qty:1,size:t[1],type:r}}return null}const afe=[{key:"brakes",namePattern:/brakes/i,label:"Fetch Brakes",color:"#f59e0b",endpoint:"/api/food-flags/brakes-lookup",paramName:"product_code"}];function VP(n){return n&&afe.find(e=>e.namePattern.test(n))||null}const lfe=new Set(["brakes","brake","bidfood","the","a","an","and","or","of","for","with","in","per","pack","pkt","case","cs","box","bag","tub","tin","jar","btl","bottle","x","pk","ea","each"]);function ON(n){return new Set(n.toLowerCase().replace(/[^a-z0-9%]+/g," ").split(/\s+/).filter(e=>e.length>=2&&!lfe.has(e)))}function dfe(n,e){const t=ON(n),r=ON(e);if(t.size===0||r.size===0)return 0;let i=0;for(const a of t){if(r.has(a)){i++;continue}for(const l of r)if(a.length>=4&&l.length>=4&&(a.includes(l)||l.includes(a))){i+=.5;break}}const o=Math.min(t.size,r.size);return Math.round(i/o*100)}function A0({open:n,onClose:e,onSaved:t,editingIngredient:r,prePopulateName:i,preSelectLineItem:o}){var gi;const{token:a}=gn(),l=pi(),d=je=>je==="each"?"count":["g","kg","oz"].includes(je)?"weight":["ml","ltr","cl"].includes(je)?"volume":"unknown",[c,u]=k.useState(""),[f,p]=k.useState(""),[g,m]=k.useState("g"),[y,v]=k.useState("100"),[x,w]=k.useState(""),[S,_]=k.useState(""),[b,C]=k.useState([]),[T,F]=k.useState(""),[A,D]=k.useState(""),[P,L]=k.useState(null),[W,O]=k.useState(1),[U,M]=k.useState(""),[I,H]=k.useState("g"),[z,G]=k.useState(""),[te,re]=k.useState([]),[me,J]=k.useState([]),[ne,ye]=k.useState(!1),[ke,Ye]=k.useState(!1),[De,qe]=k.useState(""),[ue,Ze]=k.useState(null),[ee,Z]=k.useState(!1),[ge,Te]=k.useState(null),[Be,he]=k.useState(!1),[He,Ge]=k.useState(!1),[ae,K]=k.useState(null),[de,Y]=k.useState(!1),[Q,X]=k.useState(""),[pe,we]=k.useState([]),[Ne,st]=k.useState([]),[Ve,Re]=k.useState(null),[Le,rt]=k.useState([]),[$e,ce]=k.useState(null),[Je,jt]=k.useState(!1),[ct,Se]=k.useState([]),ot=Rg(De,1e3),[ut,Ot]=k.useState(!1),[An,on]=k.useState(null),[Ke,Rt]=k.useState(null),[vt,Cr]=k.useState(!1),Qt=Rg(c,1200),{data:Ci}=Oe({queryKey:["ingredient-categories"],queryFn:async()=>{const je=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${a}`}});if(!je.ok)throw new Error("Failed to fetch categories");return je.json()},enabled:!!a&&n}),{data:Lr}=Oe({queryKey:["suppliers"],queryFn:async()=>{const je=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${a}`}});if(!je.ok)return[];const bt=await je.json();return bt.suppliers||bt||[]},enabled:!!a&&n}),{data:Gs}=Oe({queryKey:["ingredient-sources",r==null?void 0:r.id],queryFn:async()=>{const je=await fetch(`/api/ingredients/${r.id}/sources`,{headers:{Authorization:`Bearer ${a}`}});return je.ok?je.json():[]},enabled:!!a&&n&&!!r}),Ai=Rg(T,300),{data:Ks,isLoading:un}=Oe({queryKey:["ing-modal-li-search",Ai,A],queryFn:async()=>{const je=new URLSearchParams;Ai&&je.set("q",Ai),A&&je.set("supplier_id",A),je.set("limit","100");const bt=await fetch(`/api/search/line-items?${je}`,{headers:{Authorization:`Bearer ${a}`}});return bt.ok?bt.json():{items:[],total_count:0}},enabled:!!a&&n&&Ai.length>=2}),{data:Fr}=Oe({queryKey:["settings-llm-check"],queryFn:async()=>{const je=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${a}`}});return je.ok?je.json():{llm_enabled:!1}},enabled:!!a&&n,staleTime:6e4}),zi=(Fr==null?void 0:Fr.llm_enabled)??!1;k.useEffect(()=>{if(!zi||!ot||ot.trim().length<10){Se([]);return}let je=!1;return(async()=>{var yn;jt(!0);try{const tn=await fetch("/api/food-flags/analyse-label",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({ingredients_text:ot})});if(tn.ok&&!je){const ci=await tn.json();((yn=ci.suggestions)==null?void 0:yn.length)>0?Se(ci.suggestions.map(hn=>({flag_id:hn.flag_id,flag_name:hn.flag_name,flag_code:hn.flag_code,category_name:hn.category_name,matched_keywords:[hn.status==="may_contain"?`may contain: ${hn.reason}`:hn.reason]}))):Se([])}}catch{}je||jt(!1)})(),()=>{je=!0}},[zi,ot,a]),k.useEffect(()=>{if(!zi||r||!Qt||Qt.trim().length<3){Rt(null);return}let je=!1;return(async()=>{Cr(!0);try{const yn=await fetch(`/api/ingredients/ai-estimate-yield?name=${encodeURIComponent(Qt.trim())}`,{headers:{Authorization:`Bearer ${a}`}});if(yn.ok&&!je){const tn=await yn.json();(tn.llm_status==="success"||tn.llm_status==="cached")&&tn.yield_percent?Rt({percent:tn.yield_percent,reason:tn.reason||""}):Rt(null)}}catch{}je||Cr(!1)})(),()=>{je=!0}},[zi,r,Qt,a]);const aa=je=>P!=null&&je.product_code===P.product_code&&je.description===P.description&&je.supplier_id===P.supplier_id,Oi=k.useMemo(()=>{const je=parseFloat(U);if(!je||!I||!P)return"";const bt=P.most_recent_price!=null?Number(P.most_recent_price):null;return ofe(W,je,I,g,bt)},[W,U,I,g,P]),Vd=()=>{u(""),p(""),m("g"),v("100"),w(""),_(""),C([]),F(""),D(""),L(null),O(1),M(""),H("g"),G(""),re([]),J([]),ye(!1),Ye(!1),qe(""),Ze(null),Z(!1),Te(null),he(!1),Ge(!1),K(null),Y(!1),X(""),we([]),st([]),Re(null),rt([]),ce(null),jt(!1),Se([]),Rt(null),Cr(!1)},Gn=()=>{Vd(),e()},Dr=k.useMemo(()=>VP(P==null?void 0:P.supplier_name),[P==null?void 0:P.supplier_name]),xr=k.useMemo(()=>!Ve||Ve==="NOT FOUND"||!(P!=null&&P.description)?null:dfe(Ve,P.description),[Ve,P==null?void 0:P.description]),Ss=async(je,bt,yn=!1)=>{var tn,ci,hn;Y(!0);try{const Ti=new URLSearchParams({[bt.paramName]:je});yn&&Ti.set("force","true");const js=await fetch(`${bt.endpoint}?${Ti}`,{headers:{Authorization:`Bearer ${a}`}});if(js.ok){const Ar=await js.json();if(Ar.found){Ye(!0),Re(Ar.product_name||null);let fs=Ar.ingredients_text||"";((tn=Ar.contains_allergens)==null?void 0:tn.length)>0?fs+=` -Contains: ${Ar.contains_allergens.join(", ")}`:fs&&(fs+=` -Contains: None of the 14 Food Allergens`),((ci=Ar.suitable_for)==null?void 0:ci.length)>0&&(fs+=` -Suitable for: ${Ar.suitable_for.join(", ")}`),qe(fs),Ze({raw_text:Ar.ingredients_text||"",suggested_flags:Ar.suggested_flags||[]});const Qs=(Ar.suggested_flags||[]).filter(Lo=>Lo.source==="contains"||Lo.source==="dietary").map(Lo=>Lo.flag_id);Qs.length>0&&we(Qs),((hn=Ar.none_category_ids)==null?void 0:hn.length)>0&&st(Ar.none_category_ids)}else Re("NOT FOUND")}}catch{}Y(!1)},rs=async je=>{Z(!0),Ze(null);try{const bt=new FormData;bt.append("file",je);const yn=new FileReader;yn.onload=hn=>{var Ti;return Te((Ti=hn.target)==null?void 0:Ti.result)},yn.readAsDataURL(je);const tn=r?`/api/food-flags/scan-label/${r.id}`:"/api/food-flags/scan-label",ci=await fetch(tn,{method:"POST",headers:{Authorization:`Bearer ${a}`},body:bt});if(ci.ok){const hn=await ci.json();Ze(hn),hn.raw_text&&qe(hn.raw_text)}}catch{}Z(!1)},Xs=async je=>{if(!(!P||!a))try{const bt={supplier_id:P.supplier_id,pack_quantity:W||1,unit_size:parseFloat(U)||null,unit_size_type:I||null,apply_to_existing:!0};P.product_code?bt.product_code=P.product_code:P.description&&(bt.description_pattern=P.description.substring(0,100).toLowerCase().trim()),P.most_recent_price&&(bt.latest_unit_price=P.most_recent_price),P.most_recent_invoice_id&&(bt.invoice_id=P.most_recent_invoice_id);const yn=await fetch(`/api/ingredients/${je}/sources`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(bt)});if(!yn.ok){const tn=await yn.json().catch(()=>({}));G(tn.detail||"Saved but source mapping failed")}}catch{G("Saved but source mapping failed (network error)")}},Jt=async je=>{if(te.length>0)try{await fetch(`/api/ingredients/${je}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:te})})}catch{}for(const bt of me)try{await fetch(`/api/ingredients/${je}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:bt})})}catch{}if(Le.length>0)try{await fetch(`/api/ingredients/${je}/flags/dismissals/batch`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({dismissals:Le})})}catch{}};k.useEffect(()=>{var je,bt;if(n)if(Ot(!1),on(null),r)u(r.name),p(((je=r.category_id)==null?void 0:je.toString())||""),m(r.standard_unit),v(r.yield_percent.toString()),w(((bt=r.manual_price)==null?void 0:bt.toString())||""),_(r.notes||""),ye(r.is_free||!1),Ye(r.is_prepackaged||!1),qe(r.product_ingredients||""),Te(r.has_label_image?`/api/ingredients/${r.id}/label-image?token=${encodeURIComponent(a||"")}`:null),F(r.name);else{const yn=i||"";if(u(yn),F((o==null?void 0:o.description)||yn),o){if(L(o),o.most_recent_pack_quantity&&o.most_recent_unit_size)O(o.most_recent_pack_quantity),M(Number(o.most_recent_unit_size).toString()),H(o.most_recent_unit_size_type||"g");else{const ci=J2(o.description||"");ci?(O(ci.qty),M(ci.size),H(ci.type)):o.description&&(Ot(!0),fetch(`/api/ingredients/ai-pack-size?description=${encodeURIComponent(o.description)}`,{headers:{Authorization:`Bearer ${a}`}}).then(hn=>hn.ok?hn.json():null).then(hn=>{hn!=null&&hn.pack_quantity&&(hn!=null&&hn.unit_size)&&(O(hn.pack_quantity),M(String(hn.unit_size)),H(hn.unit_size_type||"g"),on(hn.source))}).catch(()=>{}).finally(()=>Ot(!1)))}VP(o.supplier_name)&&o.product_code&&(X(o.product_code),ce(o.product_code))}}},[n]),k.useEffect(()=>{if($e&&a&&Dr){const je=$e;ce(null),Ss(je,Dr)}},[$e,a,Dr]),k.useEffect(()=>{if(!c||c.length<3||!a||!n){C([]);return}const je=setTimeout(async()=>{try{const bt=await fetch(`/api/ingredients/check-duplicate?name=${encodeURIComponent(c)}`,{headers:{Authorization:`Bearer ${a}`}});if(bt.ok){const yn=await bt.json();C(yn.filter(tn=>r?tn.id!==r.id:!0))}}catch{}},500);return()=>clearTimeout(je)},[c,a,r==null?void 0:r.id,n]);const Ys=Ue({mutationFn:async je=>{const bt=await fetch("/api/ingredients",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(je)});if(!bt.ok){const yn=await bt.json().catch(()=>({}));throw new Error(yn.detail||"Failed to create")}return bt.json()},onSuccess:async je=>{P&&await Xs(je.id),await Jt(je.id),l.invalidateQueries({queryKey:["ingredients"]}),l.invalidateQueries({queryKey:["ingredient-sources"]}),t==null||t({id:je.id,name:je.name,standard_unit:je.standard_unit}),Gn()}}),Ft=Ue({mutationFn:async({id:je,data:bt})=>{const yn=await fetch(`/api/ingredients/${je}`,{method:"PATCH",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(bt)});if(!yn.ok)throw new Error("Failed to update");return yn.json()},onSuccess:async(je,bt)=>{P&&await Xs(bt.id),l.invalidateQueries({queryKey:["ingredients"]}),l.invalidateQueries({queryKey:["ingredient-sources"]}),t==null||t({id:bt.id,name:c,standard_unit:g}),Gn()}}),Ea=()=>{const je={name:c,category_id:f?parseInt(f):null,standard_unit:g,yield_percent:parseFloat(y),manual_price:!P&&x?parseFloat(x):null,notes:S||null,is_free:ne,is_prepackaged:ke,product_ingredients:ke&&De||null};r?Ft.mutate({id:r.id,data:je}):Ys.mutate(je)},zn=je=>{if(L(je),w(""),je.most_recent_pack_quantity&&je.most_recent_unit_size)O(je.most_recent_pack_quantity),M(Number(je.most_recent_unit_size).toString()),H(je.most_recent_unit_size_type||g);else{const yn=J2(je.description||"");yn?(O(yn.qty),M(yn.size),H(yn.type)):(O(1),M(""),H(g))}const bt=VP(je.supplier_name);bt&&je.product_code&&(X(je.product_code),Ss(je.product_code,bt))};return n?s.jsxs("div",{style:cr.overlay,children:[s.jsxs("div",{style:{...cr.modal,width:"850px"},children:[s.jsxs("div",{style:cr.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:r?"Edit Ingredient":"Create Ingredient"}),s.jsx("button",{onClick:Gn,style:cr.closeBtn,children:"✕"})]}),s.jsxs("div",{style:{...cr.modalBody,display:"flex",gap:"1.5rem"},children:[s.jsxs("div",{style:{flex:"0 0 280px"},children:[s.jsx("label",{style:cr.label,children:"Name *"}),s.jsx("input",{value:c,onChange:je=>u(je.target.value),style:cr.input,placeholder:"e.g. Butter, Minced Beef 80/20"}),b.length>0&&s.jsxs("div",{style:cr.warning,children:["Similar ingredients exist: ",b.map(je=>`${je.name} (${Math.round(je.similarity*100)}%)`).join(", ")]}),s.jsxs("div",{style:{display:"flex",marginTop:"0.6rem",borderRadius:"6px",overflow:"hidden",border:"1px solid #ddd"},children:[s.jsx("button",{type:"button",onClick:()=>Ye(!1),style:{flex:1,padding:"0.4rem 0.5rem",border:"none",background:ke?"#f5f5f5":"#1a1a2e",color:ke?"#888":"white",fontSize:"0.72rem",fontWeight:600,cursor:"pointer",letterSpacing:"0.03em"},children:"RAW INGREDIENT"}),s.jsx("button",{type:"button",onClick:()=>Ye(!0),style:{flex:1,padding:"0.4rem 0.5rem",border:"none",borderLeft:"1px solid #ddd",background:ke?"#6366f1":"#f5f5f5",color:ke?"white":"#888",fontSize:"0.72rem",fontWeight:600,cursor:"pointer",letterSpacing:"0.03em"},children:"PACKAGED PRODUCT"})]}),s.jsx("label",{style:cr.label,children:"Category"}),s.jsxs("select",{value:f,onChange:je=>p(je.target.value),style:cr.input,children:[s.jsx("option",{value:"",children:"None"}),Ci==null?void 0:Ci.map(je=>s.jsx("option",{value:je.id,children:je.name},je.id))]}),s.jsxs("div",{style:cr.row,children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("label",{style:cr.label,children:"Standard Unit"}),s.jsxs("select",{value:g,onChange:je=>{const bt=je.target.value;m(bt);const yn=d(bt),tn=d(I);yn!==tn&&(H(bt),bt==="each"&&M("1"))},style:cr.input,children:[s.jsx("option",{value:"g",children:"g (grams)"}),s.jsx("option",{value:"kg",children:"kg (kilograms)"}),s.jsx("option",{value:"ml",children:"ml (millilitres)"}),s.jsx("option",{value:"ltr",children:"ltr (litres)"}),s.jsx("option",{value:"each",children:"each"})]})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("label",{style:cr.label,children:"Yield %"}),s.jsx("input",{type:"number",value:y,onChange:je=>v(je.target.value),style:cr.input,min:"1",max:"100",step:"0.5"}),vt&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#7952b3",marginTop:"0.25rem"},children:"Estimating yield..."}),Ke&&!vt&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#7952b3",marginTop:"0.25rem"},children:["Typical yield: ~",Ke.percent,"%"," ",s.jsx("button",{type:"button",onClick:()=>v(Ke.percent.toString()),style:{background:"none",border:"none",color:"#7952b3",textDecoration:"underline",cursor:"pointer",fontSize:"0.75rem",padding:0},children:"Apply"}),Ke.reason&&s.jsxs("span",{style:{color:"#999",marginLeft:"0.25rem"},children:["(",Ke.reason,")"]})]})]})]}),!P&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{style:cr.label,children:["Manual Price (per ",g,", optional)"]}),s.jsx("input",{type:"number",value:x,onChange:je=>w(je.target.value),style:cr.input,step:"0.0001",placeholder:"Only if no line item linked"})]}),P&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.4rem 0.6rem",background:"#e8f5e9",borderRadius:"6px",fontSize:"0.8rem",color:"#2e7d32"},children:"Price from supplier source"}),s.jsx("label",{style:cr.label,children:"Notes"}),s.jsx("textarea",{value:S,onChange:je=>_(je.target.value),style:{...cr.input,minHeight:"50px"},placeholder:"Optional notes..."}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.4rem",marginTop:"0.5rem",fontSize:"0.82rem",color:"#555",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:ne,onChange:je=>ye(je.target.checked)}),"Free item (no cost — e.g. water, tap water)"]}),ke&&s.jsxs("div",{style:{marginTop:"0.5rem",padding:"0.5rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsx("label",{style:{...cr.label,marginTop:0},children:"Product Ingredients"}),s.jsx("textarea",{value:De,onChange:je=>qe(je.target.value),style:{...cr.input,minHeight:"60px",fontSize:"0.8rem"},placeholder:"Ingredients list from product label..."}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem",marginTop:"0.35rem"},children:[s.jsxs("label",{style:{padding:"0.3rem 0.6rem",border:"1px solid #6366f1",borderRadius:"4px",background:ee?"#e0e0e0":"#6366f1",color:"white",cursor:ee?"default":"pointer",fontSize:"0.75rem",fontWeight:600,display:"inline-flex",alignItems:"center",gap:"0.25rem"},children:[ee?"Scanning...":"📷 Scan Label",s.jsx("input",{type:"file",accept:"image/*",capture:"environment",style:{display:"none"},onChange:je=>{var yn;const bt=(yn=je.target.files)==null?void 0:yn[0];bt&&K(bt),je.target.value=""},disabled:ee})]}),ge&&s.jsxs("button",{onClick:()=>he(!0),style:{padding:"0.3rem 0.6rem",border:"1px solid #ccc",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem",color:"#555"},children:["🖼"," View Label"]})]}),ee&&s.jsx("div",{style:{marginTop:"0.35rem",fontSize:"0.75rem",color:"#6366f1"},children:"Analysing label image..."})]})]}),s.jsxs("div",{style:{flex:1,borderLeft:"1px solid #eee",paddingLeft:"1.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,marginBottom:"0.5rem",color:"#555"},children:"Link to Supplier Line Item"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#888",marginBottom:"0.5rem"},children:"Optional — search invoiced items to auto-map pricing"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"0.5rem"},children:[s.jsx("input",{value:T,onChange:je=>{F(je.target.value),L(null),G("")},style:{...cr.input,flex:2},placeholder:"Search line items..."}),s.jsxs("select",{value:A,onChange:je=>D(je.target.value),style:{...cr.input,flex:1,minWidth:"120px"},children:[s.jsx("option",{value:"",children:"All Suppliers"}),Lr==null?void 0:Lr.map(je=>s.jsx("option",{value:je.id,children:je.name},je.id))]})]}),r&&Gs&&Gs.length>0&&!P&&s.jsxs("div",{style:{border:"1px solid #c8e6c9",borderRadius:"6px",marginBottom:"0.5rem",background:"#f1f8e9"},children:[s.jsx("div",{style:{padding:"0.3rem 0.5rem",fontSize:"0.7rem",fontWeight:600,color:"#558b2f",borderBottom:"1px solid #c8e6c9"},children:"Linked Sources"}),Gs.map(je=>s.jsxs("div",{style:{padding:"0.3rem 0.5rem",fontSize:"0.78rem",display:"flex",justifyContent:"space-between",alignItems:"center",borderBottom:"1px solid #e8f5e9"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#666",fontSize:"0.73rem",marginRight:"0.3rem"},children:je.supplier_name}),je.product_code&&s.jsx("span",{style:{color:"#888",fontSize:"0.68rem",marginRight:"0.25rem"},children:je.product_code}),je.description_pattern||"-"]}),s.jsxs("span",{style:{fontSize:"0.73rem",color:"#666"},children:[je.latest_unit_price!=null?`£${Number(je.latest_unit_price).toFixed(2)}`:"",je.pack_quantity?` (${je.pack_quantity}x${je.unit_size||"?"}${je.unit_size_type||""})`:""]})]},je.id))]}),Ai.length>=2&&s.jsx("div",{style:{maxHeight:"180px",overflow:"auto",border:"1px solid #e0e0e0",borderRadius:"6px",marginBottom:"0.5rem"},children:un?s.jsx("div",{style:{padding:"0.75rem",color:"#888",textAlign:"center",fontSize:"0.85rem"},children:"Searching..."}):Ks!=null&&Ks.items.length?s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.78rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:cr.liTh,children:"Supplier"}),s.jsx("th",{style:cr.liTh,children:"Description"}),s.jsx("th",{style:{...cr.liTh,textAlign:"right"},children:"Unit Price"}),s.jsx("th",{style:{...cr.liTh,textAlign:"center"}})]})}),s.jsx("tbody",{children:Ks.items.map((je,bt)=>s.jsxs("tr",{style:{borderBottom:"1px solid #f0f0f0",background:aa(je)?"#e8f5e9":void 0},children:[s.jsx("td",{style:{padding:"0.3rem 0.5rem",fontSize:"0.73rem",color:"#666"},children:je.supplier_name||"-"}),s.jsxs("td",{style:{padding:"0.3rem 0.5rem"},children:[je.product_code&&s.jsx("span",{style:{color:"#888",fontSize:"0.68rem",marginRight:"0.25rem"},children:je.product_code}),je.description]}),s.jsx("td",{style:{padding:"0.3rem 0.5rem",textAlign:"right",whiteSpace:"nowrap"},children:je.most_recent_price!=null?`£${Number(je.most_recent_price).toFixed(2)}`:"-"}),s.jsx("td",{style:{padding:"0.35rem 0.5rem",textAlign:"center"},children:s.jsx("button",{onClick:()=>zn(je),style:{background:"none",border:"none",cursor:"pointer",fontSize:"1rem",padding:"0.15rem 0.3rem",borderRadius:"4px",color:aa(je)?"#2e7d32":je.ingredient_id!=null?"#22c55e":J2(je.description||"")?"#f59e0b":"#ef4444"},title:aa(je)?"Selected":je.ingredient_id!=null?`Mapped to ${je.ingredient_name}`:J2(je.description||"")?"Pack info detected":"No pack info — manual entry needed",children:"⚖"})})]},`${je.product_code||""}-${je.supplier_id}-${bt}`))})]}):s.jsx("div",{style:{padding:"0.75rem",color:"#888",textAlign:"center",fontSize:"0.85rem"},children:"No line items found"})}),P&&P.most_recent_line_number!=null&&s.jsx("div",{style:{marginTop:"0.5rem",borderRadius:"6px",overflow:"hidden",border:"1px solid #e0e0e0",cursor:"pointer"},onClick:()=>Ge(!0),title:"Click to enlarge",children:s.jsx("img",{src:`/api/invoices/${P.most_recent_invoice_id}/line-items/${P.most_recent_line_number}/preview?token=${encodeURIComponent(a||"")}`,alt:"Invoice line item",style:{width:"100%",height:"auto",display:"block"},onError:je=>{je.target.parentElement.style.display="none"}})}),P&&s.jsxs("div",{style:{background:"#f8f9fa",padding:"0.6rem",borderRadius:"6px",marginTop:"0.25rem"},children:[s.jsxs("div",{style:{fontSize:"0.8rem",fontWeight:600,marginBottom:"0.35rem"},children:["✓"," ",P.description,s.jsxs("button",{onClick:()=>{L(null),G("")},style:{background:"none",border:"none",cursor:"pointer",color:"#c62828",fontSize:"0.75rem",marginLeft:"0.5rem"},children:["✕"," remove"]})]}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#666",marginBottom:"0.35rem"},children:[P.supplier_name,P.most_recent_price!=null?` — £${Number(P.most_recent_price).toFixed(2)}`:""]}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem",alignItems:"flex-end"},children:[s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{fontSize:"0.65rem",fontWeight:600,color:"#888",marginBottom:"0.15rem"},children:["Contains",ut&&s.jsx("span",{style:{marginLeft:"3px",color:"#7952b3"},children:"..."}),An==="ai"&&s.jsx("span",{style:{marginLeft:"3px"},title:"Deduced by AI",children:"✨"})]}),s.jsx("input",{type:"number",value:U,onChange:je=>M(je.target.value),style:cr.input,step:"0.1",min:"0",placeholder:"Size"})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:600,color:"#888",marginBottom:"0.15rem"},children:"Unit"}),s.jsxs("select",{value:I,onChange:je=>{const bt=je.target.value;H(bt);const yn=d(bt),tn=d(g);yn!==tn&&(m(bt==="cl"?"ml":bt==="oz"?"g":bt),bt==="each"&&M("1"))},style:cr.input,children:[s.jsx("option",{value:"each",children:"each"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"}),s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"oz",children:"oz"}),s.jsx("option",{value:"cl",children:"cl"})]})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:600,color:"#888",marginBottom:"0.15rem"},children:"Pack of"}),s.jsx("input",{type:"number",value:W,onChange:je=>O(parseInt(je.target.value)||1),style:cr.input,min:"1",step:"1"})]})]}),Oi&&s.jsx("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:"#e8f5e9",borderRadius:"4px",fontSize:"0.8rem",color:"#2e7d32",fontWeight:500},children:Oi})]}),P&&Dr&&s.jsxs("div",{style:{marginTop:"0.5rem",padding:"0.5rem",background:"#fefce8",borderRadius:"6px",border:`1px solid ${Dr.color}33`},children:[s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"stretch"},children:[P.most_recent_line_number!=null&&s.jsx("div",{style:{flex:"0 0 auto",maxWidth:"120px",borderRadius:"4px",overflow:"hidden",border:"1px solid #e0e0e0"},children:s.jsx("img",{src:`/api/invoices/${P.most_recent_invoice_id}/line-items/${P.most_recent_line_number}/preview/field/product_code?token=${encodeURIComponent(a||"")}`,alt:"Product code from invoice",style:{width:"100%",height:"auto",display:"block"},onError:je=>{je.target.parentElement.style.display="none"}})}),s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},children:[de&&s.jsx("div",{style:{fontSize:"0.72rem",color:Dr.color},children:"Fetching product data..."}),s.jsxs("div",{style:{display:"flex",gap:"0.3rem",alignItems:"center"},children:[s.jsx("input",{value:Q,onChange:je=>X(je.target.value),style:{...cr.input,flex:1,fontSize:"0.75rem",padding:"0.25rem 0.4rem"},placeholder:"Product code",onKeyDown:je=>{je.key==="Enter"&&Q.trim()&&Ss(Q.trim(),Dr,!0)}}),s.jsx("button",{onClick:()=>{Q.trim()&&Ss(Q.trim(),Dr,!0)},disabled:!Q.trim()||de,style:{padding:"0.25rem 0.5rem",border:`1px solid ${Dr.color}`,borderRadius:"4px",background:de?"#e0e0e0":Dr.color,color:"white",cursor:de?"default":"pointer",fontSize:"0.7rem",fontWeight:600,whiteSpace:"nowrap"},children:Dr.label})]})]})]}),Ve==="NOT FOUND"&&s.jsx("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:"#fdecea",border:"1px solid #ef9a9a",borderRadius:"4px",fontSize:"0.72rem",color:"#c62828"},children:"Product not found on Brakes website — SKU may be incorrect"}),Ve&&Ve!=="NOT FOUND"&&s.jsxs("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:xr!==null&&xr<30?"#fdecea":xr!==null&&xr<60?"#fffbeb":"#e8f5e9",border:`1px solid ${xr!==null&&xr<30?"#ef9a9a":xr!==null&&xr<60?"#f59e0b55":"#a5d6a7"}`,borderRadius:"4px",fontSize:"0.72rem",color:xr!==null&&xr<30?"#c62828":xr!==null&&xr<60?"#b45309":"#2e7d32"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem",marginBottom:pe.length>0||Ne.length>0?"0.2rem":0},children:[s.jsxs("span",{style:{flex:1},children:[s.jsx("span",{style:{fontWeight:600},children:"Matched: "}),Ve]}),xr!==null&&s.jsxs("span",{style:{fontWeight:700,fontSize:"0.68rem",padding:"0.1rem 0.35rem",borderRadius:"3px",background:xr<30?"#c6282822":xr<60?"#b4530922":"#2e7d3222",whiteSpace:"nowrap"},children:[xr,"% match"]})]}),xr!==null&&xr<30&&s.jsx("div",{style:{fontSize:"0.68rem",fontStyle:"italic",marginBottom:"0.15rem"},children:"Product name doesn't match line item — verify SKU is correct"}),pe.length>0&&(ue==null?void 0:ue.suggested_flags)&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontWeight:600},children:"Auto-flagged: "}),ue.suggested_flags.filter(je=>pe.includes(je.flag_id)).map(je=>je.flag_name).join(", ")]}),Ne.length>0&&s.jsxs("span",{children:[pe.length>0?" | ":"",s.jsx("span",{style:{fontWeight:600},children:"None of 14 allergens: "}),"allergen categories set to None"]})]})]}),z&&s.jsx("div",{style:{marginTop:"0.35rem",padding:"0.35rem 0.5rem",background:"#fdecea",borderRadius:"4px",fontSize:"0.8rem",color:"#c62828"},children:z})]})]}),s.jsx(rfe,{ingredientId:(r==null?void 0:r.id)??null,token:a||"",onChange:(je,bt)=>{re(je),J(bt)},onDismissalsChange:je=>rt(je),ingredientName:c,productIngredients:ke?De:void 0,lineItemDescription:(P==null?void 0:P.description)||void 0,scanSuggestions:ue==null?void 0:ue.suggested_flags,llmSuggestions:zi?ct:void 0,llmAnalysing:zi?Je:!1,autoApplyFlagIds:pe,autoApplyNoneCategoryIds:Ne}),s.jsxs("div",{style:cr.modalFooter,children:[s.jsx("button",{onClick:Gn,style:cr.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:Ea,disabled:!c||Ys.isPending||Ft.isPending,style:cr.primaryBtn,children:Ys.isPending||Ft.isPending?"Saving...":P?r?"Save & Map":"Create & Map":"Save"})]}),(Ys.error||Ft.error)&&s.jsx("div",{style:{padding:"0 1.25rem 0.75rem"},children:s.jsx("div",{style:cr.errorMsg,children:(gi=Ys.error||Ft.error)==null?void 0:gi.message})})]}),ae&&s.jsx(ife,{imageFile:ae,onCropped:je=>{K(null),rs(je)},onCancel:()=>K(null)}),Be&&ge&&s.jsx("div",{onClick:()=>he(!1),style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1200,cursor:"pointer"},children:s.jsxs("div",{onClick:je=>je.stopPropagation(),style:{position:"relative",maxWidth:"90vw",maxHeight:"90vh"},children:[s.jsx("button",{onClick:()=>he(!1),style:{position:"absolute",top:"-12px",right:"-12px",width:"28px",height:"28px",borderRadius:"50%",background:"white",border:"1px solid #ccc",cursor:"pointer",fontSize:"0.9rem",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",zIndex:1},children:"✕"}),s.jsx("img",{src:ge,alt:"Product label",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"}})]})}),He&&(P==null?void 0:P.most_recent_line_number)!=null&&s.jsx("div",{onClick:()=>Ge(!1),style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.7)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1200,cursor:"pointer"},children:s.jsxs("div",{onClick:je=>je.stopPropagation(),style:{position:"relative",maxWidth:"95vw",maxHeight:"90vh"},children:[s.jsx("button",{onClick:()=>Ge(!1),style:{position:"absolute",top:"-12px",right:"-12px",width:"28px",height:"28px",borderRadius:"50%",background:"white",border:"1px solid #ccc",cursor:"pointer",fontSize:"0.9rem",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 2px 6px rgba(0,0,0,0.2)",zIndex:1},children:"✕"}),s.jsx("img",{src:`/api/invoices/${P.most_recent_invoice_id}/line-items/${P.most_recent_line_number}/preview?token=${encodeURIComponent(a||"")}`,alt:"Invoice line item",style:{maxWidth:"95vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"}})]})})]}):null}const cr={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"500px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},row:{display:"flex",gap:"0.75rem"},warning:{background:"#fff3cd",color:"#856404",padding:"0.5rem 0.75rem",borderRadius:"6px",fontSize:"0.8rem",marginTop:"0.35rem"},errorMsg:{padding:"0.75rem 1.25rem",color:"#dc3545",fontSize:"0.85rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},liTh:{padding:"0.35rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.7rem",fontWeight:600,color:"#555",position:"sticky",top:0}};Bu.workerSrc="/pdf.worker.min.mjs";const cfe=({style:n})=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",style:{width:"18px",height:"18px",...n},children:s.jsx("path",{d:"M12 3c-1.27 0-2.4.8-2.82 2H3v2h1.95L2 14c-.47 2 1 4 4 4s4.5-2 4-4L7.05 7H9.18c.35.99 1.17 1.74 2.18 1.94V19H7v2h10v-2h-4.18V8.94c1.01-.2 1.83-.95 2.18-1.94h2.13L14 14c-.47 2 1 4 4 4s4.5-2 4-4l-2.95-7H21V5h-6.18C14.4 3.8 13.27 3 12 3zm0 2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM6 10.45L7.5 14h-3L6 10.45zm12 0L19.5 14h-3L18 10.45z"})}),LN={upload:{label:"Upload",color:"#6c757d",icon:"📤"},email:{label:"Email",color:"#3498db",icon:"📧"},api:{label:"API",color:"#9b59b6",icon:"🔌"}},ufe=({source:n,sourceReference:e})=>{const{label:t,color:r,icon:i}=LN[n]||LN.upload;return s.jsxs("span",{style:{background:r,color:"white",padding:"0.4rem 0.6rem",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",display:"inline-flex",alignItems:"center",gap:"0.25rem"},title:e||void 0,children:[i," ",t]})},hfe=n=>n.ingredient_id?"#28a745":n.pack_quantity?n.portions_per_unit===null?"#ffc107":n.cost_per_portion!==null?"#28a745":"#ffc107":"#dc3545",EK=.02,ffe=n=>n?n.split(` -`)[0].trim():"";function bx(n,e){if(!n)return"red";if(e==="CONFIRMED")return"none";const t=new Date(n),r=new Date;if(r.setHours(0,0,0,0),t.setHours(0,0,0,0),t>r)return"future";const i=r.getTime()-t.getTime(),o=Math.floor(i/(1e3*60*60*24));if(o>7){const a=t.getMonth()===r.getMonth(),l=t.getFullYear()===r.getFullYear();return!a||!l?o<=45?"amber":"red":"amber"}return"none"}const pfe={none:{},amber:{backgroundColor:"#fff3cd",borderColor:"#ffc107"},red:{backgroundColor:"#f8d7da",borderColor:"#dc3545"},future:{backgroundColor:"#ffe0cc",borderColor:"#e85d04",outline:"2px solid #e85d04"}};function NN(n){const e=n.split("-");if(e.length!==3)return null;const[t,r,i]=e,o=parseInt(i,10),a=parseInt(r,10);if(o<1||o>12||a<1||a>31)return null;const l=`${t}-${String(o).padStart(2,"0")}-${String(a).padStart(2,"0")}`,d=new Date(l);return isNaN(d.getTime())?null:l}function WN(n){const e=n.split("-");if(e.length!==3)return null;const[t,r,i]=e,o=new Date;o.setHours(0,0,0,0);const a=o.getFullYear();if(parseInt(t,10)<=a||Math.floor((new Date(n).getTime()-o.getTime())/(1e3*60*60*24))<=60)return null;for(const d of[a,a-1]){const c=`${d}-${r}-${i}`,u=new Date(c);if(!isNaN(u.getTime())&&u<=o)return{date:c,year:d}}return null}function gfe({lineItems:n,invoiceTotal:e,netTotal:t}){if(n.length===0)return s.jsxs("div",{style:{marginTop:"1rem",padding:"1rem",background:"#fef2f2",borderRadius:"6px",border:"1px solid #fca5a5"},children:[s.jsx("div",{style:{color:"#dc2626",fontWeight:"600",marginBottom:"0.5rem"},children:"⚠️ No Line Items"}),s.jsx("div",{style:{color:"#991b1b",fontSize:"0.9rem"},children:'This invoice has no line items. It will NOT be included in GP calculations. Use the "Edit Line Items" button above to manually add line items.'}),s.jsxs("div",{style:{marginTop:"0.5rem",color:"#991b1b",fontSize:"0.9rem"},children:[s.jsx("strong",{children:"Invoice Total:"})," £",e.toFixed(2)]})]});const r=n.reduce((f,p)=>f+(p.amount||0),0),i=n.filter(f=>!f.is_non_stock).reduce((f,p)=>f+(p.amount||0),0),o=n.filter(f=>f.is_non_stock).reduce((f,p)=>f+(p.amount||0),0),l=Math.abs((t??e)-r),d=l<=EK,c=d,u=o>0;return s.jsxs("div",{style:{marginTop:"1rem",padding:"0.75rem",background:c?"#d4edda":"#fff3cd",borderRadius:"6px",border:`1px solid ${c?"#c3e6cb":"#ffeeba"}`},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{style:{fontWeight:"500"},children:["Line Items Total: ",s.jsxs("strong",{children:["£",r.toFixed(2)]})]}),s.jsxs("span",{style:{fontWeight:"500"},children:["Invoice Net: ",s.jsxs("strong",{children:["£",(t??e).toFixed(2)]}),t&&s.jsxs("span",{style:{fontSize:"0.85rem",color:"#666"},children:[" (Gross: £",e.toFixed(2),")"]})]})]}),u&&s.jsxs("div",{style:{marginTop:"0.5rem",padding:"0.5rem",background:"rgba(255,255,255,0.5)",borderRadius:"4px"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"0.9rem"},children:[s.jsxs("span",{children:[s.jsx("strong",{children:"Stock Items:"})," £",i.toFixed(2)]}),s.jsxs("span",{style:{color:"#856404"},children:[s.jsx("strong",{children:"Non-Stock:"})," £",o.toFixed(2)]})]}),s.jsx("div",{style:{marginTop:"0.25rem",fontSize:"0.8rem",color:"#155724"},children:"GP will be calculated using stock items only"})]}),d?s.jsx("div",{style:{marginTop:"0.5rem",fontSize:"0.85rem",color:"#155724"},children:"✓ Totals match"}):s.jsxs("div",{style:{marginTop:"0.5rem",fontSize:"0.85rem",color:c?"#155724":"#856404"},children:[c?"✓ ":"⚠ ","Difference: £",l.toFixed(2)]})]})}function mfe(){var Z1,J1,ew,nx,EC,tw;const{id:n}=G_(),{token:e,user:t}=gn(),r=go(),i=pi(),[o,a]=k.useState(""),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState(""),[g,m]=k.useState("food"),[y,v]=k.useState(""),[x,w]=k.useState("invoice"),[S,_]=k.useState(""),[b,C]=k.useState(!1),[T,F]=k.useState(!1),[A,D]=k.useState(!1),[P,L]=k.useState(!1),[W,O]=k.useState(null),[U,M]=k.useState(!1),[I,H]=k.useState(null),[z,G]=k.useState(!1),[te,re]=k.useState(!1),[me,J]=k.useState(!1),[ne,ye]=k.useState(null),[ke,Ye]=k.useState(""),[De,qe]=k.useState(null),[ue,Ze]=k.useState(!1),[ee,Z]=k.useState(""),[ge,Te]=k.useState(null),[Be,he]=k.useState({}),[He,Ge]=k.useState(!1),[ae,K]=k.useState(null),[de,Y]=k.useState(null),[Q,X]=k.useState({}),[pe,we]=k.useState(null),[Ne,st]=k.useState(""),[Ve,Re]=k.useState(!1),[Le,rt]=k.useState(null),[$e,ce]=k.useState(!1),[Je,jt]=k.useState([]),[ct,Se]=k.useState(1),[ot,ut]=k.useState(0),[Ot,An]=k.useState(1),on=k.useRef(null),Ke=k.useRef(null),Rt=k.useRef(null),vt=k.useRef(null),[Cr,Qt]=k.useState(""),[Ci,Lr]=k.useState(!1),[Gs,Ai]=k.useState(!1),[Ks,un]=k.useState(!1),[Fr,zi]=k.useState([]),[aa,Oi]=k.useState(!1),[Vd,Gn]=k.useState(!1),[Dr,xr]=k.useState([]),[Ss,rs]=k.useState(!1),[Xs,Jt]=k.useState([]),[Ys,Ft]=k.useState([]),[Ea,zn]=k.useState(!1),[gi,je]=k.useState(""),[bt,yn]=k.useState("asc"),[tn,ci]=k.useState(""),[hn,Ti]=k.useState(""),[js,Ar]=k.useState(""),[fs,Qs]=k.useState(""),[Lo,xn]=k.useState(1),Pa=k.useRef(null),[nn,Zl]=k.useState(null),[qu,$s]=k.useState(""),[Gd,mo]=k.useState([]),[Bc,Kd]=k.useState(!1),[Zs,Ra]=k.useState(null),[Xd,No]=k.useState(""),[Js,Ba]=k.useState(""),[Ic,al]=k.useState(!1),[ie,nt]=k.useState(!1),[$,ze]=k.useState(""),[Qe,pt]=k.useState({}),[kt,Ht]=k.useState(null),[Gt,Er]=k.useState(!1),[ar,Kn]=k.useState([]),[is,On]=k.useState(!1),[sn,ps]=k.useState(null),[It,Tn]=k.useState([]),[Dt,Ln]=k.useState(null),[Fi,Zr]=k.useState(new Set),[ll,Wo]=k.useState(!1),[Mc,H0]=k.useState(null),[Ia,q0]=k.useState(null),[A1,V0]=k.useState(null),{data:_e,isLoading:T1,refetch:G0}=Oe({queryKey:["invoice",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch invoice");return B.json()},staleTime:3e4,refetchOnWindowFocus:!1}),Mf=_e?`/api/invoices/${n}/file?token=${encodeURIComponent(e||"")}#toolbar=0&navpanes=0&view=FitH`:null,{data:Yt,refetch:zc}=Oe({queryKey:["invoice-line-items",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/line-items`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch line items");return B.json()}}),{data:Vu}=Oe({queryKey:["invoice-stock-history",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/stock-history`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch stock history");return B.json()},enabled:!!n}),{data:Li}=Oe({queryKey:["invoice-duplicates",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/duplicates`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch duplicates");return B.json()},enabled:!!(_e!=null&&_e.duplicate_status)}),{data:ks}=Oe({queryKey:["invoice-ocr-data",n],queryFn:async()=>{const B=await fetch(`/api/invoices/${n}/ocr-data`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch OCR data");return B.json()}}),{data:ui}=Oe({queryKey:["settings"],queryFn:async()=>{const B=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to fetch settings");return B.json()},staleTime:6e4});k.useEffect(()=>{if(!Yt||!S||!e)return;const B=Yt.filter(Ae=>!Ae.ingredient_id&&!Ae.product_code&&Ae.description);if(B.length===0){pt({});return}const oe=B.map(Ae=>({description:Ae.description.split(` -`)[0].trim(),price:Ae.unit_price??void 0})),be=Array.from(new Map(oe.map(Ae=>[Ae.description.toLowerCase(),Ae])).values());be.length!==0&&fetch("/api/ingredients/sources/alias-suggestions",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({supplier_id:parseInt(S),items:be})}).then(Ae=>Ae.ok?Ae.json():[]).then(Ae=>{const it={};for(const en of Ae)it[en.description.toLowerCase()]=en;pt(it)}).catch(()=>pt({}))},[Yt,S,e]);const la=B=>{var er,lr,Kt,Fn,Jr,ei,Ui;if(!((ei=(Jr=(Fn=(Kt=(lr=(er=ks==null?void 0:ks.raw_json)==null?void 0:er.documents)==null?void 0:lr[0])==null?void 0:Kt.fields)==null?void 0:Fn[B])==null?void 0:Jr.bounding_regions)!=null&&ei[0]))return null;const oe=ks.raw_json.documents[0].fields[B].bounding_regions[0],be=oe.polygon,Ae=oe.page_number||1;if(!be||be.length<4)return null;const it=(Ui=ks.raw_json.pages)==null?void 0:Ui[Ae-1],en=(it==null?void 0:it.width)||8.5,rn=(it==null?void 0:it.height)||11,Nn=be.map(Uo=>Uo[0]),Qn=be.map(Uo=>Uo[1]),gr=Math.min(...Nn),br=Math.max(...Nn),mr=Math.min(...Qn),Wi=Math.max(...Qn);return{x:gr/en*100,y:mr/rn*100,width:(br-gr)/en*100,height:(Wi-mr)/rn*100,pageNumber:Ae}},F1=B=>{var er,lr,Kt,Fn,Jr,ei,Ui,Uo,da;if(!((Uo=(Ui=(ei=(Jr=(Fn=(Kt=(lr=(er=ks==null?void 0:ks.raw_json)==null?void 0:er.documents)==null?void 0:lr[0])==null?void 0:Kt.fields)==null?void 0:Fn.Items)==null?void 0:Jr.value)==null?void 0:ei[B])==null?void 0:Ui.bounding_regions)!=null&&Uo[0]))return null;const oe=ks.raw_json.documents[0].fields.Items.value[B].bounding_regions[0],be=oe.polygon,Ae=oe.page_number||1;if(!be||be.length<4)return null;const it=(da=ks.raw_json.pages)==null?void 0:da[Ae-1],en=(it==null?void 0:it.width)||8.5,rn=(it==null?void 0:it.height)||11,Nn=be.map(zf=>zf[0]),Qn=be.map(zf=>zf[1]),gr=Math.min(...Nn),br=Math.max(...Nn),mr=Math.min(...Qn),Wi=Math.max(...Qn);return{x:gr/en*100,y:mr/rn*100,width:(br-gr)/en*100,height:(Wi-mr)/rn*100,pageNumber:Ae}},D1=(B,oe)=>{var ei;if(!((ei=_e==null?void 0:_e.image_path)!=null&&ei.toLowerCase().endsWith(".pdf"))||Je.length===0)return null;const be=Je[B.pageNumber-1];if(!be)return null;const{padX:Ae=60,padY:it=20,strokeColor:en="#007bff"}=oe||{},rn=B.x/100*be.width,Nn=B.y/100*be.height,Qn=B.width/100*be.width,gr=B.height/100*be.height,br=Math.max(0,rn-Ae),mr=Math.max(0,Nn-it),Wi=Math.min(be.width,rn+Qn+Ae),er=Math.min(be.height,Nn+gr+it),lr=Wi-br,Kt=er-mr,Fn=document.createElement("canvas");Fn.width=lr,Fn.height=Kt;const Jr=Fn.getContext("2d");return Jr?(Jr.drawImage(be.canvas,br,mr,lr,Kt,0,0,lr,Kt),Jr.strokeStyle=en,Jr.lineWidth=3,Jr.strokeRect(rn-br-4,Nn-mr-4,Qn+8,gr+8),Fn.toDataURL()):null},E1=B=>{if(!B||!on.current||Je.length===0)return 2;const oe=Je[B.pageNumber-1];if(!oe)return 2;const be=on.current.clientWidth-32,Ae=on.current.clientHeight-32,it=B.width/100*oe.displayWidth,en=B.height/100*oe.displayHeight,rn=.8,Nn=be*rn/it,Qn=Ae*rn/en,gr=Math.min(Nn,Qn);return Math.max(2,Math.min(gr,8))},P1=(B,oe)=>{!B||!on.current||Je.length===0||!Je[B.pageNumber-1]||(Se(oe),ut(B.pageNumber),setTimeout(()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!on.current)return;const Ae=on.current;Ae.offsetHeight;const it=Ae.querySelectorAll("[data-page-container]"),en=it[B.pageNumber-1];if(!en){console.warn("Could not find page element for scrolling",{totalPages:Je.length,targetPage:B.pageNumber,foundElements:it.length});return}const rn=Ae.getBoundingClientRect(),Nn=en.getBoundingClientRect(),Qn=Nn.width,gr=Nn.height,br=(B.x+B.width/2)/100*Qn,mr=(B.y+B.height/2)/100*gr,Wi=Nn.left-rn.left+Ae.scrollLeft,er=Nn.top-rn.top+Ae.scrollTop,lr=Wi+br,Kt=er+mr,Fn=Ae.clientWidth,Jr=Ae.clientHeight,ei=Math.max(0,lr-Fn/2),Ui=Math.max(0,Kt-Jr/2);Ae.scrollTo({left:ei,top:Ui,behavior:"auto"})})})},100))},Oc=()=>{Se(1),ut(0),on.current&&on.current.scrollTo({left:0,top:0,behavior:"smooth"})},Lc=B=>{if(ae===B)K(null),Oc();else{K(B),Y(null);const oe=la(B),be=E1(oe);P1(oe,be)}},fC=(B,oe)=>{de===B?Y(null):(Y(B),K(null),Oc())},{data:Yd}=Oe({queryKey:["suppliers"],queryFn:async()=>{const B=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${e}`}});return B.ok?B.json():[]}}),{data:Ni,refetch:K0}=Oe({queryKey:["po-match",n],queryFn:async()=>{const B=await fetch(`/api/purchase-orders/matching/for-invoice?invoice_id=${n}`,{headers:{Authorization:`Bearer ${e}`}});return B.ok?B.json():{matches:[],linked_po:null}},enabled:!!(_e!=null&&_e.supplier_id)});k.useEffect(()=>{var B,oe,be;_e&&(a(_e.invoice_number||""),d(_e.invoice_date||""),u(((B=_e.total)==null?void 0:B.toString())||""),p(((oe=_e.net_total)==null?void 0:oe.toString())||""),m(_e.category||"food"),v(_e.order_number||""),w(_e.document_type||"invoice"),_(((be=_e.supplier_id)==null?void 0:be.toString())||""),Qt(_e.notes||""))},[_e]),k.useEffect(()=>{if(!_e||_e.status!=="PENDING")return;const B=setInterval(async()=>{try{const oe=await fetch(`/api/invoices/${n}`,{headers:{Authorization:`Bearer ${e}`}});oe.ok&&(await oe.json()).status!=="PENDING"&&(clearInterval(B),window.location.reload())}catch{}},2e3);return()=>clearInterval(B)},[_e==null?void 0:_e.status,n,e]),k.useEffect(()=>{(async()=>{var be;if(!(!_e||!e||!((be=_e.image_path)!=null&&be.toLowerCase().endsWith(".pdf"))||!Ke.current))try{const Ae=`/api/invoices/${n}/file?token=${encodeURIComponent(e)}`,en=await(await fetch(Ae)).arrayBuffer(),rn=await kG({data:en}).promise,Nn=rn.numPages,Qn=Ke.current.clientWidth-112,gr=1500,br=[];for(let mr=1;mr<=Nn;mr++){const Wi=await rn.getPage(mr),er=Wi.getViewport({scale:1}),lr=Qn/er.width,Kt=er.width*lr,Fn=er.height*lr,Jr=gr/er.width,ei=Wi.getViewport({scale:Jr}),Ui=document.createElement("canvas");Ui.width=ei.width,Ui.height=ei.height;const Uo=Ui.getContext("2d");if(Uo){const da=(ui==null?void 0:ui.pdf_preview_show_annotations)===!1?Ru.DISABLE:Ru.ENABLE;await Wi.render({canvasContext:Uo,viewport:ei,canvas:Ui,annotationMode:da}).promise}br.push({width:ei.width,height:ei.height,displayWidth:Kt,displayHeight:Fn,canvas:Ui})}jt(br)}catch(Ae){console.error("Error rendering PDF:",Ae)}})()},[_e,e,n,ui==null?void 0:ui.pdf_preview_show_annotations]);const Gu=Ue({mutationFn:async B=>{var be,Ae;const oe=await fetch(`/api/invoices/${n}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(B)});if(!oe.ok){const it=await oe.json().catch(()=>({})),en=((be=it.detail)==null?void 0:be.message)||it.detail||"Failed to update",rn=new Error(en);throw rn.code=(Ae=it.detail)==null?void 0:Ae.error,rn}return oe.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["invoice",n]}),i.invalidateQueries({queryKey:["invoices"]}),i.invalidateQueries({queryKey:["invoice-line-items",n]})}}),pC=Ue({mutationFn:async()=>{const B=await fetch(`/api/invoices/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to delete");return B.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["invoices"]}),r("/invoices")}}),Jl=Ue({mutationFn:async({itemId:B,data:oe})=>{const be=await fetch(`/api/invoices/${n}/line-items/${B}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(oe)});if(!be.ok)throw new Error("Failed to update");return be.json()},onSuccess:()=>{zc(),i.invalidateQueries({queryKey:["invoice",n]}),Te(null),he({}),Y(null)}}),gC=Ue({mutationFn:async B=>{const oe=await fetch(`/api/invoices/${n}/line-items`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(B)});if(!oe.ok)throw new Error("Failed to create line item");return oe.json()},onSuccess:()=>{zc(),i.invalidateQueries({queryKey:["invoice",n]}),Te(null),he({})}}),mC=Ue({mutationFn:async B=>{const oe=await fetch(`/api/invoices/${n}/line-items/${B}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}});if(!oe.ok)throw new Error("Failed to delete line item");return oe.json()},onSuccess:()=>{zc(),i.invalidateQueries({queryKey:["invoice",n]}),Te(null)}}),yC=Ue({mutationFn:async({itemId:B,portionDesc:oe})=>{const be=await fetch(`/api/invoices/${n}/line-items/${B}/save-definition`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({portion_description:oe||null})});if(!be.ok){const Ae=await be.json();throw new Error(Ae.detail||"Failed to save definition")}return be.json()}}),X0=Ue({mutationFn:async B=>{const oe=await fetch("/api/suppliers/",{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({name:B})});if(!oe.ok)throw new Error("Failed to create supplier");return oe.json()},onSuccess:B=>{i.invalidateQueries({queryKey:["suppliers"]}),_(B.id.toString()),D(!1),Z("")}}),Y0=Ue({mutationFn:async({supplierId:B,alias:oe,invoiceId:be})=>{const Ae=await fetch(`/api/suppliers/${B}/aliases`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({alias:oe,invoice_id:be})});if(!Ae.ok)throw new Error("Failed to add alias");return Ae.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["suppliers"]}),i.invalidateQueries({queryKey:["invoice",n]})}}),xC=Ue({mutationFn:async({sourceId:B,alias:oe})=>{const be=await fetch(`/api/ingredients/sources/${B}/aliases`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({alias:oe})});if(!be.ok)throw new Error("Failed to add alias");return be.json()},onSuccess:(B,oe)=>{pt(be=>{const Ae={...be};return delete Ae[oe.alias.toLowerCase()],Ae}),Ht(null),i.invalidateQueries({queryKey:["invoice-line-items",n]})}}),bC=async B=>{try{if(!(await fetch(`/api/purchase-orders/${B}/link`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({invoice_id:parseInt(n)})})).ok)throw new Error("Failed to link PO");K0()}catch{}},R1=async B=>{try{if(!(await fetch(`/api/purchase-orders/${B}/unlink`,{method:"POST",headers:{Authorization:`Bearer ${e}`}})).ok)throw new Error("Failed to unlink PO");K0()}catch{}},B1=()=>{ee.trim()&&X0.mutate(ee.trim())},I1=()=>{Z((_e==null?void 0:_e.vendor_name)||""),D(!0)},vC=async(B="REVIEWED")=>{await Gu.mutateAsync({invoice_number:o||null,invoice_date:l||null,total:c?parseFloat(c):null,net_total:f?parseFloat(f):null,supplier_id:S?parseInt(S):null,category:g,order_number:y||null,document_type:x,status:B})};k.useEffect(()=>{if(!_e)return;const B=setTimeout(()=>{var be,Ae,it;(o!==(_e.invoice_number||"")||l!==(_e.invoice_date||"")||c!==(((be=_e.total)==null?void 0:be.toString())||"")||f!==(((Ae=_e.net_total)==null?void 0:Ae.toString())||"")||S!==(((it=_e.supplier_id)==null?void 0:it.toString())||"")||g!==(_e.category||"food")||y!==(_e.order_number||"")||x!==(_e.document_type||"invoice"))&&Gu.mutate({invoice_number:o||null,invoice_date:l||null,total:c?parseFloat(c):null,net_total:f?parseFloat(f):null,supplier_id:S?parseInt(S):null,category:g,order_number:y||null,document_type:x})},1e3);return()=>clearTimeout(B)},[o,l,c,f,S,g,y,x]);const M1=async()=>{if(_e!=null&&_e.has_open_disputes&&!window.confirm(`This invoice has ${_e.dispute_count} open dispute(s). - -You can still confirm — the invoice will appear in reports while the dispute is tracked separately. - -Continue?`))return;if(l&&bx(l,"PENDING")==="future"){const oe=new Date(l).toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"});if(!window.confirm(`⚠ Invoice date is in the future: ${oe} - -This is almost certainly a day/month format error (e.g. 6 April entered as 4 June). - -Please double-check the date on the document before confirming. - -Confirm anyway?`))return}const B=(Yt||[]).filter(oe=>{const be=Vu==null?void 0:Vu[oe.id.toString()];return(be==null?void 0:be.has_history)&&be.previously_non_stock&&!oe.is_non_stock});if(B.length>0){xr(B.map(oe=>({description:oe.description,amount:oe.amount}))),Gn(!0);return}if(!l){alert(`Cannot confirm invoice without a date. - -Please set the invoice date before confirming. - -Invoices without dates cannot be found in date-filtered views.`);return}await z1()},z1=async()=>{try{await vC("CONFIRMED"),r("/invoices")}catch(B){const oe=B instanceof Error?B.message:"Failed to confirm invoice";alert(oe)}},wC=()=>{pC.mutate()},SC=async()=>{if(window.confirm(`Mark this invoice as sent to Dext without actually sending? - -This will also trigger Nextcloud archival if configured.`)){M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/mark-dext-sent`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const be=await B.json();throw new Error(be.detail||"Failed to mark as sent")}const oe=await B.json();H({type:"success",message:oe.message+(oe.archival_status?` - -${oe.archival_status}`:"")}),i.invalidateQueries({queryKey:["invoice",n]})}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}}},jC=async()=>{if(window.confirm(`Reprocess existing OCR data? - -This will: -- Re-identify supplier -- Re-detect document type -- Re-create line items with product definitions -- Re-run duplicate detection - -Existing line items will be replaced.`)){M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/reprocess`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const be=await B.json();throw new Error(be.detail||"Failed to reprocess")}const oe=await B.json();H({type:"success",message:`${oe.message} - -Supplier ID: ${oe.supplier_id||"None"} -Document Type: ${oe.document_type} -Line Items: ${oe.line_items_count} -Duplicate Status: ${oe.duplicate_status||"None"}`}),window.location.reload()}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}}},O1=async()=>{Oi(!0),zi([]),un(!0);try{const B=await fetch(`/api/invoices/${n}/parse-dates`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to parse dates");const oe=await B.json();zi(oe.found_dates||[])}catch(B){console.error("Failed to fetch parsed dates:",B)}finally{Oi(!1)}},Q0=B=>{d(B),un(!1)},L1=async()=>{zn(!0),Jt([]),Ft([]),rs(!0);try{const B=await fetch(`/api/invoices/${n}/parse-invoice-number`,{headers:{Authorization:`Bearer ${e}`}});if(!B.ok)throw new Error("Failed to search for invoice number");const oe=await B.json();Jt(oe.candidates||[]),Ft(oe.supplier_examples||[])}catch(B){console.error("Failed to fetch invoice number candidates:",B)}finally{zn(!1)}},N1=B=>{a(B),rs(!1)},W1=async()=>{if(window.confirm(`Re-send invoice to Azure for OCR extraction? - -This will: -- Fully re-extract data from Azure -- Update all invoice fields -- Re-create line items with product definitions -- Re-run duplicate detection - -Existing data will be replaced.`)){M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/resend-to-azure`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const Ae=await B.json();throw new Error(Ae.detail||"Failed to resend to Azure")}const oe=await B.json();H({type:"success",message:`${oe.message} - -The page will reload automatically when processing completes.`});const be=setInterval(async()=>{try{const Ae=await fetch(`/api/invoices/${n}`,{headers:{Authorization:`Bearer ${e}`}});Ae.ok&&(await Ae.json()).status!=="PENDING"&&(clearInterval(be),window.location.reload())}catch{}},2e3);setTimeout(()=>clearInterval(be),12e4)}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}}},kC=async()=>{M(!0),H(null);try{const B=await fetch(`/api/invoices/${n}/regenerate-highlights`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){const en=await B.json();throw new Error(en.detail||"Failed to regenerate highlights")}const oe=await B.json(),be=oe.non_stock_count||0,Ae=oe.has_notes;let it="";be>0?it=`PDF highlights regenerated successfully. - -Highlighted ${be} non-stock item(s).`:it="PDF highlights cleared (no non-stock items marked).",Ae&&(it+=` -Notes overlay added.`),H({type:"success",message:it}),i.invalidateQueries({queryKey:["invoice",n]})}catch(B){H({type:"error",message:B instanceof Error?B.message:"Operation failed"})}finally{M(!1)}},U1=B=>{Te(B.id),he({product_code:B.product_code,description:B.description,unit:B.unit,quantity:B.quantity,unit_price:B.unit_price,tax_rate:B.tax_rate,amount:B.amount,is_non_stock:B.is_non_stock}),Y(B.id),K(null),Oc()},_C=B=>{B===-1?gC.mutate(Be):Jl.mutate({itemId:B,data:Be}),Te(null),he({}),Y(null)},CC=()=>{Te(null),he({}),Y(null)},$0=()=>{Te(-1),he({product_code:"",description:"",unit:"",quantity:null,unit_price:null,tax_rate:"",amount:null,is_non_stock:!1,line_number:(tx.length||0)+1})},pD=B=>{window.confirm("Are you sure you want to delete this line item? This action cannot be undone.")&&mC.mutate(B)},ed=B=>{ge!==B.id&&U1(B)},AC=()=>{if(!Yd)return[];const B=[];for(const oe of Yd)if(oe.name&&B.push(...oe.name.toLowerCase().split(/\s+/)),oe.aliases)for(const be of oe.aliases)be&&B.push(...be.toLowerCase().split(/\s+/));return[...new Set(B)].filter(oe=>oe.length>1)},H1=B=>{if(!B)return"";let oe=B;oe=oe.replace(/\b\d+\s*x\s*\d+(\.\d+)?\s*(g|kg|ml|ltr|l|oz|cl)?\b/gi,""),oe=oe.replace(/\b(qty|quantity)\s*:?\s*\d+\b/gi,""),oe=oe.replace(/\bcase\s*(of\s*)?\d+\b/gi,""),oe=oe.replace(/\([A-Z]{1,3}-?[A-Z0-9]{1,5}\)/gi,""),oe=oe.replace(/\[[A-Z0-9-]+\]/gi,""),oe=oe.replace(/\b(case|qty|un|pack|box|each|per|unit|pkt|bag|bottle|tin|can|carton|tray|portion|portions)\b/gi,""),oe=oe.replace(/\b\d+(\.\d+)?\s*(g|kg|ml|ltr|l|oz|cl|lb)?\b/gi,""),oe=oe.replace(/[^\w\s]/g," "),oe=oe.replace(/\b(the|a|an|in|on|at|by|for|with|to|of|and|or|is|it|as|be|are|was|been|being|have|has|had|do|does|did|will|would|could|should|may|might|this|that|these|those|from|into|through|during|before|after|above|below|between|under|over)\b/gi,"");const be=AC();if(be.length>0){const Ae=new RegExp(`\\b(${be.map(it=>it.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")})\\b`,"gi");oe=oe.replace(Ae,"")}return oe.split(/\s+/).filter(Ae=>Ae.length>1).join(" ").trim()},TC=B=>{ye(B);const oe=H1(B.description||"");Ye(oe),qe(null),re(!0),oe&&J0(oe)},Z0=B=>{_e!=null&&_e.supplier_id&&q0({isOpen:!0,productCode:B.product_code,description:B.description,unit:B.unit,supplierId:_e.supplier_id,supplierName:_e.supplier_name||"Unknown",currentPrice:B.unit_price||void 0,sourceInvoiceId:_e.id,sourceLineItemId:B.id})},J0=async B=>{if(!(!B||B.length<2)){Ze(!0);try{const oe=await fetch("/api/invoices/line-items/search",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({query:B,exclude_invoice_id:n?parseInt(n):null})});oe.ok&&qe(await oe.json())}finally{Ze(!1)}}},ex=async B=>{if(Yt)try{const oe=Yt.map(be=>fetch(`/api/invoices/${n}/line-items/${be.id}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({is_non_stock:!B})}));await Promise.all(oe),await zc(),i.invalidateQueries({queryKey:["invoice",n]}),J(!1)}catch(oe){console.error("Failed to bulk update stock status:",oe)}},q1=async B=>{var oe;Er(!0),Kn([]);try{const be=await fetch(`/api/ingredients/ai-match?description=${encodeURIComponent(B)}`,{headers:{Authorization:`Bearer ${e}`}});if(be.ok){const Ae=await be.json();((oe=Ae.ranked)==null?void 0:oe.length)>0&&Kn(Ae.ranked)}}catch{}Er(!1)},V1=async()=>{On(!0),Ln(null),ps(null),Tn([]),Zr(new Set);try{const B=await fetch(`/api/invoices/${n}/ai-assist`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!B.ok){let be="AI analysis failed";try{be=(await B.json()).detail||be}catch{}throw new Error(be)}const oe=await B.json();oe.suggestions&&ps(oe.suggestions),oe.reconciliation_matches&&Tn(oe.reconciliation_matches),oe.error&&Ln(oe.error)}catch(B){Ln(B instanceof Error?B.message:"AI analysis failed")}finally{On(!1)}},G1=async(B,oe,be)=>{if(!Yt)return;const Ae=Yt[B];if(Ae)try{await Jl.mutateAsync({itemId:Ae.id,data:{[oe]:be}}),Zr(it=>new Set([...it,`${B}-${oe}`]))}catch(it){console.error("Failed to apply AI correction:",it)}},K1=async B=>{try{await Gu.mutateAsync({supplier_id:B})}catch(oe){console.error("Failed to apply AI supplier match:",oe)}},X1=async B=>{Zl(B),Wo(!1),H0(null),X({pack_quantity:B.pack_quantity,unit_size:B.unit_size,unit_size_type:B.unit_size_type,portions_per_unit:B.portions_per_unit,unit_price:B.unit_price}),st(""),Re(!1),rt(null),nt(!1),al(!1),$s(""),mo([]),Ra(B.ingredient_id||null),No(B.ingredient_name||""),Ba(B.ingredient_unit||""),B.unit_size&&B.unit_size_type&&Ku(B.ingredient_unit||void 0,{pack_quantity:B.pack_quantity,unit_size:B.unit_size,unit_size_type:B.unit_size_type,unit_price:B.unit_price}),ce(!0);try{const oe=await fetch(`/api/invoices/${n}/line-items/${B.id}/definition`,{headers:{Authorization:`Bearer ${e}`}});if(oe.ok){const be=await oe.json();rt(be),st((be==null?void 0:be.portion_description)||"")}}catch{}if(ce(!1),B.description&&!B.ingredient_id&&Y1(B.description),!B.pack_quantity&&!B.unit_size){Wo(!0);try{const oe=await fetch(`/api/invoices/${n}/line-items/${B.id}/ai-pack-size`,{headers:{Authorization:`Bearer ${e}`}});if(oe.ok){const be=await oe.json();be.pack_quantity&&be.unit_size&&(H0(be.source),X(Ae=>({...Ae,pack_quantity:be.pack_quantity,unit_size:be.unit_size,unit_size_type:be.unit_size_type})),Ku(B.ingredient_unit||void 0,{pack_quantity:be.pack_quantity,unit_size:be.unit_size,unit_size_type:be.unit_size_type,unit_price:B.unit_price}))}}catch{}Wo(!1)}},Y1=async B=>{if(!B||B.length<2){mo([]);return}Kd(!0);try{const oe=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(B)}`,{headers:{Authorization:`Bearer ${e}`}});if(oe.ok){const be=await oe.json();mo(be)}}catch{}Kd(!1)},Q1=B=>{Ra(B.id),No(B.name),Ba(B.standard_unit),$s(""),mo([]),Q.unit_size_type||X(oe=>({...oe,unit_size_type:B.standard_unit})),Ku(B.standard_unit)},Ku=(B,oe)=>{var lr;const be=oe?{...Q,...oe}:Q,Ae=B||Js||be.unit_size_type,it=be.pack_quantity||1,en=be.unit_size,rn=be.unit_size_type,Nn=be.unit_price;if(!en||!rn||!Ae){ze("");return}const gr=(lr={g:{g:1,kg:.001},kg:{g:1e3,kg:1},oz:{g:28.3495,kg:.0283495},ml:{ml:1,ltr:.001},cl:{ml:10,ltr:.01},ltr:{ml:1e3,ltr:1},each:{each:1}}[rn])==null?void 0:lr[Ae];if(!gr){ze(rn!==Ae?`Cannot convert ${rn} → ${Ae}`:`${en}${rn}`);return}const br=it*en*gr,mr=Nn?Nn/br:null;let er=`${it>1?`${it} × ${en}${rn} = `:""}${br.toFixed(br%1?2:0)} ${Ae}`;mr&&(er+=` → £${mr.toFixed(4)} per ${Ae}`,Ae==="g"&&mr?er+=` (£${(mr*1e3).toFixed(2)}/kg)`:Ae==="ml"&&mr&&(er+=` (£${(mr*1e3).toFixed(2)}/ltr)`)),ze(er)},FC=B=>{zc(),dl()},dl=()=>{Zl(null),X({}),st(""),Re(!1),rt(null),Ra(null),No(""),Ba(""),al(!1),$s(""),mo([]),ze("")},DC=async B=>{if(await Jl.mutateAsync({itemId:B,data:Q}),Zs)try{if(await fetch(`/api/invoices/${n}/line-items/${B}`,{method:"PATCH",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_id:Zs})}),_e!=null&&_e.supplier_id){const oe={supplier_id:_e.supplier_id,pack_quantity:Q.pack_quantity||1,unit_size:Q.unit_size||null,unit_size_type:Q.unit_size_type||Js||null},be=nn;be!=null&&be.product_code?oe.product_code=be.product_code:be!=null&&be.description&&(oe.description_pattern=be.description.substring(0,100).toLowerCase().trim()),Q.unit_price&&(oe.latest_unit_price=Q.unit_price),n&&(oe.invoice_id=parseInt(n));const Ae=await fetch(`/api/ingredients/${Zs}/sources`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(oe)});if(!Ae.ok){const it=await Ae.json().catch(()=>({}));console.warn("Source creation failed:",Ae.status,it)}}}catch(oe){console.error("Failed to set ingredient mapping:",oe)}if(Ve)try{await yC.mutateAsync({itemId:B,portionDesc:Ne})}catch(oe){console.error("Failed to save definition:",oe)}dl(),zc()},tx=k.useMemo(()=>{if(!Yt)return[];let B=Yt.map(oe=>({...oe,_originalIndex:oe.line_number}));if(hn){const oe=hn.toLowerCase();B=B.filter(be=>{const Ae=(be.product_code||"").toLowerCase(),it=(be.description||"").toLowerCase();return Ae.includes(oe)||it.includes(oe)})}return tn&&(B=B.filter(oe=>tn==="consistent"?oe.price_change_status==="consistent":tn==="amber"?oe.price_change_status==="amber":tn==="red"?oe.price_change_status==="red":tn==="no_history"?oe.price_change_status==="no_history":!0)),js&&(B=B.filter(oe=>{const be=oe.portions_per_unit!=null&&oe.portions_per_unit>0;return js==="yes"?be:js==="no"?!be:!0})),fs==="missing"&&(B=B.filter(oe=>{const be=oe.quantity==null||oe.quantity===0,Ae=oe.unit_price==null||oe.unit_price===0,it=oe.amount==null||oe.amount===0;return be||Ae||it})),gi&&B.sort((oe,be)=>{let Ae=null,it=null;switch(gi){case"code":Ae=oe.product_code||"",it=be.product_code||"";break;case"description":Ae=oe.description||"",it=be.description||"";break;case"unit":Ae=oe.unit||"",it=be.unit||"";break;case"quantity":Ae=oe.quantity||0,it=be.quantity||0;break;case"unit_price":Ae=oe.unit_price||0,it=be.unit_price||0;break;case"price_change":Ae=oe.price_change_percent||0,it=be.price_change_percent||0;break;case"amount":Ae=oe.amount||0,it=be.amount||0;break}return typeof Ae=="string"?bt==="asc"?Ae.localeCompare(it):it.localeCompare(Ae):bt==="asc"?Ae-it:it-Ae}),B},[Yt,gi,bt,tn,hn,js,fs]);k.useEffect(()=>{const B=Pa.current;if(!B)return;const oe=()=>{const be=B.querySelectorAll("tr[data-page]");if(be.length===0)return;const Ae=B.getBoundingClientRect().top+50;for(const rn of be)if(rn.getBoundingClientRect().top>=Ae-10){const Qn=parseInt(rn.getAttribute("data-page")||"1",10);xn(Qn);return}const it=be[be.length-1],en=parseInt(it.getAttribute("data-page")||"1",10);xn(en)};return B.addEventListener("scroll",oe),oe(),()=>B.removeEventListener("scroll",oe)},[tx]);const qn=k.useMemo(()=>{if(!Yt)return{total:0,withPortions:0,withoutPortions:0,missingData:0,nonStock:0,priceCalcErrors:0,totalsMatch:!0,totalDifference:0,lineItemsTotal:0,stockItemsTotal:0,nonStockItemsTotal:0,stockItemsGross:0};const B=Yt.filter(Kt=>Kt.portions_per_unit!=null&&Kt.portions_per_unit>0).length,oe=Yt.filter(Kt=>{const Fn=Kt.quantity==null||Kt.quantity===0,Jr=Kt.unit_price==null||Kt.unit_price===0,ei=Kt.amount==null||Kt.amount===0;return Fn||Jr||ei}).length,be=Yt.filter(Kt=>Kt.is_non_stock).length,Ae=Yt.filter(Kt=>{const Fn=Kt.quantity!=null&&Kt.quantity!==0,Jr=Kt.unit_price!=null&&Kt.unit_price!==0,ei=Kt.amount!=null&&Kt.amount!==0,Ui=(Kt.quantity||0)*(Kt.unit_price||0),Uo=Kt.amount||0,da=Math.abs(Ui-Uo)>.02;return Jr&&(!Fn||!ei)||ei&&(!Fn||!Jr)||Fn&&Jr&&ei&&da}).length,it=Yt.reduce((Kt,Fn)=>Kt+(Fn.amount||0),0),en=Yt.filter(Kt=>!Kt.is_non_stock).reduce((Kt,Fn)=>Kt+(Fn.amount||0),0),rn=Yt.filter(Kt=>Kt.is_non_stock).reduce((Kt,Fn)=>Kt+(Fn.amount||0),0),Nn=parseFloat(c)||0,Qn=parseFloat(f)||Nn,gr=Qn>0?Nn/Qn:1,br=en,mr=en*gr,er=Math.abs(Qn-it),lr=er<=EK;return{total:Yt.length,withPortions:B,withoutPortions:Yt.length-B,missingData:oe,nonStock:be,priceCalcErrors:Ae,totalsMatch:lr,totalDifference:er,lineItemsTotal:it,stockItemsTotal:en,stockItemsNet:br,nonStockItemsTotal:rn,stockItemsGross:mr}},[Yt,c,f]),Qd=k.useMemo(()=>!Yt||Yt.length===0||!qn.totalsMatch||qn.priceCalcErrors>0,[Yt,qn.totalsMatch,qn.priceCalcErrors]),Nc=k.useMemo(()=>Yt?{consistent:Yt.filter(B=>B.price_change_status==="consistent").length,amber:Yt.filter(B=>B.price_change_status==="amber").length,red:Yt.filter(B=>B.price_change_status==="red").length,no_history:Yt.filter(B=>B.price_change_status==="no_history").length,withPortions:Yt.filter(B=>B.portions_per_unit!=null&&B.portions_per_unit>0).length,withoutPortions:Yt.filter(B=>!(B.portions_per_unit!=null&&B.portions_per_unit>0)).length,missingData:Yt.filter(B=>{const oe=B.quantity==null||B.quantity===0,be=B.unit_price==null||B.unit_price===0,Ae=B.amount==null||B.amount===0;return oe||be||Ae}).length}:{consistent:0,amber:0,red:0,no_history:0,withPortions:0,withoutPortions:0,missingData:0},[Yt]),Xu=B=>{gi===B?yn(bt==="asc"?"desc":"asc"):(je(B),yn("asc"))};if(T1)return s.jsx("div",{style:fe.loading,children:"Loading invoice..."});if(!_e)return s.jsx("div",{style:fe.error,children:"Invoice not found"});const $1=_e.ocr_confidence?(Number(_e.ocr_confidence)*100).toFixed(0):null,Yu=(Z1=_e==null?void 0:_e.image_path)==null?void 0:Z1.toLowerCase().endsWith(".pdf");return s.jsxs("div",{style:fe.pageContainer,children:[(_e==null?void 0:_e.ocr_raw_text)&&_e.ocr_raw_text.startsWith("Error:")&&s.jsxs("div",{style:fe.errorBanner,children:[s.jsx("div",{style:fe.errorBannerIcon,children:"⚠️"}),s.jsxs("div",{style:fe.errorBannerContent,children:[s.jsx("strong",{children:"OCR Processing Error"}),s.jsx("p",{children:_e.ocr_raw_text.replace("Error: ","")}),_e.ocr_raw_text.includes("quota exceeded")&&s.jsxs("p",{style:{marginTop:"0.5rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:"Next steps:"}),' Check your Azure subscription budget limits in the Azure portal. Once resolved, use the "Reprocess" button below to retry OCR extraction.']}),_e.ocr_raw_text.includes("authentication failed")&&s.jsxs("p",{style:{marginTop:"0.5rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:"Next steps:"})," Verify your Azure API credentials in Settings → Azure Configuration."]})]})]}),_e.status==="PENDING"&&s.jsxs("div",{style:{display:"flex",gap:"1rem",padding:"1rem 1.5rem",marginBottom:"1.5rem",background:"#d4edda",border:"2px solid #28a745",borderRadius:"8px",color:"#155724",alignItems:"center"},children:[s.jsx("div",{style:{fontSize:"1.5rem",flexShrink:0},children:"⚙"}),s.jsxs("div",{children:[s.jsx("strong",{children:"Processing Invoice"}),s.jsx("p",{style:{margin:"0.25rem 0 0"},children:"Azure OCR extraction is in progress. The page will reload automatically when complete."})]})]}),s.jsxs("div",{style:fe.topRow,children:[s.jsxs("div",{style:fe.imageSection,ref:Ke,children:[s.jsxs("h3",{children:["Invoice ",Yu?"Document":"Image"]}),Mf?Yu?s.jsx("div",{style:fe.pdfScrollContainer,ref:on,children:Je.length>0?Je.map((B,oe)=>{const be=oe+1,Ae=ae?la(ae):null,it=de!==null&&Yt?(()=>{const en=Yt.find(rn=>rn.id===de);return en?F1(en.line_number):null})():null;return s.jsxs("div",{style:fe.pdfPageWrapper,children:[s.jsxs("div",{"data-page-container":!0,style:{...fe.pdfPageContainer,position:"relative",width:B.displayWidth*(ot===be?ct:1),height:B.displayHeight*(ot===be?ct:1),margin:"0 auto"},children:[s.jsx("img",{src:B.canvas.toDataURL(),alt:`Page ${be}`,style:{width:"100%",height:"100%",display:"block"}}),Ae&&Ae.pageNumber===be&&(()=>{const rn=Math.max(1,2/ct);return s.jsx("div",{ref:vt,style:{...fe.highlightOverlay,left:`${Ae.x-.5}%`,top:`${Ae.y-.5}%`,width:`${Ae.width+.5*2}%`,height:`${Ae.height+.5*2}%`,border:`${rn}px solid #ffc107`},onClick:()=>{K(null),Oc()}})})(),it&&it.pageNumber===be&&(()=>{const rn=Math.max(1,2/ct);return s.jsx("div",{style:{...fe.highlightOverlay,left:`${it.x-.5}%`,top:`${it.y-.5}%`,width:`${it.width+.5*2}%`,height:`${it.height+.5*2}%`,border:`${rn}px solid #ffc107`},onClick:()=>{Y(null),Oc()}})})()]}),Je.length>1&&s.jsxs("div",{style:fe.pageLabel,children:["Page ",be," of ",Je.length]})]},oe)}):s.jsx("div",{style:fe.imagePlaceholder,children:"Rendering PDF..."})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:fe.imageZoomControls,children:[s.jsx("button",{onClick:()=>An(Math.min(Ot+.5,5)),style:fe.zoomBtn,title:"Zoom In",children:"+"}),s.jsxs("span",{style:fe.zoomLabel,children:[Math.round(Ot*100),"%"]}),s.jsx("button",{onClick:()=>An(Math.max(Ot-.5,1)),style:fe.zoomBtn,title:"Zoom Out",children:"−"}),Ot>1&&s.jsx("button",{onClick:()=>An(1),style:fe.zoomResetBtnSmall,title:"Reset Zoom",children:"Reset"})]}),s.jsx("div",{style:{...fe.imageScrollContainer,cursor:Ot>1?"grab":"default"},ref:Rt,onWheel:B=>{if(B.ctrlKey||B.metaKey){B.preventDefault();const oe=B.deltaY>0?-.1:.1;An(Math.max(1,Math.min(5,Ot+oe)))}},children:s.jsxs("div",{style:{...fe.imageContainer,width:`${Ot*100}%`,height:"auto"},children:[s.jsx("img",{src:Mf,alt:"Invoice",style:{...fe.image,width:"100%",height:"auto"}}),ae&&la(ae)&&(()=>{const B=la(ae),oe=.5;return s.jsx("div",{style:{...fe.highlightOverlay,left:`${B.x-oe}%`,top:`${B.y-oe}%`,width:`${B.width+oe*2}%`,height:`${B.height+oe*2}%`,border:"2px solid #ffc107"},onClick:()=>K(null)})})()]})})]}):s.jsxs("div",{style:fe.imagePlaceholder,children:["Loading ",Yu?"document":"image","..."]}),Yu&&ct>1&&s.jsxs("button",{onClick:Oc,style:fe.zoomResetBtn,children:["Reset Zoom (",ct,"x)"]}),Yu&&Mf&&s.jsx("a",{href:`/api/invoices/${n}/file?token=${encodeURIComponent(e||"")}`,target:"_blank",rel:"noopener noreferrer",style:fe.openPdfLink,children:"Open PDF in new tab"}),$1&&s.jsxs("div",{style:fe.confidenceBadge,children:["OCR Confidence: ",$1,"%"]})]}),s.jsxs("div",{style:fe.formSection,children:[_e.duplicate_status&&s.jsx("div",{style:{...fe.duplicateWarning,background:_e.duplicate_status==="firm_duplicate"?"#f8d7da":"#fff3cd",borderColor:_e.duplicate_status==="firm_duplicate"?"#f5c6cb":"#ffeeba",color:_e.duplicate_status==="firm_duplicate"?"#721c24":"#856404"},onClick:()=>F(!0),children:_e.duplicate_status==="firm_duplicate"?"⚠️ DUPLICATE: This invoice matches an existing record. Click to compare.":"⚠️ Possible duplicate detected. Click to compare."}),(Ni==null?void 0:Ni.linked_po)&&s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.75rem 1rem",marginBottom:"1rem",background:"#d4edda",border:"1px solid #c3e6cb",borderRadius:"8px",color:"#155724",fontSize:"0.9rem"},children:[s.jsxs("div",{children:[s.jsxs("strong",{children:["Linked to PO-",Ni.linked_po.po_id]})," ","(",Ni.linked_po.total_amount!=null?`£${Ni.linked_po.total_amount.toFixed(2)}`:"N/A",", ",Ni.linked_po.order_date?new Date(Ni.linked_po.order_date+"T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}):"",")"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>V0(Ni.linked_po.po_id),style:{padding:"0.3rem 0.6rem",border:"1px solid #155724",borderRadius:"4px",background:"white",color:"#155724",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},children:"View PO"}),s.jsx("button",{onClick:()=>R1(Ni.linked_po.po_id),style:{padding:"0.3rem 0.6rem",border:"1px solid #856404",borderRadius:"4px",background:"#fff3cd",color:"#856404",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},children:"Unlink"})]})]}),!(Ni!=null&&Ni.linked_po)&&(Ni==null?void 0:Ni.matches)&&Ni.matches.length>0&&s.jsxs("div",{style:{padding:"0.75rem 1rem",marginBottom:"1rem",background:"#e3f2fd",border:"1px solid #bbdefb",borderRadius:"8px",fontSize:"0.9rem",color:"#1565c0"},children:[s.jsxs("div",{style:{fontWeight:600,marginBottom:"0.5rem"},children:["This supplier has ",Ni.matches.length," pending Purchase Order",Ni.matches.length>1?"s":""]}),Ni.matches.map((B,oe)=>{const be=oe===0&&B.confidence>=.8,Ae=!be&&B.confidence>=.8;return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.4rem 0.5rem",marginBottom:"0.25rem",background:"rgba(255,255,255,0.6)",borderRadius:"4px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsxs("span",{style:{fontWeight:500},children:["PO-",B.po_id,":"]}),s.jsx("span",{children:B.total_amount!=null?`£${B.total_amount.toFixed(2)}`:"N/A"}),s.jsxs("span",{style:{color:"#666"},children:["(",B.order_date?new Date(B.order_date+"T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}):"No date",")"]}),be&&s.jsx("span",{style:{background:"#4caf50",color:"white",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.75rem",fontWeight:600},children:"Suggested match"}),Ae&&s.jsx("span",{style:{background:"#ff9800",color:"white",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.75rem",fontWeight:600},children:"Potential match"})]}),s.jsxs("div",{style:{display:"flex",gap:"0.4rem"},children:[s.jsx("button",{onClick:()=>V0(B.po_id),style:{padding:"0.2rem 0.5rem",border:"1px solid #1565c0",borderRadius:"4px",background:"white",color:"#1565c0",cursor:"pointer",fontSize:"0.8rem"},children:"View"}),s.jsx("button",{onClick:()=>bC(B.po_id),style:{padding:"0.2rem 0.5rem",border:"none",borderRadius:"4px",background:"#1565c0",color:"white",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},children:"Link"})]})]},B.po_id)})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"20px"},children:[s.jsx("h3",{style:{margin:0},children:"Invoice Details"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[_e.source&&_e.source!=="upload"&&s.jsx(ufe,{source:_e.source,sourceReference:_e.source_reference}),s.jsxs("span",{style:{padding:"0.4rem 0.8rem",borderRadius:"4px",fontSize:"0.85rem",fontWeight:"600",background:_e.status==="CONFIRMED"?"#22c55e":_e.status==="REVIEWED"?"#8b5cf6":_e.status==="PROCESSED"?"#3b82f6":"#f59e0b",color:"white"},children:[_e.status.toUpperCase(),_e.document_type==="delivery_note"&&" (DN)"]})]})]}),s.jsxs("div",{style:fe.form,children:[s.jsxs("div",{style:fe.label,children:[s.jsx("span",{children:"Supplier"}),s.jsxs("div",{style:fe.supplierRow,children:[s.jsxs("select",{value:S,onChange:B=>_(B.target.value),style:{...fe.input,flex:1,...(_e==null?void 0:_e.supplier_match_type)==="fuzzy"&&S?{border:"2px solid #f0ad4e",background:"#fff8e6"}:{}},children:[s.jsx("option",{value:"",children:"-- Select Supplier --"}),Yd==null?void 0:Yd.map(B=>s.jsx("option",{value:B.id,children:B.name},B.id))]}),la("VendorName")&&s.jsx("button",{type:"button",onClick:()=>Lc("VendorName"),style:{...fe.eyeBtn,...ae==="VendorName"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"}),s.jsx("button",{type:"button",onClick:I1,style:fe.createSupplierBtn,title:"Create new supplier",children:"+ New"})]}),(_e==null?void 0:_e.supplier_match_type)==="fuzzy"&&S&&_e.vendor_name&&s.jsxs("div",{style:fe.fuzzyMatchWarning,children:[s.jsxs("span",{children:['Fuzzy match from "',_e.vendor_name,'" - please verify']}),s.jsx("button",{type:"button",onClick:()=>Y0.mutate({supplierId:parseInt(S),alias:_e.vendor_name,invoiceId:_e.id}),style:fe.addAliasBtn,disabled:Y0.isPending,title:"Add this name as an alias so future invoices match exactly",children:Y0.isPending?"Adding...":"+ Add as alias"})]}),(_e==null?void 0:_e.vendor_name)&&!S&&s.jsxs("div",{style:fe.extractedHintRow,children:[s.jsxs("span",{style:fe.extractedHint,children:["Extracted: ",_e.vendor_name]}),s.jsxs("button",{type:"button",onClick:I1,style:fe.createFromExtractedBtn,children:['Create "',_e.vendor_name,'"']})]})]}),s.jsxs("div",{style:fe.row,children:[s.jsxs("label",{style:{...fe.label,flex:1},children:["Invoice Date",(()=>{const B=bx(l||null,(_e==null?void 0:_e.status)||"");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"date",value:l,onChange:oe=>d(oe.target.value),style:{...fe.input,...pfe[B]}}),la("InvoiceDate")&&s.jsx("button",{type:"button",onClick:()=>Lc("InvoiceDate"),style:{...fe.eyeBtn,...ae==="InvoiceDate"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"}),(_e==null?void 0:_e.status)!=="CONFIRMED"&&s.jsx("button",{type:"button",onClick:O1,style:{background:"none",border:"none",cursor:"pointer",padding:"2px 4px",fontSize:"1rem",color:!l||B!=="none"?"#007bff":"#ccc",display:"flex",alignItems:"center"},title:"Find dates in document",children:"🔍"})]}),B!=="none"&&s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:B==="future"?s.jsx("button",{type:"button",onClick:O1,style:{background:"none",border:"none",padding:0,cursor:"pointer",fontSize:"0.8rem",color:"#e85d04",fontWeight:600,textDecoration:"underline",textDecorationStyle:"dotted"},title:"Click to fix date",children:"⚠ Date is in the future — likely a day/month swap — click to fix"}):s.jsx("span",{style:{fontSize:"0.8rem",color:B==="red"?"#dc3545":"#856404"},children:l?"Date differs from today by more than 7 days":"No date set"})})]})})()]}),s.jsxs("label",{style:{...fe.label,flex:1},children:["Document Type",s.jsxs("select",{value:x,onChange:B=>w(B.target.value),style:fe.input,children:[s.jsx("option",{value:"invoice",children:"Invoice"}),s.jsx("option",{value:"credit_note",children:"Credit Note"}),s.jsx("option",{value:"delivery_note",children:"Delivery Note"})]})]})]}),s.jsxs("div",{style:fe.row,children:[s.jsxs("label",{style:{...fe.label,flex:1},children:["Invoice Number",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"text",value:o,onChange:B=>a(B.target.value),style:fe.input,placeholder:"e.g., INV-12345"}),la("InvoiceId")&&s.jsx("button",{type:"button",onClick:()=>Lc("InvoiceId"),style:{...fe.eyeBtn,...ae==="InvoiceId"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"}),(_e==null?void 0:_e.status)!=="CONFIRMED"&&s.jsx("button",{type:"button",onClick:L1,style:{background:"none",border:"none",cursor:"pointer",padding:"2px 4px",fontSize:"1rem",color:o?"#ccc":"#007bff",display:"flex",alignItems:"center"},title:"Search OCR for invoice number",children:"🔍"})]})]}),s.jsxs("label",{style:{...fe.label,flex:1},children:["Order/PO Number",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"text",value:y,onChange:B=>v(B.target.value),style:fe.input,placeholder:"e.g., PO-12345"}),la("PurchaseOrder")&&s.jsx("button",{type:"button",onClick:()=>Lc("PurchaseOrder"),style:{...fe.eyeBtn,...ae==="PurchaseOrder"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})]})]})]}),s.jsxs("div",{style:fe.row,children:[s.jsxs("label",{style:{...fe.label,flex:1},children:["Net Total (£)",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"number",step:"0.01",value:f,onChange:B=>p(B.target.value),style:fe.input,placeholder:"Exc. VAT"}),la("SubTotal")&&s.jsx("button",{type:"button",onClick:()=>Lc("SubTotal"),style:{...fe.eyeBtn,...ae==="SubTotal"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})]})]}),s.jsxs("label",{style:{...fe.label,flex:1},children:["Gross Total (£)",s.jsxs("div",{style:fe.inputWithEye,children:[s.jsx("input",{type:"number",step:"0.01",value:c,onChange:B=>u(B.target.value),style:fe.input,placeholder:"Inc. VAT"}),la("InvoiceTotal")&&s.jsx("button",{type:"button",onClick:()=>Lc("InvoiceTotal"),style:{...fe.eyeBtn,...ae==="InvoiceTotal"?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})]})]})]}),s.jsxs("label",{style:fe.label,children:[s.jsxs("span",{children:["Invoice Notes"," ",s.jsx("small",{style:{color:"#666",fontSize:"0.85em"},children:"(Optional, included in Dext etc.)"})]}),s.jsx("textarea",{value:Cr,onChange:B=>Qt(B.target.value),onBlur:async()=>{try{await fetch(`/api/invoices/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({notes:Cr})})}catch(B){console.error("Failed to save notes:",B)}},placeholder:"Add notes about this invoice...",rows:3,style:{...fe.input,resize:"vertical",fontFamily:"inherit"}})]})]}),s.jsxs("div",{style:{marginTop:"20px",display:"flex",gap:"10px"},children:[(_e==null?void 0:_e.document_type)==="credit_note"&&(_e==null?void 0:_e.supplier_id)&&(_e!=null&&_e.linked_dispute_id?s.jsx("button",{onClick:()=>O(_e.linked_dispute_id),style:{padding:"0.75rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold",fontSize:"0.9rem",whiteSpace:"nowrap"},title:"View the dispute resolved by this credit note",children:"✓ Resolved Dispute"}):s.jsx("button",{onClick:()=>Ai(!0),style:{padding:"0.75rem 1rem",background:"#28a745",color:"white",border:"none",borderRadius:"8px",cursor:"pointer",fontWeight:"bold",fontSize:"0.9rem",whiteSpace:"nowrap"},title:"Link this credit note to an open dispute",children:"Link Dispute"})),s.jsx("button",{onClick:M1,style:{...fe.confirmBtn,flex:1,opacity:Qd||Gu.isPending?.5:1,cursor:Qd||Gu.isPending?"not-allowed":"pointer"},disabled:Qd||Gu.isPending,title:Qd?"Fix line item validation errors before confirming":"",children:_e!=null&&_e.dext_sent_at||_e!=null&&_e.supplier_skip_dext?"CONFIRM":"CONFIRM & DEXT"})]}),Yt&&Yt.length>0&&s.jsxs("div",{style:{margin:"20px 0",display:"flex",gap:"8px"},children:[s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`2px solid ${qn.totalsMatch?"#c3e6cb":"#dc2626"}`,background:qn.totalsMatch?"#d4edda":"#fef2f2",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:qn.totalsMatch?"✓":"⛔"}),s.jsx("div",{style:{fontWeight:"600",color:qn.totalsMatch?"#155724":"#dc2626",marginBottom:"2px"},children:"Items Total"}),s.jsx("div",{style:{fontSize:"0.7rem",color:qn.totalsMatch?"#155724":"#dc2626"},children:qn.totalsMatch?"Matches":"Doesn't match"})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`2px solid ${qn.priceCalcErrors===0?"#c3e6cb":"#dc2626"}`,background:qn.priceCalcErrors===0?"#d4edda":"#fef2f2",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:qn.priceCalcErrors===0?"✓":"⛔"}),s.jsx("div",{style:{fontWeight:"600",color:qn.priceCalcErrors===0?"#155724":"#dc2626",marginBottom:"2px"},children:"QTY/Price"}),s.jsx("div",{style:{fontSize:"0.7rem",color:qn.priceCalcErrors===0?"#155724":"#dc2626"},children:qn.priceCalcErrors===0?"All OK":`${qn.priceCalcErrors} error${qn.priceCalcErrors!==1?"s":""}`})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${qn.withoutPortions===0?"#c3e6cb":"#ffc107"}`,background:qn.withoutPortions===0?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:"📦"}),s.jsx("div",{style:{fontWeight:"600",color:qn.withoutPortions===0?"#155724":"#856404",marginBottom:"2px"},children:"Portions"}),s.jsxs("div",{style:{fontSize:"0.7rem",color:qn.withoutPortions===0?"#155724":"#856404"},children:[qn.withPortions," / ",qn.total]})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${qn.missingData===0?"#c3e6cb":"#ffc107"}`,background:qn.missingData===0?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:qn.missingData===0?"✓":"⚠"}),s.jsx("div",{style:{fontWeight:"600",color:qn.missingData===0?"#155724":"#856404",marginBottom:"2px"},children:"Missing Data"}),s.jsxs("div",{style:{fontSize:"0.7rem",color:qn.missingData===0?"#155724":"#856404"},children:[qn.missingData," item",qn.missingData!==1?"s":""]})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${qn.nonStock===0?"#c3e6cb":"#ffc107"}`,background:qn.nonStock===0?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:"🚫"}),s.jsx("div",{style:{fontWeight:"600",color:qn.nonStock===0?"#155724":"#856404",marginBottom:"2px"},children:"Non-Stock"}),s.jsxs("div",{style:{fontSize:"0.7rem",color:qn.nonStock===0?"#155724":"#856404"},children:[qn.nonStock," item",qn.nonStock!==1?"s":""]})]}),s.jsxs("div",{style:{flex:1,padding:"8px",borderRadius:"4px",border:`1px solid ${_e.supplier_skip_dext||_e.dext_sent_at?"#c3e6cb":"#ffc107"}`,background:_e.supplier_skip_dext||_e.dext_sent_at?"#d4edda":"#fff3cd",display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",fontSize:"0.8rem"},children:[s.jsx("div",{style:{fontSize:"1.3rem",marginBottom:"2px"},children:_e.supplier_skip_dext?"−":_e.dext_sent_at?"✓":"⚠"}),s.jsx("div",{style:{fontWeight:"600",color:_e.supplier_skip_dext||_e.dext_sent_at?"#155724":"#856404",marginBottom:"2px"},children:"Dext Status"}),s.jsx("div",{style:{fontSize:"0.7rem",color:_e.supplier_skip_dext||_e.dext_sent_at?"#155724":"#856404"},children:_e.supplier_skip_dext?"N/A (Skipped)":_e.dext_sent_at?new Date(_e.dext_sent_at).toLocaleDateString():"Not sent"})]})]}),_e.disputes&&_e.disputes.length>0&&s.jsx("div",{style:{marginTop:"15px",display:"flex",flexDirection:"column",gap:"10px"},children:_e.disputes.map(B=>{const oe=["NEW","CONTACTED","AWAITING_CREDIT","AWAITING_REPLACEMENT"].includes(B.status);return s.jsxs("div",{onClick:()=>O(B.id),style:{padding:"12px",background:oe?"#fff3cd":"#d1ecf1",border:`2px solid ${oe?"#ffc107":"#17a2b8"}`,borderRadius:"8px",display:"flex",justifyContent:"space-between",alignItems:"center",cursor:"pointer"},children:[s.jsxs("div",{children:[s.jsxs("div",{style:{fontWeight:"bold",color:"#1a1a2e",marginBottom:"4px"},children:[oe?"⚠️":"ℹ️"," ",B.status.replace(/_/g," ")]}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666"},children:["#",B.id," - ",B.dispute_type.replace(/_/g," ").toUpperCase()," - ",B.title]})]}),s.jsx("span",{style:{padding:"6px 12px",background:"#e94560",color:"white",borderRadius:"4px",fontSize:"0.85rem",fontWeight:"bold",whiteSpace:"nowrap"},children:"View"})]},B.id)})}),s.jsxs("div",{style:{marginTop:"15px",display:"flex",flexDirection:"column",alignItems:"center",gap:"10px"},children:[s.jsxs("div",{style:{display:"flex",gap:"10px"},children:[(_e.status==="CONFIRMED"||_e.status==="REVIEWED")&&(ui==null?void 0:ui.dext_manual_send_enabled)&&!_e.supplier_skip_dext&&s.jsx("button",{onClick:()=>Lr(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:Qd?"not-allowed":"pointer",minWidth:"130px",whiteSpace:"nowrap",opacity:Qd?.5:1},disabled:Qd,title:Qd?"Fix line item validation errors before sending to Dext":"",children:_e.dext_sent_at?"Resend to Dext":"Send to Dext"}),s.jsx("button",{onClick:()=>C(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#dc3545",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",minWidth:"110px",whiteSpace:"nowrap"},children:"Delete Invoice"}),s.jsx("button",{onClick:()=>L(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#f0ad4e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",minWidth:"110px",whiteSpace:"nowrap"},children:"Log Dispute"}),(ui==null?void 0:ui.llm_enabled)&&(ui==null?void 0:ui.anthropic_api_key_set)&&s.jsx("button",{onClick:V1,disabled:is,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:sn?"#6f42c1":"#7952b3",color:"white",border:"none",borderRadius:"4px",cursor:is?"wait":"pointer",minWidth:"120px",whiteSpace:"nowrap",opacity:is?.7:1},children:is?"Analysing...":sn?"✨ AI Results":"✨ AI Assist"}),s.jsx("button",{onClick:()=>G(!0),style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:"#6c757d",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",minWidth:"120px",whiteSpace:"nowrap"},children:"View OCR Data"})]}),(t==null?void 0:t.is_admin)&&s.jsxs("div",{style:{display:"flex",gap:"10px"},children:[!_e.supplier_skip_dext&&s.jsx("button",{onClick:SC,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"140px",whiteSpace:"nowrap"},children:U?"Processing...":"Mark Dext Sent"}),s.jsx("button",{onClick:jC,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#ffc107",color:"#000",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"130px",whiteSpace:"nowrap"},children:U?"Processing...":"Reprocess OCR"}),s.jsx("button",{onClick:W1,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#fd7e14",color:"white",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"150px",whiteSpace:"nowrap"},children:U?"Processing...":"Resend to Azure"}),s.jsx("button",{onClick:kC,disabled:U,style:{padding:"0.4rem 1.2rem",fontSize:"0.8rem",background:U?"#ccc":"#6f42c1",color:"white",border:"none",borderRadius:"4px",cursor:U?"not-allowed":"pointer",minWidth:"160px",whiteSpace:"nowrap"},title:"Regenerate PDF highlight annotations for non-stock items",children:U?"Processing...":"Regen Highlights"})]}),I&&s.jsxs("div",{style:{marginTop:"10px",padding:"12px",borderRadius:"4px",background:I.type==="success"?"#d4edda":"#f8d7da",color:I.type==="success"?"#155724":"#721c24",border:`1px solid ${I.type==="success"?"#c3e6cb":"#f5c6cb"}`,fontSize:"0.85rem",whiteSpace:"pre-wrap",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[s.jsx("span",{children:I.message}),s.jsx("button",{onClick:()=>H(null),style:{background:"transparent",border:"none",fontSize:"1.2rem",cursor:"pointer",marginLeft:"10px",color:"inherit"},children:"×"})]})]})]})]}),(sn||Dt||It.length>0)&&s.jsxs("div",{style:{background:"#f8f5ff",border:"1px solid #d4c5f9",borderRadius:"8px",padding:"1rem",marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[s.jsxs("h3",{style:{margin:0,color:"#5a32a3",fontSize:"1rem"},children:["✨"," AI Analysis"]}),s.jsx("button",{onClick:()=>{ps(null),Tn([]),Ln(null)},style:{background:"none",border:"none",cursor:"pointer",fontSize:"1.1rem",color:"#999"},children:"✕"})]}),Dt&&s.jsx("div",{style:{background:"#f8d7da",color:"#721c24",padding:"0.5rem 0.75rem",borderRadius:"4px",fontSize:"0.85rem",marginBottom:"0.5rem"},children:Dt}),(sn==null?void 0:sn.supplier_match)&&!_e.supplier_id&&s.jsxs("div",{style:{background:"#d1ecf1",padding:"0.5rem 0.75rem",borderRadius:"4px",marginBottom:"0.5rem",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{style:{fontSize:"0.85rem",color:"#0c5460"},children:["Supplier: ",s.jsx("strong",{children:sn.supplier_match.name})," (",(sn.supplier_match.confidence*100).toFixed(0),"% confident) — ",sn.supplier_match.reason]}),s.jsx("button",{onClick:()=>K1(sn.supplier_match.id),style:{padding:"0.25rem 0.75rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},children:"Accept"})]}),(sn==null?void 0:sn.total_mismatch_analysis)&&s.jsxs("div",{style:{background:"#fff3cd",padding:"0.5rem 0.75rem",borderRadius:"4px",marginBottom:"0.5rem",fontSize:"0.85rem",color:"#856404"},children:[s.jsx("strong",{children:"Total mismatch:"})," ",sn.total_mismatch_analysis]}),(sn==null?void 0:sn.vat_treatment)&&s.jsxs("div",{style:{background:"#e2e3e5",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.5rem",fontSize:"0.85rem",color:"#383d41"},children:["VAT treatment: ",s.jsx("strong",{children:sn.vat_treatment})]}),(sn==null?void 0:sn.line_item_corrections)&&sn.line_item_corrections.length>0&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Line Item Corrections"}),sn.line_item_corrections.filter(B=>!Fi.has(`${B.idx}-${B.field}`)).map((B,oe)=>s.jsxs("div",{style:{background:"#ffe6e6",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#721c24"},children:["Line ",B.idx+1,": ",s.jsx("strong",{children:B.field})," ",B.current," ","→"," ",B.suggested," — ",B.reason]}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem"},children:[s.jsx("button",{onClick:()=>G1(B.idx,B.field,B.suggested),style:{padding:"0.2rem 0.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Apply"}),s.jsx("button",{onClick:()=>Zr(be=>new Set([...be,`${B.idx}-${B.field}`])),style:{padding:"0.2rem 0.5rem",background:"#6c757d",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Dismiss"})]})]},oe))]}),(sn==null?void 0:sn.subtotal_flags)&&sn.subtotal_flags.length>0&&Yt&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Subtotal / Fee Rows"}),sn.subtotal_flags.map(B=>{var be;const oe=Yt[B];return oe?s.jsxs("div",{style:{background:"#fff3cd",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#856404"},children:["Line ",B+1,': "',(be=oe.description)==null?void 0:be.substring(0,50),'" — appears to be a subtotal or fee, not a product']}),!oe.is_non_stock&&s.jsx("button",{onClick:()=>Jl.mutate({itemId:oe.id,data:{is_non_stock:!0}}),style:{padding:"0.2rem 0.5rem",background:"#f0ad4e",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Mark Non-Stock"})]},B):null})]}),(sn==null?void 0:sn.description_recommendations)&&sn.description_recommendations.length>0&&Yt&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Description Recommendations"}),sn.description_recommendations.filter(B=>B.recommendation!=="keep").map((B,oe)=>{const be=Yt[B.idx];return!be||!be.description_alt?null:s.jsxs("div",{style:{background:"#d1ecf1",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#0c5460"},children:["Line ",B.idx+1,": Swap description recommended — ",B.reason]}),s.jsx("button",{onClick:()=>Jl.mutate({itemId:be.id,data:{description:be.description_alt,description_alt:be.description}}),style:{padding:"0.2rem 0.5rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Swap"})]},oe)})]}),(sn==null?void 0:sn.pack_size_suggestions)&&sn.pack_size_suggestions.length>0&&Yt&&s.jsxs("div",{style:{marginBottom:"0.5rem"},children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Pack Size (from description)"}),sn.pack_size_suggestions.map((B,oe)=>{var en;const be=Yt[B.idx];if(!be)return null;const Ae=B.pack_quantity>1?`${B.pack_quantity} × ${B.unit_size}${B.unit_size_type}`:`${B.unit_size}${B.unit_size_type}`,it=be.pack_quantity&&be.unit_size;return s.jsxs("div",{style:{background:it?"#e8e8e8":"#e8daef",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:it?"#666":"#4a235a"},children:["Line ",B.idx+1,': "',(en=be.description)==null?void 0:en.substring(0,40),'" → ',s.jsx("strong",{children:Ae}),it&&" (already set)"]}),!it&&s.jsx("button",{onClick:()=>Jl.mutate({itemId:be.id,data:{pack_quantity:B.pack_quantity,unit_size:B.unit_size,unit_size_type:B.unit_size_type}}),style:{padding:"0.2rem 0.5rem",background:"#7d3c98",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Apply"})]},oe)})]}),It.length>0&&Yt&&s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"0.85rem",fontWeight:600,color:"#5a32a3",marginBottom:"0.35rem"},children:"Ingredient Matches (from supplier history)"}),It.map((B,oe)=>{var Ae;const be=Yt[B.idx];return be?s.jsxs("div",{style:{background:"#d4edda",padding:"0.4rem 0.75rem",borderRadius:"4px",marginBottom:"0.25rem",display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.85rem"},children:[s.jsxs("span",{style:{color:"#155724"},children:["Line ",B.idx+1,' "',(Ae=be.description)==null?void 0:Ae.substring(0,40),'" ',"→"," ",s.jsx("strong",{children:B.ingredient_name})," (",(B.confidence*100).toFixed(0),"%) — ",B.reason]}),s.jsx("button",{onClick:()=>Jl.mutate({itemId:be.id,data:{ingredient_id:B.ingredient_id}}),style:{padding:"0.2rem 0.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"0.75rem"},children:"Map"})]},oe):null})]})]}),s.jsxs("div",{style:fe.lineItemsSection,children:[s.jsxs("div",{style:{marginBottom:"10px"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"10px"},children:[s.jsx("h3",{style:{margin:"0"},children:"Line Items"}),s.jsx("button",{onClick:()=>{if(He){if(ge!==null&&!window.confirm("You have unsaved changes. Are you sure you want to exit edit mode?"))return;Te(null),he({}),Ge(!1)}else Ge(!0),(!Yt||Yt.length===0)&&$0()},style:{...fe.editBtn,background:He?"#dc3545":"#f0f0f0",color:He?"white":"#333",border:He?"none":"1px solid #ddd",padding:"0.5rem 1rem",fontSize:"0.85rem"},children:He?"✕ Exit Edit Mode":"✏️ Edit Line Items"})]}),Yt&&Yt.length>0&&s.jsxs("div",{style:{display:"flex",gap:"10px",alignItems:"center"},children:[s.jsx("input",{type:"text",placeholder:"Search by code or description...",value:hn,onChange:B=>Ti(B.target.value),style:{flex:1,padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db",fontSize:"0.9rem"}}),s.jsxs("label",{style:{fontSize:"0.9rem",color:"#6b7280"},children:["Price:",s.jsxs("select",{value:tn,onChange:B=>ci(B.target.value),style:{marginLeft:"5px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db"},children:[s.jsx("option",{value:"",children:"All"}),s.jsx("option",{value:"consistent",disabled:Nc.consistent===0,children:"✓ Consistent"}),s.jsx("option",{value:"amber",disabled:Nc.amber===0,children:"? Changed"}),s.jsx("option",{value:"red",disabled:Nc.red===0,children:"! Large change"}),s.jsx("option",{value:"no_history",disabled:Nc.no_history===0,children:"No history"})]})]}),s.jsxs("label",{style:{fontSize:"0.9rem",color:"#6b7280"},children:["Portions:",s.jsxs("select",{value:js,onChange:B=>Ar(B.target.value),style:{marginLeft:"5px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db"},children:[s.jsx("option",{value:"",children:"All"}),s.jsx("option",{value:"yes",disabled:Nc.withPortions===0,children:"📦 Yes"}),s.jsx("option",{value:"no",disabled:Nc.withoutPortions===0,children:"○ No"})]})]}),s.jsxs("label",{style:{fontSize:"0.9rem",color:"#6b7280"},children:["Data:",s.jsxs("select",{value:fs,onChange:B=>Qs(B.target.value),style:{marginLeft:"5px",padding:"4px 8px",borderRadius:"4px",border:"1px solid #d1d5db"},children:[s.jsx("option",{value:"",children:"All"}),s.jsx("option",{value:"missing",disabled:Nc.missingData===0,children:"⚠ Missing key data"})]})]}),(gi||tn||hn||js||fs)&&s.jsx("button",{onClick:()=>{je(""),ci(""),Ti(""),Ar(""),Qs("")},style:{padding:"4px 10px",fontSize:"0.85rem",color:"#6b7280",background:"#f3f4f6",border:"1px solid #d1d5db",borderRadius:"4px",cursor:"pointer"},children:"Clear"})]})]}),Yt&&Yt.length>0||He?s.jsx("div",{style:fe.lineItemsTableContainer,ref:Pa,children:s.jsxs("table",{style:fe.lineItemsTable,children:[s.jsxs("thead",{style:fe.stickyThead,children:[s.jsxs("tr",{children:[s.jsx("th",{style:{...fe.th,width:"30px"}}),s.jsxs("th",{style:{...fe.th,width:"80px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("code"),children:["Code ",gi==="code"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,minWidth:"240px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("description"),children:["Description ",gi==="description"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,width:"50px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("unit"),children:["Unit ",gi==="unit"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,width:"50px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("quantity"),children:["Qty ",gi==="quantity"&&(bt==="asc"?"↑":"↓")]}),s.jsxs("th",{style:{...fe.th,width:"110px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("unit_price"),children:["Price ",gi==="unit_price"&&(bt==="asc"?"↑":"↓")]}),s.jsx("th",{style:{...fe.th,width:"50px"},children:"Tax"}),s.jsxs("th",{style:{...fe.th,width:"70px",cursor:"pointer",userSelect:"none"},onClick:()=>Xu("amount"),children:["Total ",gi==="amount"&&(bt==="asc"?"↑":"↓")]}),s.jsx("th",{style:{...fe.th,textAlign:"center",width:"60px",cursor:"pointer",userSelect:"none"},onClick:()=>J(!0),title:"Click to mark all items as stock or non-stock",children:"Stock"}),s.jsx("th",{style:{...fe.th,textAlign:"center",width:"40px"},title:"Cost Breakdown"}),s.jsx("th",{style:{...fe.th,width:"70px"}})]}),_e&&_e.total_pages&&_e.total_pages>1&&!gi&&!hn&&!tn&&!js&&!fs&&s.jsx("tr",{children:s.jsxs("th",{colSpan:11,style:fe.stickyPageIndicatorCell,children:["Page ",Lo," of ",_e.total_pages]})})]}),s.jsxs("tbody",{children:[[...tx,...ge===-1?[{id:-1,product_code:Be.product_code||"",description:Be.description||"",description_alt:null,unit:Be.unit||"",quantity:Be.quantity??null,order_quantity:null,unit_price:Be.unit_price??null,tax_rate:Be.tax_rate||"",tax_amount:null,amount:Be.amount??null,line_number:Be.line_number||0,is_non_stock:Be.is_non_stock||!1,raw_content:null,pack_quantity:null,unit_size:null,unit_size_type:null,portions_per_unit:null,cost_per_item:null,cost_per_portion:null,ocr_warnings:null,price_change_status:null,price_change_percent:null,previous_price:null,future_price:null,future_change_percent:null,page_number:null,_originalIndex:-1}]:[]].map((B,oe,be)=>{var nw,rw,iw,sw,ow,aw,rx;const Ae=F1(B._originalIndex),it=(ui==null?void 0:ui.high_quantity_threshold)??100,en=B.quantity!==null&&B.quantity>it,rn=Vu==null?void 0:Vu[B.id.toString()],Nn=(rn==null?void 0:rn.has_history)&&rn.previously_non_stock&&!B.is_non_stock,Qn=B.quantity!=null&&B.quantity!==0,gr=B.unit_price!=null&&B.unit_price!==0,br=B.amount!=null&&B.amount!==0,mr=(B.quantity||0)*(B.unit_price||0),Wi=B.amount||0,er=Math.abs(mr-Wi)>.02,lr=gr&&(!Qn||!br)||br&&(!Qn||!gr)||Qn&&gr&&br&&er,Kt=(nw=_e.disputed_line_item_ids)==null?void 0:nw.includes(B.id),Fn=_e&&_e.total_pages&&_e.total_pages>1&&!gi&&!hn&&!tn&&!js&&!fs&&B.page_number&&oefC(B.id,B._originalIndex),style:{...fe.eyeBtn,padding:"0.25rem 0.4rem",fontSize:"0.8rem",...de===B.id?fe.eyeBtnActive:{}},title:"Show on document",children:"👁"})}),ge===B.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.product_code||"":B.product_code||"",onChange:vr=>{ed(B),he({...Be,product_code:vr.target.value})},style:{...fe.tableInput,width:"70px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.description||"":B.description||"",onChange:vr=>{ed(B),he({...Be,description:vr.target.value})},style:fe.tableInput})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.unit||"":B.unit||"",onChange:vr=>{ed(B),he({...Be,unit:vr.target.value})},style:{...fe.tableInput,width:"50px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"number",step:"0.01",value:ge===B.id?Be.quantity??"":B.quantity??"",onChange:vr=>{ed(B),he({...Be,quantity:parseFloat(vr.target.value)})},style:{...fe.tableInput,width:"50px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"number",step:"0.01",value:ge===B.id?Be.unit_price??"":B.unit_price??"",onChange:vr=>{ed(B),he({...Be,unit_price:parseFloat(vr.target.value)})},style:{...fe.tableInput,width:"70px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"text",value:ge===B.id?Be.tax_rate||"":B.tax_rate||"",onChange:vr=>{ed(B),he({...Be,tax_rate:vr.target.value})},style:{...fe.tableInput,width:"50px"}})}),s.jsx("td",{style:fe.td,children:s.jsx("input",{type:"number",step:"0.01",value:ge===B.id?Be.amount??"":B.amount??"",onChange:vr=>{ed(B),he({...Be,amount:parseFloat(vr.target.value)})},style:{...fe.tableInput,width:"60px"}})}),s.jsx("td",{style:{...fe.td,textAlign:"center"},children:s.jsx("input",{type:"checkbox",checked:ge===B.id?!Be.is_non_stock:!B.is_non_stock,onChange:vr=>{ed(B),he({...Be,is_non_stock:!vr.target.checked})},style:{width:"18px",height:"18px",cursor:"pointer"}})}),s.jsx("td",{style:{...fe.td,textAlign:"center"}}),s.jsx("td",{style:fe.td,children:s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("button",{onClick:()=>_C(B.id),style:{padding:"0.35rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem",display:"flex",alignItems:"center",justifyContent:"center",minWidth:"32px",height:"32px"},title:"Save changes",children:"✅"}),s.jsx("button",{onClick:CC,style:{padding:"0.35rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem",display:"flex",alignItems:"center",justifyContent:"center",minWidth:"32px",height:"32px"},title:"Cancel editing",children:"❌"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsx("td",{style:{...fe.td,fontSize:"0.85rem",color:"#666"},children:s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"4px"},children:[s.jsx("span",{style:B.ocr_warnings?{background:"#fff3cd",padding:"2px 6px",borderRadius:"3px",border:"1px solid #ffc107"}:void 0,children:B.product_code||"—"}),B.ocr_warnings&&s.jsx("span",{title:B.ocr_warnings,style:{cursor:"help",fontSize:"1rem"},children:"⚠️"})]})}),s.jsxs("td",{style:{...fe.td,...B.is_non_stock?{color:"#856404",fontStyle:"italic"}:{}},children:[s.jsxs("div",{children:[ffe(B.description)||"—",B.description_alt&&B.description!==B.description_alt&&s.jsx("button",{onClick:vr=>{vr.stopPropagation(),we(B)},style:{background:"none",border:"none",cursor:"pointer",padding:"2px 6px",fontSize:"0.9rem",color:"#e94560",marginLeft:"6px"},title:"OCR detected alternative description - click to compare",children:"🔄"}),((iw=_e.disputed_line_item_ids)==null?void 0:iw.includes(B.id))&&s.jsx("span",{style:{marginLeft:"8px",color:"#e94560",fontSize:"0.7rem",fontWeight:"bold",padding:"2px 6px",background:"#ffe0e6",borderRadius:"3px"},children:"[DISPUTED]"})]}),Nn&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#856404",fontStyle:"italic",marginTop:"4px",lineHeight:"1.2"},children:"⚠️ This item has previously been marked as not a stock item"}),lr&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#dc3545",fontWeight:"bold",marginTop:"4px",lineHeight:"1.3"},children:["! QTY x Price = Total Check Failed",s.jsx("br",{}),(sw=B.quantity)==null?void 0:sw.toFixed(2)," × £",(ow=B.unit_price)==null?void 0:ow.toFixed(2)," ≠ £",(aw=B.amount)==null?void 0:aw.toFixed(2)]}),!B.ingredient_id&&!B.product_code&&B.description&&(()=>{const vr=B.description.split(` -`)[0].trim().toLowerCase(),Gr=Qe[vr];if(!Gr)return null;const Ho=kt===vr;return s.jsxs("div",{style:{fontSize:"0.75rem",color:"#0c5460",background:"#d1ecf1",padding:"0.25rem 0.5rem",borderRadius:"4px",marginTop:"4px",border:"1px solid #bee5eb",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",flexWrap:"wrap"},children:[s.jsxs("span",{children:['Similar to "',Gr.canonical_description,'"',Gr.ingredient_name&&s.jsxs(s.Fragment,{children:[" → ",Gr.ingredient_name]})," ","(",Math.round(Gr.similarity*100),"% match)",Gr.price_difference!=null&&Gr.price_difference>5&&s.jsxs("span",{style:{color:"#856404",marginLeft:"6px"},children:["Price differs ",Gr.price_difference.toFixed(0),"%"]})]}),s.jsx("button",{type:"button",onClick:Qu=>{Qu.stopPropagation(),Ht(vr),xC.mutate({sourceId:Gr.source_id,alias:B.description.split(` -`)[0].trim()})},disabled:Ho,style:{padding:"0.2rem 0.5rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"4px",cursor:Ho?"default":"pointer",fontSize:"0.7rem",fontWeight:"500",whiteSpace:"nowrap",opacity:Ho?.6:1},children:Ho?"Adding...":"+ Add as alias"})]})})()]}),s.jsx("td",{style:{...fe.td,fontSize:"0.85rem"},children:B.unit||"—"}),s.jsx("td",{style:{...fe.td,...Uo},children:((rx=B.quantity)==null?void 0:rx.toFixed(2))||"—"}),s.jsxs("td",{style:{...fe.td,...da,position:"relative"},children:[s.jsxs("div",{style:{display:"inline-block",verticalAlign:"middle",whiteSpace:"nowrap"},children:[B.unit_price!=null?`£${B.unit_price.toFixed(2)}`:"—",B.price_change_status==="consistent"&&s.jsx("span",{style:{marginLeft:"6px",color:"#22c55e",fontWeight:"bold"},children:"✓"}),B.price_change_status==="no_history"&&s.jsx("span",{style:{marginLeft:"6px",color:"#22c55e"},children:"📄⁺"}),B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_status!=="consistent"&&s.jsx("span",{style:{marginLeft:"6px",color:"#f59e0b"},children:"🪙"})]}),B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_status!=="consistent"&&B.price_change_percent!==null&&B.price_change_percent!==0&&(()=>{const vr=B.price_change_percent>0,Gr=vr?"▲":"▼",Ho=vr?"#ef4444":"#22c55e";return s.jsxs("div",{onClick:()=>Z0(B),style:{position:"absolute",bottom:"0.2rem",left:"0.5rem",fontSize:"0.65rem",lineHeight:"1",color:Ho,cursor:"pointer"},title:"View price history",children:[s.jsx("span",{style:{fontWeight:"bold"},children:Gr})," ",Math.abs(B.price_change_percent).toFixed(1),"%"]})})(),B.future_change_percent!==null&&B.future_change_percent!==0&&(()=>{const Gr=B.future_change_percent>0?"▲":"▼";return s.jsxs("div",{onClick:()=>Z0(B),style:{position:"absolute",bottom:"0.2rem",left:"0.5rem",fontSize:"0.75rem",color:"#9ca3af",cursor:"pointer"},title:"Price changed after this invoice",children:["(",s.jsx("span",{style:{fontWeight:"bold"},children:Gr})," ",Math.abs(B.future_change_percent).toFixed(1),"%)"]})})()]}),s.jsx("td",{style:{...fe.td,fontSize:"0.85rem",...da},children:B.tax_rate||"—"}),s.jsx("td",{style:{...fe.td,...zf},children:B.amount?`£${B.amount.toFixed(2)}`:"—"}),s.jsx("td",{style:{...fe.td,textAlign:"center"},children:s.jsx("input",{type:"checkbox",checked:!B.is_non_stock,onChange:vr=>{Jl.mutate({itemId:B.id,data:{is_non_stock:!vr.target.checked}})},style:{width:"18px",height:"18px",cursor:"pointer"},title:B.is_non_stock?"Mark as stock item":"Mark as non-stock item"})}),s.jsx("td",{style:{...fe.td,textAlign:"center"},children:s.jsx("button",{type:"button",onClick:()=>X1(B),style:{...fe.scaleBtn,...(nn==null?void 0:nn.id)===B.id?fe.scaleBtnActive:{},color:hfe(B)},title:B.ingredient_id?`Mapped → ${B.ingredient_name||"Ingredient"}`:B.pack_quantity?B.portions_per_unit===null?"Pack data extracted - click to map ingredient":"Pack data complete - click to map ingredient":"No pack data - click to map ingredient",children:s.jsx(cfe,{})})}),s.jsx("td",{style:{...fe.td,minWidth:"135px",whiteSpace:"nowrap",verticalAlign:"middle"},children:s.jsx("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:He?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>U1(B),style:fe.iconBtn,title:"Edit line item",children:"✏️"}),s.jsx("button",{onClick:()=>pD(B.id),style:{...fe.iconBtn,color:"#dc3545"},title:"Delete line item",children:"🗑️"})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>TC(B),style:fe.iconBtn,title:"Search similar items",children:"🔍"}),s.jsx("button",{onClick:()=>B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null&&Z0(B),style:{...fe.iconBtn,opacity:B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null?1:.5,cursor:B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null?"pointer":"not-allowed"},title:B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null?"View price history":"No price history available",disabled:!(B.price_change_status&&B.price_change_status!=="no_history"&&B.price_change_percent!==null),children:"📊"})]})})})]})]}),de===B.id&&Ae&&s.jsx("tr",{children:s.jsx("td",{colSpan:11,style:fe.lineItemPreviewCell,children:Yu&&Je.length>0?(()=>{const vr=Ae.pageNumber-1,Gr=Je[vr];if(!Gr)return null;const Ho=Ae.x/100*Gr.width,Qu=Ae.y/100*Gr.height,Of=Ae.width/100*Gr.width,lw=Ae.height/100*Gr.height,$u=15,dw=Math.max(0,Ho-$u),Xg=Math.max(0,Qu-$u),cw=Of+$u*2,uw=lw+$u*2,Yg=5,ix=Math.max(0,dw-Yg),Lf=Math.max(0,Xg-Yg),hw=Math.min(Gr.width,dw+cw+Yg),PC=Math.min(Gr.height,Xg+uw+Yg),Zu=hw-ix,Qg=PC-Lf,fw=dw-ix,gD=Xg-Lf,Nf=document.createElement("canvas");Nf.width=Zu,Nf.height=Qg;const pw=Nf.getContext("2d");return pw&&pw.drawImage(Gr.canvas,ix,Lf,Zu,Qg,0,0,Zu,Qg),s.jsx("div",{style:fe.lineItemPreviewContainer,children:s.jsxs("div",{style:{position:"relative",display:"block",width:"100%"},children:[s.jsx("img",{src:Nf.toDataURL(),alt:"Line item from invoice",style:{width:"100%",height:"auto",display:"block"}}),s.jsx("div",{style:{position:"absolute",left:`${fw/Zu*100}%`,top:`${gD/Qg*100}%`,width:`${cw/Zu*100}%`,height:`${uw/Qg*100}%`,border:"2px solid #ffc107",borderRadius:"2px",pointerEvents:"none",boxShadow:"0 0 8px rgba(255, 193, 7, 0.5)"}})]})})})():Mf?(()=>{const Gr=Math.max(0,Ae.x-2),Ho=Math.max(0,Ae.y-2),Qu=Math.min(100-Gr,Ae.width+2*2),Of=Math.min(100-Ho,Ae.height+2*2);return s.jsx("div",{style:fe.lineItemPreviewContainer,children:s.jsxs("div",{style:{position:"relative",display:"block",width:"100%"},children:[s.jsx("img",{src:`${Mf.split("?")[0]}?token=${encodeURIComponent(e||"")}`,alt:"Line item location",style:{width:"100%",height:"auto",display:"block"}}),s.jsx("div",{style:{position:"absolute",left:`${Gr}%`,top:`${Ho}%`,width:`${Qu}%`,height:`${Of}%`,border:"2px solid #ffc107",borderRadius:"2px",pointerEvents:"none",boxShadow:"0 0 8px rgba(255, 193, 7, 0.5)"}})]})})})():null})})]},B.id)}),He&&s.jsx("tr",{children:s.jsx("td",{colSpan:11,style:{textAlign:"center",padding:"1.5rem",background:"#f9fafb"},children:s.jsx("button",{onClick:$0,style:{...fe.confirmBtn,padding:"0.75rem 2rem",fontSize:"0.95rem"},children:"+ Add Line Item"})})})]})]})}):s.jsx("p",{style:fe.noItems,children:"No line items extracted"}),s.jsx(gfe,{lineItems:Yt||[],invoiceTotal:parseFloat(c)||0,netTotal:f?parseFloat(f):null})]}),b&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>C(!1),children:s.jsxs("div",{style:fe.modal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Delete Invoice?"}),s.jsxs("div",{style:fe.modalInfo,children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",_e.invoice_number||"N/A"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",_e.invoice_date||"N/A"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",_e.total?`£${Number(_e.total).toFixed(2)}`:"N/A"]})]}),_e.duplicate_status&&s.jsxs("div",{style:fe.modalDuplicateInfo,children:["This invoice is marked as a ",_e.duplicate_status==="firm_duplicate"?"duplicate":"possible duplicate",". Deleting it will resolve the duplicate warning."]}),s.jsxs("div",{style:fe.modalActions,children:[s.jsx("button",{onClick:()=>C(!1),style:fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:wC,style:fe.confirmDeleteBtn,children:"Delete"})]})]})}),Ci&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>Lr(!1),children:s.jsxs("div",{style:fe.modal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Send Invoice to Dext?"}),s.jsx("p",{style:{marginBottom:"1rem"},children:"This will email the invoice PDF to your configured Dext address."}),Cr&&s.jsxs("p",{style:{fontSize:"0.9rem",color:"#666"},children:[s.jsx("strong",{children:"Note:"})," Invoice notes will be included in the email."]}),Yt&&Yt.some(B=>B.is_non_stock)&&s.jsxs("p",{style:{fontSize:"0.9rem",color:"#666"},children:[s.jsx("strong",{children:"Note:"})," Non-stock items table will be included in the email."]}),s.jsxs("div",{style:fe.modalActions,children:[s.jsx("button",{onClick:()=>Lr(!1),style:fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:async()=>{try{const B=await fetch(`/api/invoices/${n}/send-to-dext`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(B.ok){const oe=await B.json();alert(`Invoice sent to Dext successfully at ${new Date(oe.sent_at).toLocaleString()}`),Lr(!1),i.invalidateQueries({queryKey:["invoice",n]})}else{const oe=await B.json();alert(`Failed to send: ${oe.detail}`)}}catch(B){console.error("Failed to send to Dext:",B),alert("Failed to send invoice to Dext")}},style:fe.confirmBtn,children:"Send to Dext"})]})]})}),T&&Li&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>F(!1),children:s.jsxs("div",{style:fe.wideModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Duplicate Comparison"}),s.jsxs("div",{style:fe.compareGrid,children:[s.jsxs("div",{style:fe.compareCard,children:[s.jsx("h4",{children:"Current Invoice"}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",Li.current_invoice.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",Li.current_invoice.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",Li.current_invoice.total?`£${Number(Li.current_invoice.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",Li.current_invoice.order_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Type:"})," ",Li.current_invoice.document_type||"invoice"]})]}),Li.firm_duplicate&&s.jsxs("div",{style:{...fe.compareCard,borderColor:"#dc3545"},children:[s.jsx("h4",{style:{color:"#dc3545"},children:"Exact Duplicate"}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",Li.firm_duplicate.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",Li.firm_duplicate.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",Li.firm_duplicate.total?`£${Number(Li.firm_duplicate.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",Li.firm_duplicate.order_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Type:"})," ",Li.firm_duplicate.document_type||"invoice"]}),s.jsx("button",{onClick:()=>r(`/invoice/${Li.firm_duplicate.id}`),style:fe.viewBtn,children:"View This Invoice"})]}),Li.possible_duplicates.map(B=>s.jsxs("div",{style:{...fe.compareCard,borderColor:"#ffc107"},children:[s.jsx("h4",{style:{color:"#856404"},children:"Possible Duplicate"}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",B.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",B.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",B.total?`£${Number(B.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",B.order_number||"—"]}),s.jsx("button",{onClick:()=>r(`/invoice/${B.id}`),style:fe.viewBtn,children:"View This Invoice"})]},B.id)),Li.related_documents.map(B=>s.jsxs("div",{style:{...fe.compareCard,borderColor:"#17a2b8"},children:[s.jsxs("h4",{style:{color:"#17a2b8"},children:["Related ",B.document_type==="delivery_note"?"Delivery Note":"Invoice"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Invoice #:"})," ",B.invoice_number||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Date:"})," ",B.invoice_date||"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total:"})," ",B.total?`£${Number(B.total).toFixed(2)}`:"—"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Order #:"})," ",B.order_number||"—"]}),s.jsx("button",{onClick:()=>r(`/invoice/${B.id}`),style:fe.viewBtn,children:"View This Invoice"})]},B.id))]}),s.jsx("button",{onClick:()=>F(!1),style:fe.closeBtn,children:"Close"})]})}),A&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>D(!1),children:s.jsxs("div",{style:fe.modal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Create New Supplier"}),s.jsxs("label",{style:fe.modalLabel,children:["Supplier Name",s.jsx("input",{type:"text",value:ee,onChange:B=>Z(B.target.value),style:fe.input,placeholder:"e.g., Sysco, US Foods",autoFocus:!0})]}),s.jsxs("div",{style:fe.modalActions,children:[s.jsx("button",{onClick:()=>D(!1),style:fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:B1,style:fe.saveBtn,disabled:!ee.trim()||X0.isPending,children:X0.isPending?"Creating...":"Create & Select"})]})]})}),z&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>G(!1),children:s.jsxs("div",{style:fe.rawOcrModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Raw Azure OCR Data"}),s.jsx("p",{style:fe.rawOcrHint,children:"This shows the raw data extracted by Azure. Use this to debug field extraction issues or identify custom field names that need mapping."}),ks!=null&&ks.raw_json?s.jsxs("div",{style:fe.rawOcrContent,children:[s.jsx("h4",{children:"Extracted Fields"}),(J1=ks.raw_json.documents)==null?void 0:J1.map((B,oe)=>s.jsxs("div",{style:fe.rawOcrDoc,children:[s.jsxs("h5",{children:["Document ",oe+1," (Confidence: ",(B.confidence*100).toFixed(1),"%)"]}),s.jsxs("table",{style:fe.rawOcrTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:fe.rawOcrTh,children:"Field"}),s.jsx("th",{style:fe.rawOcrTh,children:"Value"}),s.jsx("th",{style:fe.rawOcrTh,children:"Content"})]})}),s.jsx("tbody",{children:Object.entries(B.fields||{}).map(([be,Ae])=>s.jsxs("tr",{children:[s.jsx("td",{style:fe.rawOcrTd,children:s.jsx("strong",{children:be})}),s.jsx("td",{style:fe.rawOcrTd,children:typeof(Ae==null?void 0:Ae.value)=="object"?JSON.stringify(Ae==null?void 0:Ae.value,null,2):String((Ae==null?void 0:Ae.value)??"—")}),s.jsx("td",{style:fe.rawOcrTd,children:(Ae==null?void 0:Ae.content)||"—"})]},be))})]})]},oe))]}):s.jsx("p",{style:{color:"#999"},children:"No raw OCR data available for this invoice."}),s.jsx("button",{onClick:()=>G(!1),style:fe.closeBtn,children:"Close"})]})}),Vd&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>Gn(!1),children:s.jsxs("div",{style:{...fe.rawOcrModal,maxWidth:"480px"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{style:{marginTop:0,marginBottom:"0.75rem"},children:"Previously Non-Stock Items"}),s.jsxs("p",{style:{fontSize:"0.9rem",color:"#555",marginBottom:"1rem",lineHeight:1.5},children:["The following item",Dr.length!==1?"s have":" has"," been marked as ",s.jsx("strong",{children:"non-stock"})," on previous invoices from this supplier but ",Dr.length!==1?"are":"is"," currently included in the stock cost for this invoice. Please confirm they have been checked."]}),s.jsx("div",{style:{marginBottom:"1.25rem",borderRadius:"6px",border:"1px solid #f0c36d",background:"#fffbf0",overflow:"hidden"},children:Dr.map((B,oe)=>{var be;return s.jsxs("div",{style:{padding:"0.6rem 0.85rem",borderBottom:oeGn(!1),style:{...fe.closeBtn,margin:0},children:"Go back"}),s.jsx("button",{onClick:async()=>{Gn(!1),await z1()},style:{padding:"0.5rem 1.25rem",background:"#e85d04",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},children:"Confirm anyway"})]})]})}),Ks&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>un(!1),children:s.jsxs("div",{style:{...fe.rawOcrModal,maxWidth:"520px"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Select Invoice Date"}),(()=>{var be;const B=la("InvoiceDate");if(!B)return null;if(((be=_e==null?void 0:_e.image_path)==null?void 0:be.toLowerCase().endsWith(".pdf"))&&Je.length>0){const Ae=Je[B.pageNumber-1];if(!Ae)return null;const it=B.x/100*Ae.width,en=B.y/100*Ae.height,rn=B.width/100*Ae.width,Nn=B.height/100*Ae.height,Qn=20,gr=Math.max(0,it-Qn*3),br=Math.max(0,en-Qn),mr=Math.min(Ae.width,it+rn+Qn*3),Wi=Math.min(Ae.height,en+Nn+Qn),er=mr-gr,lr=Wi-br,Kt=document.createElement("canvas");Kt.width=er,Kt.height=lr;const Fn=Kt.getContext("2d");return Fn&&(Fn.drawImage(Ae.canvas,gr,br,er,lr,0,0,er,lr),Fn.strokeStyle="#e85d04",Fn.lineWidth=3,Fn.strokeRect(it-gr-4,en-br-4,rn+8,Nn+8)),s.jsxs("div",{style:{marginBottom:"1rem",border:"1px solid #ddd",borderRadius:"6px",overflow:"hidden"},children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#666",padding:"4px 8px",background:"#f8f9fa",borderBottom:"1px solid #ddd"},children:"Date field from document"}),s.jsx("img",{src:Kt.toDataURL(),alt:"Date field from invoice",style:{width:"100%",height:"auto",display:"block"}})]})}return null})(),l&&bx(l,"PENDING")==="future"&&(()=>{const B=new Date;B.setHours(0,0,0,0);const oe=NN(l),be=oe&&new Date(oe)<=B,Ae=WN(l);if(!be&&!Ae)return null;const it=[];return Ae&&it.push({date:Ae.date,label:new Date(Ae.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"}),sublabel:`Year corrected from ${l.split("-")[0]} → ${Ae.year}`}),be&&oe&&it.push({date:oe,label:new Date(oe).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"}),sublabel:`Day and month swapped from ${new Date(l).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}`}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{fontSize:"0.8rem",fontWeight:600,color:"#e85d04",marginBottom:"0.5rem"},children:["⚠ Suggested fix",it.length>1?"es":""," — date is in the future:"]}),it.map((en,rn)=>s.jsxs("div",{onClick:()=>Q0(en.date),style:{padding:"0.75rem 1rem",border:"2px solid #e85d04",borderRadius:"4px",cursor:"pointer",background:"#fff8f5",transition:"all 0.2s",marginBottom:rn{Nn.currentTarget.style.background="#fff0e8"},onMouseLeave:Nn=>{Nn.currentTarget.style.background="#fff8f5"},children:[s.jsx("div",{style:{fontWeight:"600",fontSize:"1.1rem",marginBottom:"0.25rem"},children:en.label}),s.jsx("div",{style:{fontSize:"0.8rem",color:"#888"},children:en.sublabel})]},rn)),Fr.length>0&&s.jsx("div",{style:{borderTop:"1px solid #eee",marginTop:"1rem",paddingTop:"0.75rem",fontSize:"0.8rem",color:"#666",marginBottom:"0.5rem"},children:"Or choose a date found in the document:"})]})})(),!l&&s.jsx("p",{style:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},children:"Dates found in the document. Click to select."}),l&&bx(l,"PENDING")!=="future"&&s.jsx("p",{style:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},children:"Dates found in the document. Click to select."}),aa?s.jsx("p",{style:{color:"#999",textAlign:"center",padding:"2rem"},children:"Searching for dates..."}):Fr.length===0?l&&bx(l,"PENDING")==="future"?null:s.jsx("p",{style:{color:"#999",textAlign:"center",padding:"2rem"},children:"No dates found in document text."}):s.jsx("div",{style:{maxHeight:"400px",overflowY:"auto"},children:Fr.filter(B=>{if(!l||bx(l,"PENDING")!=="future")return!0;const oe=new Date;oe.setHours(0,0,0,0);const be=NN(l);if(be&&new Date(be)<=oe&&B.date===be)return!1;const Ae=WN(l);return!(Ae&&B.date===Ae.date)}).map((B,oe)=>{const be=B.bbox?D1(B.bbox,{padX:80,padY:25,strokeColor:"#e85d04"}):null;return s.jsxs("div",{onClick:()=>Q0(B.date),style:{marginBottom:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",transition:"all 0.2s",background:"#fff",overflow:"hidden"},onMouseEnter:Ae=>{Ae.currentTarget.style.background="#f0f7ff",Ae.currentTarget.style.borderColor="#007bff"},onMouseLeave:Ae=>{Ae.currentTarget.style.background="#fff",Ae.currentTarget.style.borderColor="#ddd"},children:[be&&s.jsx("img",{src:be,alt:"Date location in document",style:{width:"100%",height:"auto",display:"block",borderBottom:"1px solid #eee"}}),s.jsxs("div",{style:{padding:"0.75rem 1rem"},children:[s.jsx("div",{style:{fontWeight:"600",fontSize:"1.1rem",marginBottom:"0.25rem"},children:new Date(B.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"})}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666"},children:["Original: ",B.original]}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#999",marginTop:"0.25rem",fontStyle:"italic"},children:["...",B.context,"..."]})]})]},oe)})}),s.jsx("button",{onClick:()=>un(!1),style:fe.closeBtn,children:"Cancel"})]})}),Ss&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>rs(!1),children:s.jsxs("div",{style:{...fe.rawOcrModal,maxWidth:"520px"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Find Invoice Number"}),(()=>{var be;const B=la("InvoiceId");if(!B)return null;if(((be=_e==null?void 0:_e.image_path)==null?void 0:be.toLowerCase().endsWith(".pdf"))&&Je.length>0){const Ae=Je[B.pageNumber-1];if(!Ae)return null;const it=B.x/100*Ae.width,en=B.y/100*Ae.height,rn=B.width/100*Ae.width,Nn=B.height/100*Ae.height,Qn=20,gr=Math.max(0,it-Qn*3),br=Math.max(0,en-Qn),mr=Math.min(Ae.width,it+rn+Qn*3),Wi=Math.min(Ae.height,en+Nn+Qn),er=mr-gr,lr=Wi-br,Kt=document.createElement("canvas");Kt.width=er,Kt.height=lr;const Fn=Kt.getContext("2d");return Fn&&(Fn.drawImage(Ae.canvas,gr,br,er,lr,0,0,er,lr),Fn.strokeStyle="#007bff",Fn.lineWidth=3,Fn.strokeRect(it-gr-4,en-br-4,rn+8,Nn+8)),s.jsxs("div",{style:{marginBottom:"1rem",border:"1px solid #ddd",borderRadius:"6px",overflow:"hidden"},children:[s.jsx("div",{style:{fontSize:"0.75rem",color:"#666",padding:"4px 8px",background:"#f8f9fa",borderBottom:"1px solid #ddd"},children:"Invoice number field from document"}),s.jsx("img",{src:Kt.toDataURL(),alt:"Invoice number field",style:{width:"100%",height:"auto",display:"block"}})]})}return null})(),Ys.length>0&&s.jsxs("div",{style:{marginBottom:"1rem",padding:"0.5rem 0.75rem",background:"#f8f9fa",borderRadius:"4px",fontSize:"0.8rem",color:"#555"},children:[s.jsx("strong",{children:"Format from this supplier:"})," ",Ys.slice(0,4).join(", ")]}),s.jsx("p",{style:{color:"#666",marginBottom:"1rem",fontSize:"0.9rem"},children:Ea?"Searching document...":Xs.length===0?"No candidates found in document text.":"Candidates found in the document. Click to use."}),Ea?s.jsx("p",{style:{color:"#999",textAlign:"center",padding:"2rem"},children:"Searching for invoice number..."}):Xs.length===0?null:s.jsx("div",{style:{maxHeight:"400px",overflowY:"auto"},children:Xs.map((B,oe)=>{const be=B.bbox?D1(B.bbox,{padX:80,padY:25,strokeColor:"#007bff"}):null;return s.jsxs("div",{onClick:()=>N1(B.value),style:{marginBottom:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",background:"#fff",transition:"all 0.2s",overflow:"hidden"},onMouseEnter:Ae=>{Ae.currentTarget.style.background="#f0f7ff",Ae.currentTarget.style.borderColor="#007bff"},onMouseLeave:Ae=>{Ae.currentTarget.style.background="#fff",Ae.currentTarget.style.borderColor="#ddd"},children:[be&&s.jsx("img",{src:be,alt:"Candidate location in document",style:{width:"100%",height:"auto",display:"block",borderBottom:"1px solid #eee"}}),s.jsxs("div",{style:{padding:"0.75rem 1rem"},children:[s.jsx("div",{style:{fontWeight:"600",fontSize:"1.05rem",marginBottom:"0.25rem",fontFamily:"monospace"},children:B.value}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#999",marginBottom:"0.2rem"},children:B.source==="ocr_field"?"📋 Azure OCR field":B.source==="supplier_pattern"?"🔗 Matches supplier format":"🔤 Found near reference keyword"}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#888",fontStyle:"italic"},children:["...",B.context,"..."]})]})]},oe)})}),s.jsx("button",{onClick:()=>rs(!1),style:fe.closeBtn,children:"Cancel"})]})}),te&&ne&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>re(!1),children:s.jsxs("div",{style:fe.searchModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{children:"Compare Similar Items"}),s.jsxs("div",{style:fe.currentItemSection,children:[s.jsxs("h4",{style:fe.currentItemHeader,children:["Current Item (",((ew=Yd==null?void 0:Yd.find(B=>B.id===(_e==null?void 0:_e.supplier_id)))==null?void 0:ew.name)||"Unknown Supplier",")"]}),s.jsxs("table",{style:fe.searchResultsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:fe.searchTh,children:"Description"}),s.jsx("th",{style:fe.searchThRight,children:"Unit Price"}),s.jsx("th",{style:fe.searchTh,children:"Unit"}),s.jsx("th",{style:fe.searchTh,children:"Pack Info"}),s.jsx("th",{style:fe.searchTh,children:"Invoice Date"})]})}),s.jsx("tbody",{children:s.jsxs("tr",{style:fe.currentItemRow,children:[s.jsx("td",{style:fe.searchTd,children:ne.description}),s.jsx("td",{style:fe.searchTdRight,children:ne.unit_price?`£${ne.unit_price.toFixed(2)}`:"—"}),s.jsx("td",{style:fe.searchTd,children:ne.unit||"—"}),s.jsx("td",{style:fe.searchTd,children:ne.pack_quantity&&ne.unit_size&&ne.unit_size_type?`${ne.pack_quantity}x${ne.unit_size}${ne.unit_size_type}`:ne.pack_quantity?`${ne.pack_quantity} pack`:"—"}),s.jsx("td",{style:fe.searchTd,children:(_e==null?void 0:_e.invoice_date)||"—"})]})})]})]}),s.jsxs("div",{style:fe.searchInputRow,children:[s.jsx("input",{type:"text",value:ke,onChange:B=>Ye(B.target.value),onKeyDown:B=>B.key==="Enter"&&J0(ke),style:fe.searchInput,placeholder:"Enter search keywords...",autoFocus:!0}),s.jsx("button",{onClick:()=>J0(ke),style:fe.searchButton,disabled:ue,children:ue?"Searching...":"Search"})]}),De&&s.jsxs("div",{style:fe.searchResultsContainer,children:[s.jsxs("p",{style:fe.resultsInfo,children:["Found ",De.total_matches," matches",De.extracted_keywords&&s.jsxs("span",{style:{color:"#666"},children:[' (searched: "',De.extracted_keywords,'")']})]}),De.results.length===0?s.jsx("p",{style:{color:"#999",fontStyle:"italic"},children:"No matching items found."}):De.results.map(B=>s.jsxs("div",{style:fe.supplierGroup,children:[s.jsx("h4",{style:fe.supplierHeader,children:B.supplier_name}),s.jsxs("table",{style:fe.searchResultsTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:fe.searchTh,children:"Description"}),s.jsx("th",{style:fe.searchThRight,children:"Unit Price"}),s.jsx("th",{style:fe.searchTh,children:"Unit"}),s.jsx("th",{style:fe.searchTh,children:"Pack Info"}),s.jsx("th",{style:fe.searchTh,children:"Last Invoice"}),s.jsx("th",{style:fe.searchTh})]})}),s.jsx("tbody",{children:B.items.map((oe,be)=>s.jsxs("tr",{children:[s.jsx("td",{style:fe.searchTd,children:oe.description}),s.jsx("td",{style:fe.searchTdRight,children:oe.unit_price!=null?`£${oe.unit_price.toFixed(2)}`:"—"}),s.jsx("td",{style:fe.searchTd,children:oe.unit||"—"}),s.jsx("td",{style:fe.searchTd,children:oe.pack_info||"—"}),s.jsx("td",{style:fe.searchTd,children:oe.last_invoice_date||"—"}),s.jsx("td",{style:fe.searchTd,children:s.jsx("a",{href:`/invoice/${oe.invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:fe.invoiceLink,title:"Open invoice in new tab",children:"View"})})]},be))})]})]},B.supplier_id||"unknown"))]}),s.jsx("button",{onClick:()=>re(!1),style:fe.closeBtn,children:"Close"})]})}),me&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>J(!1),children:s.jsxs("div",{style:{...fe.modal,maxWidth:"400px",textAlign:"center"},onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{style:{marginBottom:"1rem"},children:"Bulk Stock Update"}),s.jsx("p",{style:{marginBottom:"1.5rem",color:"#666"},children:"Mark all line items on this invoice as:"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[s.jsx("button",{onClick:()=>ex(!0),style:{...fe.saveBtn,padding:"1rem",background:"#28a745",fontSize:"0.95rem"},children:"Mark All as Stock"}),s.jsx("button",{onClick:()=>ex(!1),style:{...fe.saveBtn,padding:"1rem",background:"#dc3545",fontSize:"0.95rem"},children:"Mark All as Non-Stock"}),s.jsx("button",{onClick:()=>J(!1),style:{...fe.backBtn,padding:"0.75rem",marginTop:"0.5rem"},children:"Cancel"})]})]})}),Ia&&s.jsx(FK,{isOpen:Ia.isOpen,onClose:()=>q0(null),productCode:Ia.productCode,description:Ia.description,unit:Ia.unit,supplierId:Ia.supplierId,supplierName:Ia.supplierName,currentPrice:Ia.currentPrice,sourceInvoiceId:Ia.sourceInvoiceId,sourceLineItemId:Ia.sourceLineItemId,onAcknowledge:()=>{zc()}}),P&&_e&&s.jsx(Xhe,{invoiceId:_e.id,invoiceNumber:_e.invoice_number,supplierId:_e.supplier_id||null,supplierName:_e.supplier_name||null,lineItems:Yt||[],onClose:()=>L(!1),onSuccess:()=>{G0()}}),Gs&&_e&&_e.supplier_id&&s.jsx(tfe,{supplierId:_e.supplier_id,supplierName:_e.supplier_name||null,creditNoteInvoiceId:_e.id,creditNoteNumber:_e.invoice_number,creditNoteAmount:_e.total,onClose:()=>Ai(!1),onSuccess:()=>{Ai(!1),G0()}}),W&&s.jsx(DK,{disputeId:W,onClose:()=>O(null),onUpdate:()=>{G0()}}),pe&&s.jsx("div",{style:fe.modalOverlay,onClick:()=>we(null),children:s.jsxs("div",{style:fe.descSwapModal,onClick:B=>B.stopPropagation(),children:[s.jsx("h3",{style:{marginBottom:"0.5rem"},children:"Choose Description"}),s.jsx("p",{style:fe.modalHint,children:"OCR extracted two different descriptions. Select the correct one:"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem"},children:[s.jsxs("div",{style:fe.descriptionOption,onClick:()=>{we(null)},children:[s.jsx("div",{style:{fontWeight:"bold",marginBottom:"0.5rem",color:"#666"},children:"Current (Value)"}),s.jsx("div",{style:{whiteSpace:"pre-wrap",fontFamily:"monospace",fontSize:"0.85rem"},children:pe.description||"(empty)"})]}),s.jsxs("div",{style:{...fe.descriptionOption,borderColor:"#e94560"},onClick:async()=>{await Jl.mutateAsync({itemId:pe.id,data:{description:pe.description_alt,description_alt:null}}),we(null)},children:[s.jsx("div",{style:{fontWeight:"bold",marginBottom:"0.5rem",color:"#e94560"},children:"Alternative (Content) ✓ Select"}),s.jsx("div",{style:{whiteSpace:"pre-wrap",fontFamily:"monospace",fontSize:"0.85rem"},children:pe.description_alt||"(empty)"})]})]}),s.jsx("button",{onClick:()=>we(null),style:{...fe.backBtn,marginTop:"1rem",padding:"0.75rem"},children:"Cancel"})]})}),s.jsx(TT,{isOpen:A1!==null,onClose:()=>V0(null),onSaved:()=>K0(),poId:A1}),nn&&s.jsx("div",{style:fe.modalOverlay,onClick:dl,children:s.jsxs("div",{style:{...fe.wideModal,maxWidth:"650px"},onClick:B=>B.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsx("h3",{style:{margin:0},children:"Ingredient Mapping"}),s.jsx("button",{onClick:dl,style:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666"},children:"×"})]}),s.jsxs("div",{style:{padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:nn.description||nn.product_code||"Unknown item"}),nn.unit_price&&s.jsxs("span",{style:{marginLeft:"1rem",color:"#666"},children:["£",nn.unit_price.toFixed(2)]}),nn.raw_content&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},children:["Raw: ",nn.raw_content.substring(0,80)]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("label",{style:{fontWeight:"600",fontSize:"0.9rem",display:"block",marginBottom:"0.5rem"},children:["Ingredient ",Zs&&s.jsxs("span",{style:{color:"#28a745",fontWeight:"normal"},children:["(",Xd,")"]})]}),Zs?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"#d4edda",borderRadius:"6px",border:"1px solid #c3e6cb"},children:[s.jsxs("span",{style:{flex:1},children:[Xd," ",s.jsxs("span",{style:{color:"#666",fontSize:"0.85rem"},children:["(",Js,")"]})]}),s.jsx("button",{onClick:()=>{Ra(null),No(""),Ba(""),ze("")},style:{background:"none",border:"none",cursor:"pointer",color:"#666",fontSize:"1.1rem"},children:"×"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{type:"text",value:qu,onChange:B=>{$s(B.target.value),Y1(B.target.value)},placeholder:"Search ingredients...",style:{...fe.input,width:"100%",boxSizing:"border-box"}}),Bc&&s.jsx("span",{style:{position:"absolute",right:"10px",top:"10px",color:"#999"},children:"..."})]}),Gd.length>0&&s.jsx("div",{style:{border:"1px solid #ddd",borderRadius:"0 0 6px 6px",maxHeight:"200px",overflowY:"auto",background:"#fff"},children:Gd.map(B=>s.jsxs("div",{onClick:()=>Q1(B),style:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem",display:"flex",justifyContent:"space-between"},onMouseOver:oe=>oe.currentTarget.style.background="#f0f7ff",onMouseOut:oe=>oe.currentTarget.style.background="#fff",children:[s.jsxs("span",{children:[B.name," ",s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:["(",B.standard_unit,")"]})]}),s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:[B.category_name||""," ",B.similarity?`${(B.similarity*100).toFixed(0)}%`:""]})]},B.id))}),(ui==null?void 0:ui.llm_enabled)&&(ui==null?void 0:ui.anthropic_api_key_set)&&(nn==null?void 0:nn.description)&&!Zs&&s.jsxs("div",{style:{marginTop:"0.5rem"},children:[s.jsx("button",{onClick:()=>q1(nn.description),disabled:Gt,style:{padding:"0.4rem 0.75rem",background:"#7952b3",color:"white",border:"none",borderRadius:"4px",cursor:Gt?"wait":"pointer",fontSize:"0.85rem",opacity:Gt?.7:1},children:Gt?"Matching...":"✨ AI Match"}),ar.length>0&&s.jsx("div",{style:{border:"1px solid #d4c5f9",borderRadius:"6px",marginTop:"0.35rem",maxHeight:"160px",overflowY:"auto",background:"#f8f5ff"},children:ar.map(B=>s.jsxs("div",{onClick:()=>{const oe=Gd.find(be=>be.id===B.id);oe?Q1(oe):(Ra(B.id),No(B.name),Ba("")),Kn([])},style:{padding:"0.4rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #e8e0f7",fontSize:"0.85rem",display:"flex",justifyContent:"space-between"},onMouseOver:oe=>oe.currentTarget.style.background="#ede5ff",onMouseOut:oe=>oe.currentTarget.style.background="#f8f5ff",children:[s.jsxs("span",{children:["✨"," ",B.name]}),s.jsxs("span",{style:{color:"#7952b3",fontSize:"0.8rem"},children:[(B.confidence*100).toFixed(0),"%"]})]},B.id))})]}),s.jsx("button",{onClick:()=>al(!0),style:{marginTop:"0.5rem",padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"+ Create new ingredient"})]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("label",{style:{fontWeight:"600",fontSize:"0.9rem",display:"block",marginBottom:"0.25rem"},children:Zs?`How much ${Xd} is in this line item?`:"Unit size & pricing"}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#888",marginBottom:"0.5rem"},children:[nn==null?void 0:nn.description,nn!=null&&nn.unit_price?` @ £${nn.unit_price.toFixed(2)}`:"",nn!=null&&nn.quantity&&nn.quantity>1?` × ${nn.quantity}`:""]}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem",alignItems:"flex-end"},children:[s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsxs("label",{style:{fontSize:"0.8rem",color:"#666"},children:["Contains",ll&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#7952b3"},children:"analysing..."}),Mc==="ai"&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#7952b3"},title:"Deduced by AI from product knowledge",children:"✨"}),Mc==="regex"&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#28a745"},title:"Parsed from description",children:"auto"}),Mc==="unit_field"&&s.jsx("span",{style:{marginLeft:"4px",fontSize:"0.7rem",color:"#28a745"},title:"Inferred from invoice unit field",children:"auto"})]}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",step:"0.1",value:Q.unit_size||"",onChange:B=>{const oe={...Q,unit_size:parseFloat(B.target.value)||null};X(oe),Ku(void 0,oe)},onFocus:B=>B.target.select(),style:{...fe.costBreakdownInput,width:"70px"},placeholder:"e.g., 2"}),s.jsxs("select",{value:Q.unit_size_type||Js||"",onChange:B=>{const oe={...Q,unit_size_type:B.target.value||null};X(oe),Ku(void 0,oe)},style:{...fe.costBreakdownInput,width:"60px"},children:[s.jsx("option",{value:"",children:"--"}),s.jsx("option",{value:"each",children:"each"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"}),s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"oz",children:"oz"}),s.jsx("option",{value:"cl",children:"cl"})]}),Js&&Q.unit_size_type&&Q.unit_size_type!==Js&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#999"},children:["→ ",Js]})]})]}),s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Pack of"}),s.jsx("input",{type:"number",value:Q.pack_quantity||"",onChange:B=>{const oe={...Q,pack_quantity:parseInt(B.target.value)||null};X(oe),Ku(void 0,oe)},onFocus:B=>B.target.select(),style:{...fe.costBreakdownInput,width:"50px"},placeholder:"1"})]}),s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Line Price"}),s.jsx("span",{style:{...fe.costBreakdownValue,fontSize:"0.9rem"},children:Q.unit_price?`£${Q.unit_price.toFixed(2)}`:"--"})]})]}),$&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.5rem 0.75rem",background:"#e8f5e9",borderRadius:"6px",fontSize:"0.9rem",color:"#2e7d32",fontWeight:"500"},children:$})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("button",{onClick:()=>nt(!ie),style:{background:"none",border:"none",cursor:"pointer",fontSize:"0.85rem",color:"#666",padding:0},children:[ie?"▾":"▸"," Legacy Portioning"]}),ie&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem"},children:[s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Portions/Unit"}),s.jsx("input",{type:"number",value:Q.portions_per_unit??"",onChange:B=>X({...Q,portions_per_unit:B.target.value?parseInt(B.target.value):null}),style:fe.costBreakdownInput,min:"1",placeholder:"--"})]}),s.jsxs("div",{style:{...fe.costBreakdownField,minWidth:"150px"},children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Portion Desc"}),s.jsx("input",{type:"text",value:Ne,onChange:B=>st(B.target.value),style:{...fe.costBreakdownInput,width:"100%"},placeholder:"e.g., 250ml glass"})]}),s.jsxs("div",{style:fe.costBreakdownField,children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666"},children:"Cost/Portion"}),s.jsx("span",{style:{...fe.costBreakdownValue,color:"#28a745",fontWeight:"600",fontSize:"0.9rem"},children:Q.pack_quantity&&Q.unit_price&&Q.portions_per_unit?`£${(Q.unit_price/(Q.pack_quantity*Q.portions_per_unit)).toFixed(4)}`:"--"})]})]})})]}),(nn.product_code||nn.description)&&s.jsxs(s.Fragment,{children:[$e?s.jsx("div",{style:{fontSize:"0.85rem",color:"#666",marginBottom:"0.5rem"},children:"Loading saved default..."}):Le?s.jsx("div",{style:{...fe.savedByInfo,marginBottom:"0.5rem"},children:s.jsxs("span",{style:{fontSize:"0.85rem"},children:["Definition by ",s.jsx("strong",{children:Le.saved_by_username||"Unknown"}),Le.updated_at&&s.jsxs(s.Fragment,{children:[" on ",new Date(Le.updated_at).toLocaleDateString()]})]})}):null,!Zs&&s.jsx("div",{style:{...fe.saveAsDefaultRow,marginBottom:"1rem"},children:s.jsxs("label",{style:fe.saveAsDefaultLabel,children:[s.jsx("input",{type:"checkbox",checked:Ve,onChange:B=>Re(B.target.checked),style:{marginRight:"0.5rem"}}),Le?"Update saved default":`Save as default for "${nn.product_code||((nx=nn.description)==null?void 0:nx.substring(0,30))}"`]})})]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:dl,style:{...fe.smallBtnCancel,padding:"0.5rem 1.25rem"},children:"Cancel"}),s.jsx("button",{onClick:()=>DC(nn.id),style:{...fe.smallBtn,padding:"0.5rem 1.25rem"},children:Zs?"Save & Map Ingredient":Ve?"Save & Update Default":"Save"})]})]})}),s.jsx(A0,{open:Ic,onClose:()=>al(!1),onSaved:FC,prePopulateName:qu||((EC=nn==null?void 0:nn.description)==null?void 0:EC.split(` -`)[0])||"",preSelectLineItem:nn?{product_code:nn.product_code,description:((tw=nn.description)==null?void 0:tw.split(` -`)[0])||"",supplier_id:(_e==null?void 0:_e.supplier_id)||null,supplier_name:(_e==null?void 0:_e.supplier_name)||null,unit:nn.unit,most_recent_price:nn.unit_price,total_quantity:nn.quantity,occurrence_count:1,most_recent_invoice_id:Number(n),most_recent_line_number:nn.line_number,most_recent_pack_quantity:nn.pack_quantity,most_recent_unit_size:nn.unit_size,most_recent_unit_size_type:nn.unit_size_type,ingredient_id:nn.ingredient_id||null,ingredient_name:nn.ingredient_name||null}:null})]})}const fe={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00"},pageContainer:{display:"flex",flexDirection:"column",gap:"1.5rem"},topRow:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1.5rem"},imageSection:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",overflow:"hidden",minWidth:0},imageZoomControls:{display:"flex",alignItems:"center",gap:"0.5rem",marginTop:"1rem",justifyContent:"center"},zoomBtn:{padding:"0.5rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"1rem",fontWeight:"bold",minWidth:"36px"},zoomLabel:{fontSize:"0.9rem",color:"#666",minWidth:"50px",textAlign:"center"},zoomResetBtnSmall:{padding:"0.4rem 0.75rem",background:"#fff3cd",border:"1px solid #ffc107",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"500"},imageScrollContainer:{marginTop:"0.5rem",maxHeight:"70vh",maxWidth:"100%",overflow:"auto",background:"#f5f5f5",borderRadius:"8px",padding:"8px"},imageContainer:{position:"relative"},image:{width:"100%",borderRadius:"8px",display:"block"},pdfScrollContainer:{marginTop:"1rem",maxHeight:"70vh",overflow:"auto",background:"#e5e5e5",borderRadius:"8px",padding:"16px"},pdfPageWrapper:{marginBottom:"16px"},pdfPageContainer:{position:"relative",margin:"0 auto",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"},pageLabel:{textAlign:"center",fontSize:"0.8rem",color:"#666",marginTop:"4px"},highlightOverlay:{position:"absolute",background:"rgba(255, 200, 0, 0.3)",borderRadius:"2px",cursor:"pointer",boxShadow:"0 0 8px rgba(255, 200, 0, 0.6)",animation:"pulse 1.5s infinite"},imagePlaceholder:{width:"100%",height:"300px",background:"#f5f5f5",borderRadius:"8px",marginTop:"1rem",display:"flex",alignItems:"center",justifyContent:"center",color:"#999"},openPdfLink:{display:"block",marginTop:"0.5rem",textAlign:"center",color:"#0066cc",fontSize:"0.85rem"},zoomResetBtn:{display:"block",margin:"0.5rem auto",padding:"0.4rem 1rem",background:"#fff3cd",border:"1px solid #ffc107",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"500"},confidenceBadge:{marginTop:"1rem",padding:"0.5rem 1rem",background:"#f0f0f0",borderRadius:"20px",textAlign:"center",fontSize:"0.9rem",color:"#666"},formSection:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},duplicateWarning:{padding:"1rem",borderRadius:"8px",marginBottom:"1rem",cursor:"pointer",borderWidth:"1px",borderStyle:"solid",fontWeight:"500"},form:{display:"flex",flexDirection:"column",gap:"0.75rem"},row:{display:"flex",gap:"1rem"},label:{display:"flex",flexDirection:"column",gap:"0.25rem",color:"#333",fontWeight:"500",fontSize:"0.9rem"},input:{padding:"0.5rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.95rem",flex:1},inputWithEye:{display:"flex",gap:"0.5rem",alignItems:"center"},eyeBtn:{padding:"0.4rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem",lineHeight:1,flexShrink:0},eyeBtnActive:{background:"#fff3cd",border:"1px solid #ffc107"},extractedHint:{fontSize:"0.8rem",color:"#666",fontWeight:"normal",fontStyle:"italic"},extractedHintRow:{display:"flex",alignItems:"center",gap:"0.75rem",marginTop:"0.25rem",flexWrap:"wrap"},fuzzyMatchWarning:{fontSize:"0.8rem",color:"#856404",background:"#fff3cd",padding:"0.35rem 0.5rem",borderRadius:"4px",marginTop:"0.25rem",border:"1px solid #ffc107",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem",flexWrap:"wrap"},addAliasBtn:{padding:"0.2rem 0.5rem",background:"#28a745",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.75rem",fontWeight:"500",whiteSpace:"nowrap"},supplierRow:{display:"flex",gap:"0.5rem",alignItems:"center"},createSupplierBtn:{padding:"0.5rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",whiteSpace:"nowrap"},createFromExtractedBtn:{padding:"0.25rem 0.5rem",background:"#e94560",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.75rem",fontWeight:"normal"},modalLabel:{display:"flex",flexDirection:"column",gap:"0.5rem",color:"#333",fontWeight:"500",marginTop:"1rem"},lineItemsSection:{background:"white",padding:"1.5rem",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)"},lineItemsTableContainer:{maxHeight:"60vh",overflowY:"auto",overflowX:"auto",border:"1px solid #eee",borderRadius:"8px",position:"relative"},stickyThead:{position:"sticky",top:0,zIndex:2,borderBottom:"2px solid #ddd"},stickyPageIndicatorCell:{background:"#e9ecef",padding:"0.3rem 1rem",textAlign:"center",fontSize:"0.85rem",fontWeight:"500",color:"#495057"},lineItemsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.95rem"},th:{textAlign:"left",padding:"0.75rem 0.5rem",fontWeight:"600",background:"#f8f9fa"},td:{padding:"0.75rem 0.5rem",borderBottom:"1px solid #eee",verticalAlign:"middle"},tableInput:{padding:"0.35rem",borderRadius:"4px",border:"1px solid #ddd",fontSize:"0.9rem",width:"100%"},smallBtn:{padding:"0.35rem 0.75rem",background:"#5cb85c",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",marginRight:"0.25rem",fontSize:"0.8rem"},smallBtnCancel:{padding:"0.35rem 0.75rem",background:"#999",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},editBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},iconBtn:{padding:"0.35rem 0.5rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem",display:"flex",alignItems:"center",justifyContent:"center",minWidth:"32px",height:"32px"},noItems:{color:"#999",fontStyle:"italic",marginTop:"0.5rem"},saveBtn:{flex:1,padding:"1.25rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},confirmBtn:{flex:1,padding:"1.25rem",background:"#5cb85c",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold",fontSize:"1rem"},backBtn:{marginTop:"0.5rem",padding:"0.5rem",background:"transparent",border:"none",color:"#666",cursor:"pointer",width:"100%",fontSize:"0.9rem"},modalOverlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"400px",width:"90%"},wideModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"800px",width:"90%",maxHeight:"80vh",overflowY:"auto"},modalInfo:{margin:"1rem 0",padding:"1rem",background:"#f5f5f5",borderRadius:"8px"},modalDuplicateInfo:{padding:"0.75rem",background:"#d4edda",borderRadius:"6px",marginBottom:"1rem",color:"#155724",fontSize:"0.9rem"},modalActions:{display:"flex",gap:"1rem",marginTop:"1.5rem"},cancelBtn:{flex:1,padding:"0.75rem",background:"#f0f0f0",border:"none",borderRadius:"6px",cursor:"pointer"},confirmDeleteBtn:{flex:1,padding:"0.75rem",background:"#dc3545",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"bold"},compareGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"1rem",marginTop:"1rem"},compareCard:{padding:"1rem",border:"2px solid #ddd",borderRadius:"8px"},viewBtn:{marginTop:"0.5rem",padding:"0.5rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",width:"100%",fontSize:"0.85rem"},closeBtn:{marginTop:"1.5rem",padding:"0.75rem 2rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer"},rawOcrModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"900px",width:"95%",maxHeight:"85vh",overflowY:"auto"},rawOcrHint:{color:"#666",fontSize:"0.9rem",marginBottom:"1rem"},rawOcrContent:{marginTop:"1rem"},rawOcrDoc:{marginBottom:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},rawOcrTable:{width:"100%",borderCollapse:"collapse",marginTop:"0.5rem",fontSize:"0.85rem"},rawOcrTh:{textAlign:"left",padding:"0.5rem",borderBottom:"2px solid #ddd",fontWeight:"600",background:"#e9ecef"},rawOcrTd:{padding:"0.5rem",borderBottom:"1px solid #eee",verticalAlign:"top",wordBreak:"break-word",maxWidth:"300px"},lineItemPreviewCell:{padding:"0.5rem",background:"#f8f9fa",borderBottom:"1px solid #eee",textAlign:"center"},lineItemPreviewContainer:{width:"100%",overflow:"hidden",display:"inline-block"},scaleBtn:{padding:"0.25rem",background:"transparent",borderWidth:"1px",borderStyle:"solid",borderColor:"#ddd",borderRadius:"4px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#666"},scaleBtnActive:{background:"#e8f5e9",borderColor:"#28a745"},costBreakdownField:{display:"flex",flexDirection:"column",gap:"0.25rem",minWidth:"70px"},costBreakdownInput:{padding:"0.4rem",borderRadius:"4px",border:"1px solid #ddd",fontSize:"0.9rem",width:"70px",MozAppearance:"textfield",appearance:"textfield"},costBreakdownValue:{fontSize:"0.95rem",padding:"0.4rem 0"},saveAsDefaultRow:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.75rem",marginBottom:"0.5rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},saveAsDefaultLabel:{display:"flex",alignItems:"center",fontSize:"0.9rem",cursor:"pointer",fontWeight:"500"},savedByInfo:{display:"flex",alignItems:"center",padding:"0.6rem 0.75rem",marginBottom:"0.5rem",background:"#e8f4fd",borderRadius:"6px",border:"1px solid #b8daff",fontSize:"0.85rem",color:"#004085"},searchModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"900px",width:"95%",maxHeight:"85vh",overflowY:"auto"},searchInputRow:{display:"flex",gap:"0.5rem",marginBottom:"1rem"},searchInput:{flex:1,padding:"0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"1rem"},searchButton:{padding:"0.75rem 1.5rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:"500"},searchResultsContainer:{marginTop:"1rem",maxHeight:"50vh",overflowY:"auto"},resultsInfo:{color:"#333",fontSize:"0.9rem",marginBottom:"1rem"},supplierGroup:{marginBottom:"1.5rem",padding:"1rem",background:"#f8f9fa",borderRadius:"8px"},supplierHeader:{margin:"0 0 0.75rem",color:"#1a1a2e",fontSize:"1rem"},searchResultsTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},searchTh:{textAlign:"left",padding:"0.5rem",borderBottom:"2px solid #ddd",fontWeight:"600",background:"#e9ecef"},searchThRight:{textAlign:"right",padding:"0.5rem",borderBottom:"2px solid #ddd",fontWeight:"600",background:"#e9ecef"},searchTd:{padding:"0.5rem",borderBottom:"1px solid #eee"},searchTdRight:{padding:"0.5rem",borderBottom:"1px solid #eee",textAlign:"right"},currentItemSection:{marginBottom:"1.5rem",padding:"1rem",background:"#e8f4f8",borderRadius:"8px",border:"2px solid #2196f3"},currentItemHeader:{margin:"0 0 0.75rem",color:"#1565c0",fontSize:"1rem",fontWeight:"600"},currentItemRow:{background:"#fff"},invoiceLink:{color:"#1976d2",textDecoration:"none",fontSize:"0.8rem",padding:"0.2rem 0.5rem",background:"#e3f2fd",borderRadius:"4px"},errorBanner:{display:"flex",gap:"1rem",padding:"1rem 1.5rem",marginBottom:"1.5rem",background:"#fff3cd",border:"2px solid #ffc107",borderRadius:"8px",color:"#856404"},errorBannerIcon:{fontSize:"2rem",flexShrink:0},errorBannerContent:{flex:1},descSwapModal:{background:"white",padding:"2rem",borderRadius:"12px",maxWidth:"600px",width:"90%",maxHeight:"80vh",overflowY:"auto"},descriptionOption:{padding:"1rem",borderRadius:"8px",background:"#f9f9f9",border:"2px solid #ccc",cursor:"pointer",transition:"background 0.2s"},modalHint:{color:"#666",fontSize:"0.9rem",margin:0}},yfe={new:"#e94560",contacted:"#f0ad4e",awaiting_credit:"#9b59b6",awaiting_replacement:"#8b7ec8",resolved:"#5cb85c"},xfe={low:"#5cb85c",medium:"#5bc0de",high:"#f0ad4e",urgent:"#e94560"};function bfe(){const{token:n}=gn(),[e,t]=K_(),r=e.get("date")||"",[i,o]=k.useState(r?"":"not_resolved"),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState(r),[p,g]=k.useState(null),{data:m}=Oe({queryKey:["suppliers"],queryFn:async()=>{const C=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!C.ok)throw new Error("Failed to fetch suppliers");return C.json()},enabled:!!n}),y=new URLSearchParams;i&&i!=="not_resolved"&&y.append("status",i.toUpperCase()),a&&y.append("priority",a),d&&y.append("supplier_id",d),u&&y.append("opened_date",u);const v=y.toString(),{data:x,isLoading:w,error:S}=Oe({queryKey:["disputes",i,a,d,u],queryFn:async()=>{const C=v?`/api/disputes?${v}`:"/api/disputes",T=await fetch(C,{headers:{Authorization:`Bearer ${n}`}});if(!T.ok)throw new Error("Failed to fetch disputes");return T.json()},enabled:!!n});let _=(x==null?void 0:x.disputes)||[];if(i==="not_resolved"&&(_=_.filter(C=>C.status.toUpperCase()!=="RESOLVED")),k.useEffect(()=>{const C=e.get("invoice_id");if(C&&_.length>0&&!p){const T=_.filter(F=>F.invoice_id===parseInt(C));T.length>0&&(g(T[0]),t({}))}},[_,e,p,t]),w)return s.jsx("div",{style:bi.loading,children:"Loading disputes..."});if(S)return s.jsxs("div",{style:bi.error,children:["Error loading disputes: ",S.message]});const b=(m==null?void 0:m.suppliers)||[];return s.jsxs("div",{children:[s.jsx("div",{style:bi.header,children:s.jsx("h2",{style:bi.title,children:"Invoice Disputes"})}),s.jsxs("div",{style:bi.filters,children:[s.jsxs("select",{value:i,onChange:C=>o(C.target.value),style:bi.filterSelect,children:[s.jsx("option",{value:"not_resolved",children:"Not Resolved (Default)"}),s.jsx("option",{value:"",children:"All Statuses"}),s.jsx("option",{value:"new",children:"New"}),s.jsx("option",{value:"contacted",children:"Contacted"}),s.jsx("option",{value:"awaiting_credit",children:"Awaiting Credit"}),s.jsx("option",{value:"awaiting_replacement",children:"Awaiting Replacement"}),s.jsx("option",{value:"resolved",children:"Resolved"})]}),s.jsxs("select",{value:a,onChange:C=>l(C.target.value),style:bi.filterSelect,children:[s.jsx("option",{value:"",children:"All Priorities"}),s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"urgent",children:"Urgent"})]}),s.jsxs("select",{value:d,onChange:C=>c(C.target.value),style:bi.filterSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),b.map(C=>s.jsx("option",{value:C.id,children:C.name},C.id))]}),s.jsx("input",{type:"date",value:u,onChange:C=>f(C.target.value),style:bi.filterSelect}),(i!=="not_resolved"||a||d||u)&&s.jsx("button",{onClick:()=>{o("not_resolved"),l(""),c(""),f("")},style:bi.clearBtn,children:"Reset Filters"})]}),_.length===0?s.jsxs("div",{style:bi.empty,children:[s.jsx("p",{children:"No disputes found."}),i!=="not_resolved"||a||d||u?s.jsx("button",{onClick:()=>{o("not_resolved"),l(""),c(""),f("")},style:bi.link,children:"Reset filters"}):s.jsx("p",{style:bi.noDataSubtext,children:"No open disputes. Great job!"})]}):s.jsx("div",{style:bi.list,children:_.map(C=>s.jsxs("div",{onClick:()=>g(C),style:bi.card,children:[s.jsxs("div",{style:bi.cardMain,children:[s.jsxs("div",{style:bi.disputeTitleRow,children:[C.supplier_name||"Unknown"," - Invoice #",C.invoice_number||C.invoice_id,s.jsx("span",{style:bi.disputeType,children:C.dispute_type.replace(/_/g," ").toUpperCase()})]}),s.jsxs("div",{style:bi.disputeDateRow,children:["Opened ",new Date(C.opened_at).toLocaleDateString()," • Last updated ",new Date(C.updated_at).toLocaleDateString()]}),s.jsx("div",{style:bi.disputeTitle,children:C.title}),C.description&&s.jsx("div",{style:bi.description,children:C.description.length>120?`${C.description.substring(0,120)}...`:C.description})]}),s.jsxs("div",{style:bi.cardRight,children:[s.jsx("div",{style:{...bi.status,background:yfe[C.status.toLowerCase()]||"#999"},children:C.status.replace(/_/g," ")}),C.difference_amount!=null&&s.jsxs("div",{style:bi.amount,children:["£",Number(Math.abs(C.difference_amount)).toFixed(2)]}),s.jsx("span",{style:{...bi.priorityBadge,background:xfe[C.priority]||"#999"},children:C.priority})]})]},C.id))}),p&&s.jsx(DK,{disputeId:p.id,onClose:()=>g(null),onUpdate:()=>{}})]})}const bi={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},filters:{display:"flex",gap:"1rem",marginBottom:"1.5rem",flexWrap:"wrap"},filterSelect:{padding:"0.5rem 1rem",borderRadius:"8px",border:"1px solid #ccc",fontSize:"1rem",minWidth:"150px"},clearBtn:{padding:"0.5rem 1rem",borderRadius:"8px",border:"none",background:"#666",color:"white",cursor:"pointer",fontWeight:"bold"},empty:{padding:"3rem",textAlign:"center",color:"#666",background:"white",borderRadius:"12px"},noDataSubtext:{marginTop:"0.5rem",color:"#999",fontSize:"0.9rem"},link:{display:"inline-block",marginTop:"1rem",padding:"0.75rem 1.5rem",background:"transparent",color:"#e94560",border:"2px solid #e94560",borderRadius:"8px",textDecoration:"none",fontWeight:"bold",cursor:"pointer"},list:{display:"flex",flexDirection:"column",gap:"1rem"},card:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",padding:"1.5rem",background:"white",borderRadius:"12px",boxShadow:"0 2px 8px rgba(0,0,0,0.08)",cursor:"pointer",textDecoration:"none",color:"inherit",transition:"box-shadow 0.2s"},cardMain:{flex:1,display:"flex",flexDirection:"column",gap:"0.25rem"},cardRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"0.5rem"},disputeTitleRow:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",display:"flex",alignItems:"center",gap:"0.5rem"},disputeType:{fontSize:"0.65rem",fontWeight:"bold",color:"#666",letterSpacing:"0.5px"},disputeDateRow:{fontSize:"0.75rem",color:"#999",marginBottom:"0.25rem"},disputeTitle:{fontSize:"1rem",fontWeight:"bold",color:"#1a1a2e"},priorityBadge:{padding:"0.25rem 0.75rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:"bold",color:"white",textTransform:"uppercase",flexShrink:0},description:{color:"#666",fontSize:"0.9rem"},amount:{fontSize:"1.25rem",fontWeight:"bold",color:"#e94560"},status:{padding:"0.5rem 1rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:"bold",color:"white",textTransform:"uppercase",textAlign:"center",minWidth:"120px"}};pf.register(Bj,Ij,GS,qx,U6,H6,W6);const Cu=n=>n.toISOString().split("T")[0],PK="purchases-report-from-date",RK="purchases-report-to-date",vfe=()=>{const n=sessionStorage.getItem(PK),e=sessionStorage.getItem(RK);if(n&&e)return{from:n,to:e};const t=new Date,r=(7-t.getDay())%7,i=new Date(t);i.setDate(t.getDate()+r);const o=new Date(i);return o.setDate(i.getDate()-27),{from:Cu(o),to:Cu(i)}},wfe=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Cu(t),end:Cu(r)}},Sfe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()};function jfe(){var Be;const{token:n}=gn(),e=go(),[t]=K_(),r=k.useRef(null),o=(()=>{const he=t.get("from"),He=t.get("to");return he&&He?{from:he,to:He,fromUrl:!0}:{...vfe(),fromUrl:!1}})(),[a,l]=k.useState(o.from),[d,c]=k.useState(o.to),[u,f]=k.useState(""),[p,g]=k.useState((o.fromUrl,"custom")),[m,y]=k.useState(o.from),[v,x]=k.useState(o.to);k.useEffect(()=>{sessionStorage.setItem(PK,m),sessionStorage.setItem(RK,v)},[m,v]);const w=Sfe(),S=a!==m||d!==v,_=()=>{y(a),x(d)};k.useEffect(()=>{if(u){const[he,He]=u.split("-").map(Number),Ge=wfe(he,He);l(Ge.start),c(Ge.end),y(Ge.start),x(Ge.end)}},[u]);const b=he=>{l(he),f(""),g("custom")},C=he=>{c(he),f(""),g("custom")},T=he=>{f(he),g(he?"month":"custom")},F=()=>{const he=new Date,He=(7-he.getDay())%7,Ge=new Date(he);Ge.setDate(he.getDate()+He);const ae=new Date(Ge);ae.setDate(Ge.getDate()-27);const K=Cu(ae),de=Cu(Ge);l(K),c(de),y(K),x(de),f(""),g("last28")},A=()=>{const he=new Date;f(`${he.getFullYear()}-${he.getMonth()}`),g("month")},D=()=>{const he=new Date,He=new Date(he.getFullYear(),he.getMonth()-1,1);f(`${He.getFullYear()}-${He.getMonth()}`),g("month")},P=()=>{if(p==="last28")return"Last 4 Weeks: ";if(p==="month"&&u){const[he,He]=u.split("-").map(Number);return`Month of ${new Date(he,He,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},[L,W]=k.useState(!1),{data:O,isLoading:U,error:M}=Oe({queryKey:["purchases-range",m,v],queryFn:async()=>{const he=await fetch(`/api/reports/purchases/range?from_date=${m}&to_date=${v}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch purchases");return he.json()}}),{data:I}=Oe({queryKey:["daily-dispute-stats",m,v],queryFn:async()=>{const he=await fetch(`/api/disputes/stats/daily?from_date=${m}&to_date=${v}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch dispute stats");return he.json()}}),{data:H}=Oe({queryKey:["daily-allowance-stats",m,v],queryFn:async()=>{const he=await fetch(`/api/logbook/daily-stats?date_from=${m}&date_to=${v}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch allowance stats");return he.json()}}),z=he=>{var X;const He=(X=H==null?void 0:H.daily_stats)==null?void 0:X[he];if(!He)return{wastageTotal:0,otherTotal:0,total:0,wastageBreakdown:"",otherBreakdown:"",breakdown:""};const Ge={wastage:"Wastage",transfer:"Transfer",staff_food:"Staff Food",manual_adjustment:"Manual Adjustment"};let ae=0,K=0;const de=[],Y=[],Q=[];for(const[pe,we]of Object.entries(He))if(we&&we.total_cost>0){const st=`${Ge[pe]||pe}: £${we.total_cost.toFixed(2)}`;de.push(st),pe==="wastage"?(ae+=we.total_cost,Y.push(st)):(K+=we.total_cost,Q.push(st))}return{wastageTotal:ae,otherTotal:K,total:ae+K,wastageBreakdown:Y.join(` -`),otherBreakdown:Q.join(` -`),breakdown:de.join(` -`)}},G=k.useMemo(()=>{const he=new Date,He=(7-he.getDay())%7,Ge=new Date(he);Ge.setDate(he.getDate()+He);const ae=new Date(Ge);return ae.setDate(Ge.getDate()-(24*7-1)),{from:Cu(ae),to:Cu(Ge)}},[]),{data:te,isLoading:re,error:me}=Oe({queryKey:["weekly-chart-data",G.from,G.to],queryFn:async()=>{const he=await fetch(`/api/reports/gp/daily?from_date=${G.from}&to_date=${G.to}`,{headers:{Authorization:`Bearer ${n}`}});if(!he.ok)throw new Error("Failed to fetch weekly chart data");return he.json()}}),J=k.useMemo(()=>{if(!(te!=null&&te.data))return[];const he=[],He=new Date(G.from);for(let Ge=0;Ge<24;Ge++){const ae=new Date(He);ae.setDate(He.getDate()+Ge*7);const K=new Date(ae);K.setDate(ae.getDate()+6);const de=Cu(ae),Y=Cu(K);let Q=0,X=0;for(const Ve of te.data)Ve.date>=de&&Ve.date<=Y&&(Q+=Number(Ve.net_purchases)||0,X+=Number(Ve.net_sales)||0);const pe=new Date(de),we=new Date(Y),Ne={day:"numeric",month:"short"},st=`${pe.toLocaleDateString("en-GB",Ne)} - ${we.toLocaleDateString("en-GB",Ne)}`;he.push({weekLabel:st,weekStart:de,weekEnd:Y,totalPurchases:Q,totalSales:X})}return he},[te,G]),ne=J.slice(12,24),ye=J.slice(0,12),ke=k.useMemo(()=>({labels:ne.map(he=>he.weekLabel),datasets:[{label:"Purchases (Last 12 Weeks)",data:ne.map(he=>he.totalPurchases),borderColor:"#e94560",backgroundColor:"rgba(233, 69, 96, 0.1)",borderWidth:2,tension:.1,pointRadius:4,pointBackgroundColor:"#e94560",yAxisID:"y"},{label:"Net Food Sales (Last 12 Weeks)",data:ne.map(he=>he.totalSales),borderColor:"#3b82f6",backgroundColor:"rgba(59, 130, 246, 0.1)",borderWidth:2,tension:.1,pointRadius:4,pointBackgroundColor:"#3b82f6",yAxisID:"y"},{label:"Purchases (Previous 12 Weeks)",data:ye.map(he=>he.totalPurchases),borderColor:"rgba(233, 69, 96, 0.4)",backgroundColor:"transparent",borderWidth:2,borderDash:[5,5],tension:.1,pointRadius:3,pointBackgroundColor:"rgba(233, 69, 96, 0.4)",yAxisID:"y"},{label:"Net Food Sales (Previous 12 Weeks)",data:ye.map(he=>he.totalSales),borderColor:"rgba(59, 130, 246, 0.4)",backgroundColor:"transparent",borderWidth:2,borderDash:[5,5],tension:.1,pointRadius:3,pointBackgroundColor:"rgba(59, 130, 246, 0.4)",yAxisID:"y"},{label:"GP % (Last 12 Weeks)",data:ne.map(he=>he.totalSales>0?(he.totalSales-he.totalPurchases)/he.totalSales*100:0),borderColor:"#10b981",backgroundColor:"transparent",borderWidth:2,borderDash:[8,4],tension:.1,pointRadius:4,pointBackgroundColor:"#10b981",yAxisID:"y1"},{label:"GP % (Previous 12 Weeks)",data:ye.map(he=>he.totalSales>0?(he.totalSales-he.totalPurchases)/he.totalSales*100:0),borderColor:"rgba(16, 185, 129, 0.4)",backgroundColor:"transparent",borderWidth:2,borderDash:[8,4],tension:.1,pointRadius:3,pointBackgroundColor:"rgba(16, 185, 129, 0.4)",yAxisID:"y1"}]}),[ne,ye]),Ye={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top",labels:{usePointStyle:!0,padding:15}},title:{display:!0,text:"Weekly Purchases vs Net Food Sales (Last 12 Weeks with Previous 12 Weeks Comparison)",font:{size:16,weight:"bold"},padding:{bottom:20}},tooltip:{callbacks:{label:function(he){return he.dataset.yAxisID==="y1"?`${he.dataset.label}: ${he.parsed.y.toFixed(1)}%`:`${he.dataset.label}: £${he.parsed.y.toFixed(2)}`}}}},scales:{y:{type:"linear",position:"left",ticks:{callback:function(he){return"£"+he.toLocaleString()}},title:{display:!0,text:"Amount (£)"}},y1:{type:"linear",position:"right",beginAtZero:!0,grid:{drawOnChartArea:!1},ticks:{callback:function(he){return he.toFixed(0)+"%"}},title:{display:!0,text:"GP %"}},x:{title:{display:!0,text:"Week"}}}},De=he=>new Date(he).toLocaleDateString("en-GB",{weekday:"short",day:"numeric"}),qe=(he,He)=>{const Ge=new Date(he),ae=new Date(He),K={day:"numeric",month:"short"};return`${Ge.toLocaleDateString("en-GB",K)} - ${ae.toLocaleDateString("en-GB",K)}`},ue=he=>he>=a&&he<=d,Ze=()=>{if(!O)return[];const he=[];for(const He of O.weeks)for(const Ge of He.suppliers)for(const ae of Object.keys(Ge.invoices_by_date))for(const K of Ge.invoices_by_date[ae])he.find(de=>de.invoice.id===K.id)||he.push({invoice:K,supplierName:Ge.supplier_name});return he.sort((He,Ge)=>{const ae=He.invoice.invoice_date||"",K=Ge.invoice.invoice_date||"";return ae.localeCompare(K)}),he},ee=()=>{W(!0),setTimeout(()=>{window.print(),W(!1)},100)};if(U)return s.jsx("div",{style:et.loading,children:"Loading purchases..."});if(M)return s.jsxs("div",{style:et.error,children:["Error loading purchases: ",M.message]});const{weeks:Z=[],period_total:ge=0,period_label:Te=""}=O||{};if(L){const he=Ze();return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:` - @media print { - header, nav, .no-print { display: none !important; } - body { margin: 0; padding: 0; } - } - `}),s.jsxs("div",{style:et.printContainer,ref:r,children:[s.jsxs("h1",{style:et.printTitle,children:["Purchases Report - ",P(),Te]}),s.jsxs("table",{style:et.printTableSmall,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:et.printThDateSmall,children:"Date"}),s.jsx("th",{style:et.printThSmall,children:"Supplier"}),s.jsx("th",{style:et.printThSmall,children:"Invoice #"}),s.jsx("th",{style:et.printThRightSmall,children:"Net Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Gross Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Net Non-Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Gross Non-Stock"}),s.jsx("th",{style:et.printThRightSmall,children:"Net Total"}),s.jsx("th",{style:et.printThRightSmall,children:"Gross Total"})]})}),s.jsx("tbody",{children:he.map(({invoice:He,supplierName:Ge})=>{const ae=Number(He.total??0),K=Number(He.net_total??0),de=K||ae,Y=ae||K,Q=Number(He.net_stock??0),pe=Number(He.gross_stock??0)||(Math.abs(Q)>0&&Math.abs(Y)>0&&Math.abs(de)>0?Q*(Y/de):Q),we=de-Q,Ne=Y-pe,st=de<0||Q<0,Ve=(Re,Le=!1)=>Math.abs(Re)<.01&&!Le?"-":Re<0?`-£${Math.abs(Re).toFixed(2)} CR`:`£${Re.toFixed(2)}`;return s.jsxs("tr",{style:st?{background:"#d4edda"}:{},children:[s.jsx("td",{style:et.printTdDateSmall,children:He.invoice_date||"-"}),s.jsxs("td",{style:et.printTdSmall,children:[Ge,st&&" (CR)"]}),s.jsx("td",{style:et.printTdSmall,children:He.invoice_number||"-"}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(Q,!0)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(pe,!0)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(we)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(Ne)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(de,!0)}),s.jsx("td",{style:et.printTdRightSmall,children:Ve(Y,!0)})]},He.id)})}),s.jsx("tfoot",{children:(()=>{const He=he.reduce((de,{invoice:Y})=>{const Q=Number(Y.total??0),X=Number(Y.net_total??0),pe=X||Q,we=Q||X,Ne=Number(Y.net_stock??0),Ve=Number(Y.gross_stock??0)||(Math.abs(Ne)>0&&Math.abs(we)>0&&Math.abs(pe)>0?Ne*(we/pe):Ne);return{netStock:de.netStock+Ne,grossStock:de.grossStock+Ve,netTotal:de.netTotal+pe,grossTotal:de.grossTotal+we}},{netStock:0,grossStock:0,netTotal:0,grossTotal:0}),Ge=He.netTotal-He.netStock,ae=He.grossTotal-He.grossStock,K=(de,Y=!1)=>Math.abs(de)<.01&&!Y?"-":de<0?`-£${Math.abs(de).toFixed(2)} CR`:`£${de.toFixed(2)}`;return s.jsxs("tr",{style:et.printFooter,children:[s.jsx("td",{colSpan:3,style:et.printTdSmall,children:s.jsx("strong",{children:"Period Total"})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.netStock,!0)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.grossStock,!0)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(Ge)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(ae)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.netTotal,!0)})}),s.jsx("td",{style:et.printTdRightSmall,children:s.jsx("strong",{children:K(He.grossTotal,!0)})})]})})()})]})]})]})}return s.jsxs("div",{children:[s.jsxs("div",{style:et.header,children:[s.jsx("h2",{style:et.title,children:"Purchases Report"}),s.jsx("button",{onClick:ee,style:et.printBtn,children:"Print"})]}),s.jsxs("div",{style:et.dateControls,children:[s.jsxs("div",{style:et.dateRow,children:[s.jsxs("div",{style:et.dateField,children:[s.jsx("label",{style:et.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:a,onChange:he=>b(he.target.value),style:et.dateInput})]}),s.jsxs("div",{style:et.dateField,children:[s.jsx("label",{style:et.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:d,onChange:he=>C(he.target.value),style:et.dateInput})]}),s.jsxs("div",{style:et.dateField,children:[s.jsx("label",{style:et.dateLabel,children:"Month"}),s.jsxs("select",{value:u,onChange:he=>T(he.target.value),style:et.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),w.map(he=>s.jsx("option",{value:`${he.year}-${he.month}`,children:he.label},`${he.year}-${he.month}`))]})]})]}),s.jsxs("div",{style:et.presetRow,children:[s.jsx("button",{onClick:F,style:et.presetBtn,children:"Last 4 Weeks"}),s.jsx("button",{onClick:A,style:et.presetBtn,children:"This Month"}),s.jsx("button",{onClick:D,style:et.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:_,disabled:!S,style:{...et.generateBtn,...S?{}:et.generateBtnDisabled},children:S?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:et.periodLabel,children:[P(),Te]}),Z.length===0?s.jsx("div",{style:et.empty,children:s.jsx("p",{children:"No purchases in this period."})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:et.sectionContainer,children:[s.jsx("h3",{style:et.sectionTitle,children:"Daily Spending by Supplier"}),[...Z].reverse().map((he,He)=>{const Ge=Z.length-1-He;return!he.dates.some(K=>{const de=K;return ue(de)?he.suppliers.some(Y=>{var Q;return((Q=Y.invoices_by_date[de])==null?void 0:Q.length)>0}):!1})&&he.week_total===0?null:s.jsxs("div",{style:et.weekContainer,children:[s.jsxs("div",{style:et.weekHeader,children:[s.jsxs("span",{style:et.weekTitle,children:["Week ",Ge+1]}),s.jsx("span",{style:et.weekRange,children:qe(he.week_start,he.week_end)}),s.jsxs("span",{style:{...et.weekTotal,...Number(he.week_total)<0?{color:"#28a745"}:{}},children:["Week Total: ",Number(he.week_total)<0?"-":"","£",Math.abs(Number(he.week_total)).toFixed(2),Number(he.week_total)<0&&" CR"]})]}),s.jsx("div",{style:et.tableContainer,children:s.jsxs("table",{style:et.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...et.th,...et.supplierHeader},children:"Supplier"}),he.dates.map(K=>{const de=K,Y=ue(de);return s.jsx("th",{style:{...et.th,...Y?{}:et.outOfMonth},children:De(de)},de)}),s.jsx("th",{style:{...et.th,...et.totalHeader},children:"Total"}),s.jsx("th",{style:{...et.th,...et.percentHeader},children:"%"})]})}),s.jsx("tbody",{children:he.suppliers.map(K=>Object.values(K.invoices_by_date).some(Y=>Y.length>0)?s.jsxs("tr",{style:et.tr,children:[s.jsxs("td",{style:{...et.td,...et.supplierCell,...K.is_unmatched?et.unmatchedSupplier:{}},children:[K.supplier_name,K.is_unmatched&&s.jsx("span",{style:et.unmatchedBadge,children:"!"})]}),he.dates.map(Y=>{const Q=Y,X=K.invoices_by_date[Q]||[],pe=ue(Q);return s.jsx("td",{style:{...et.td,...pe?{}:et.outOfMonthCell},children:X.length>0?s.jsx("div",{style:et.invoicesCell,children:X.map(we=>{const Ne=Number(we.net_stock??0),st=Number(we.net_total??we.total??0),Ve=Ne===0&&st!==0,Re=Ne!==0&&Math.abs(Math.abs(Ne)-Math.abs(st))>.01,Le=Ne<0||st<0;return s.jsx("button",{onClick:()=>e(`/invoice/${we.id}`),style:{...et.invoiceBtn,...Le?et.creditNoteInvoice:{},...Ve&&!Le?et.nonStockInvoice:{},...we.supplier_match_type==="fuzzy"&&!Le?et.fuzzyInvoice:{},...we.supplier_match_type===null&&K.is_unmatched&&!Le?et.unmatchedInvoice:{}},title:`${Le?"CREDIT NOTE: ":""}${we.invoice_number||`Invoice #${we.id}`}`,children:Ve?s.jsxs("span",{children:[Le?"":"(","£",Math.abs(st).toFixed(2),Le?" CR":")"]}):Re?s.jsxs("span",{children:[Le&&"-","£",Math.abs(Ne).toFixed(2),Le&&" CR",s.jsx("br",{}),s.jsxs("span",{style:{fontSize:"0.7rem",opacity:.8},children:["(",Le&&"-","£",Math.abs(st).toFixed(2),")"]})]}):s.jsxs("span",{children:[Le&&"-","£",Math.abs(Ne).toFixed(2),Le&&" CR"]})},we.id)})}):s.jsx("span",{style:et.emptyCell,children:"-"})},Q)}),s.jsx("td",{style:{...et.td,...Number(K.total_net_stock)<0?et.negativeTotalCell:et.totalCell},children:(()=>{const Y=Number(K.total_net_stock),Q=Object.values(K.invoices_by_date).flat().reduce((we,Ne)=>we+Number(Ne.net_total??Ne.total??0),0),X=Math.abs(Q)>.01&&Math.abs(Y-Q)>.01,pe=Y<0;return s.jsxs(s.Fragment,{children:[pe?"-":"","£",Math.abs(Y).toFixed(2),pe&&" CR",X&&s.jsxs("div",{style:{fontSize:"0.75rem",color:pe?"#155724":"#888"},children:["(",Q<0?"-":"","£",Math.abs(Q).toFixed(2),")"]})]})})()}),s.jsxs("td",{style:{...et.td,...et.percentCell},children:[Number(K.percentage).toFixed(1),"%"]})]},K.supplier_id??K.supplier_name):null)}),s.jsxs("tfoot",{children:[s.jsxs("tr",{style:et.footerRow,children:[s.jsx("td",{style:{...et.td,...et.footerLabel},children:"Daily Total"}),he.dates.map(K=>{var Ne;const de=K,Y=ue(de),Q=Number(he.daily_totals[de]??0),X=Number(((Ne=he.daily_invoice_totals)==null?void 0:Ne[de])??0),pe=Math.abs(X)>.01&&Math.abs(Q-X)>.01,we=Q<0;return s.jsxs("td",{style:{...et.td,...et.footerCell,...Y?{}:et.outOfMonthCell,...we?{color:"#155724",background:"#d4edda"}:{}},children:[we?"-":"","£",Math.abs(Q).toFixed(2),we&&" CR",pe&&s.jsxs("div",{style:{fontSize:"0.75rem",color:we?"#155724":"#888"},children:["(",X<0?"-":"","£",Math.abs(X).toFixed(2),")"]})]},de)}),s.jsxs("td",{style:{...et.td,...et.grandTotal,...Number(he.week_total)<0?{background:"#28a745"}:{}},children:[Number(he.week_total)<0?"-":"","£",Math.abs(Number(he.week_total)).toFixed(2),Number(he.week_total)<0&&" CR",he.week_invoice_total!=null&&Math.abs(he.week_invoice_total-he.week_total)>.01&&s.jsxs("div",{style:{fontSize:"0.75rem",color:"#ccc"},children:["(",Number(he.week_invoice_total)<0?"-":"","£",Math.abs(Number(he.week_invoice_total)).toFixed(2),")"]})]}),s.jsx("td",{style:{...et.td,...et.footerCell},children:"100%"})]}),s.jsxs("tr",{style:et.statsRow,children:[s.jsx("td",{style:{...et.td,...et.statsLabel},children:"Disputes"}),he.dates.map(K=>{var pe;const de=K,Y=ue(de),Q=(pe=I==null?void 0:I.daily_stats)==null?void 0:pe[de],X=Q&&Q.total_disputed>0;return s.jsx("td",{style:{...et.td,...Y?{}:et.outOfMonthCell},children:X?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",alignItems:"center"},children:[Q.unresolved_total>0&&s.jsxs("button",{onClick:()=>e(`/disputes?date=${de}`),style:et.statsBtn,title:`${Q.unresolved_count} unresolved dispute(s)`,children:["£",Q.unresolved_total.toFixed(2)]}),Q.resolved_total>0&&s.jsxs("button",{onClick:()=>e(`/disputes?date=${de}`),style:et.statsBtnResolved,title:`${Q.resolved_count} resolved dispute(s)`,children:["£",Q.resolved_total.toFixed(2)]})]}):s.jsx("span",{style:et.emptyCell,children:"-"})},de)}),s.jsx("td",{style:{...et.td,...et.statsTotal},children:(()=>{const K=Object.entries((I==null?void 0:I.daily_stats)||{}).filter(([Q])=>he.dates.includes(Q)),de=K.reduce((Q,[,X])=>Q+((X==null?void 0:X.unresolved_total)||0),0),Y=K.reduce((Q,[,X])=>Q+((X==null?void 0:X.resolved_total)||0),0);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[de>0&&s.jsxs("span",{style:{color:"#dc3545"},children:["£",de.toFixed(2)]}),Y>0&&s.jsxs("span",{style:{color:"#6c757d"},children:["£",Y.toFixed(2)]}),de===0&&Y===0&&s.jsx("span",{children:"£0.00"})]})})()}),s.jsx("td",{style:{...et.td}})]}),s.jsxs("tr",{style:et.statsRow,children:[s.jsx("td",{style:{...et.td,...et.statsLabel},children:"Allowances"}),he.dates.map(K=>{const de=K,Y=ue(de),{wastageTotal:Q,otherTotal:X,total:pe,wastageBreakdown:we,otherBreakdown:Ne}=z(de),st=pe>0;return s.jsx("td",{style:{...et.td,...Y?{}:et.outOfMonthCell},children:st?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",alignItems:"center"},children:[Q>0&&s.jsxs("button",{onClick:()=>e(`/logbook?date_from=${de}&date_to=${de}`),style:et.wastageBtn,title:we,children:["£",Q.toFixed(2)]}),X>0&&s.jsxs("button",{onClick:()=>e(`/logbook?date_from=${de}&date_to=${de}`),style:et.allowancePurpleBtn,title:Ne,children:["£",X.toFixed(2)]})]}):s.jsx("span",{style:et.emptyCell,children:"-"})},de)}),s.jsx("td",{style:{...et.td,...et.statsTotal},children:(()=>{const K=he.dates.reduce((Y,Q)=>Y+z(Q).wastageTotal,0),de=he.dates.reduce((Y,Q)=>Y+z(Q).otherTotal,0);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[K>0&&s.jsxs("span",{style:{color:"#fd7e14"},children:["£",K.toFixed(2)]}),de>0&&s.jsxs("span",{style:{color:"#6f42c1"},children:["£",de.toFixed(2)]}),K===0&&de===0&&s.jsx("span",{children:"£0.00"})]})})()}),s.jsx("td",{style:{...et.td}})]})]})]})})]},Ge)})]}),s.jsx("div",{style:{...et.periodTotalContainer,...Number(ge)<0?{color:"#28a745"}:{}},children:s.jsxs("strong",{children:["Period Total: ",Number(ge)<0?"-":"","£",Math.abs(Number(ge)).toFixed(2),Number(ge)<0&&" CR"]})})]}),s.jsx("div",{style:et.chartContainer,children:re?s.jsx("div",{style:{textAlign:"center",padding:"2rem",color:"#666"},children:"Loading weekly comparison chart..."}):me?s.jsxs("div",{style:{textAlign:"center",padding:"2rem",color:"#c00"},children:["Error loading chart: ",me.message]}):J.length>0?s.jsx("div",{style:{height:"400px"},children:s.jsx(IU,{data:ke,options:Ye})}):s.jsxs("div",{style:{textAlign:"center",padding:"2rem",color:"#666"},children:[s.jsx("div",{children:"No data available for weekly comparison chart"}),te&&s.jsxs("div",{style:{marginTop:"1rem",fontSize:"0.85rem"},children:["Debug: Date range ",G.from," to ",G.to,s.jsx("br",{}),"Data points received: ",((Be=te.data)==null?void 0:Be.length)||0]})]})})]})}const et={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem",flexWrap:"wrap",gap:"1rem"},title:{color:"#1a1a2e",margin:0},printBtn:{padding:"0.5rem 1rem",background:"#6c757d",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},periodTotalContainer:{background:"white",borderRadius:"12px",padding:"1rem 1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",textAlign:"right",fontSize:"1.1rem",color:"#e94560"},empty:{background:"white",padding:"3rem",borderRadius:"12px",textAlign:"center",color:"#666"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem"},chartContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginTop:"2rem"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e"},weekContainer:{marginBottom:"2rem"},weekHeader:{display:"flex",alignItems:"center",gap:"1rem",marginBottom:"0.5rem",flexWrap:"wrap"},weekTitle:{fontWeight:"bold",fontSize:"1rem",color:"#1a1a2e"},weekRange:{color:"#666",fontSize:"0.9rem"},weekTotal:{marginLeft:"auto",fontWeight:"bold",color:"#e94560"},tableContainer:{background:"white",borderRadius:"12px",overflow:"auto",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.9rem"},th:{padding:"0.75rem 0.5rem",background:"#1a1a2e",color:"white",fontWeight:"600",textAlign:"center",whiteSpace:"nowrap"},supplierHeader:{textAlign:"left",paddingLeft:"1rem",minWidth:"150px"},totalHeader:{background:"#2d2d44"},percentHeader:{background:"#2d2d44",minWidth:"60px"},outOfMonth:{background:"#3d3d54",opacity:.7},outOfMonthCell:{background:"#f8f9fa",opacity:.6},tr:{borderBottom:"1px solid #eee"},td:{padding:"0.5rem",textAlign:"center",verticalAlign:"top"},supplierCell:{textAlign:"left",paddingLeft:"1rem",fontWeight:"500",whiteSpace:"nowrap"},unmatchedSupplier:{color:"#721c24",background:"#f8d7da"},unmatchedBadge:{display:"inline-block",marginLeft:"0.3rem",width:"14px",height:"14px",lineHeight:"14px",textAlign:"center",background:"#dc3545",color:"white",borderRadius:"50%",fontSize:"0.7rem",fontWeight:"bold"},invoicesCell:{display:"flex",flexDirection:"column",gap:"0.25rem",alignItems:"center"},invoiceBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#e8f4e8",color:"#155724",borderRadius:"4px",textDecoration:"none",fontSize:"0.85rem",fontWeight:"500",border:"1px solid #c3e6cb",cursor:"pointer"},fuzzyInvoice:{background:"#fff3cd",color:"#856404",border:"1px solid #ffc107"},nonStockInvoice:{background:"#e9ecef",color:"#6c757d",border:"1px solid #ced4da"},unmatchedInvoice:{background:"#f8d7da",color:"#721c24",border:"1px solid #f5c6cb"},creditNoteInvoice:{background:"#d4edda",color:"#155724",border:"2px solid #28a745",fontWeight:"bold"},emptyCell:{color:"#ccc"},totalCell:{fontWeight:"bold",background:"#f8f9fa"},negativeTotalCell:{fontWeight:"bold",background:"#d4edda",color:"#155724"},percentCell:{fontWeight:"500",background:"#f8f9fa",color:"#666"},footerRow:{background:"#f8f9fa",borderTop:"2px solid #dee2e6"},footerLabel:{textAlign:"left",paddingLeft:"1rem",fontWeight:"bold"},footerCell:{fontWeight:"bold"},grandTotal:{fontWeight:"bold",background:"#1a1a2e",color:"white"},statsRow:{background:"#fafbfc",borderTop:"1px solid #e9ecef"},statsLabel:{textAlign:"left",paddingLeft:"1rem",fontWeight:"500",color:"#6c757d",fontSize:"0.85rem"},statsBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#dc3545",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer",minWidth:"28px"},statsBtnResolved:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#6c757d",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer",minWidth:"28px"},allowancePurpleBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#6f42c1",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer"},wastageBtn:{display:"inline-block",padding:"0.2rem 0.5rem",background:"#fd7e14",color:"white",borderRadius:"4px",fontSize:"0.8rem",fontWeight:"600",border:"none",cursor:"pointer"},statsTotal:{fontWeight:"600",color:"#6c757d",fontSize:"0.85rem"},printContainer:{padding:"1rem",background:"white"},printTitle:{marginBottom:"1rem",color:"#1a1a2e",fontSize:"1.2rem"},printTableSmall:{width:"100%",borderCollapse:"collapse",fontSize:"0.65rem"},printThSmall:{padding:"0.2rem 0.3rem",background:"#f8f9fa",border:"1px solid #dee2e6",textAlign:"left",fontWeight:"bold"},printThDateSmall:{padding:"0.2rem 0.3rem",background:"#f8f9fa",border:"1px solid #dee2e6",textAlign:"left",fontWeight:"bold",whiteSpace:"nowrap",minWidth:"60px"},printThRightSmall:{padding:"0.2rem 0.3rem",background:"#f8f9fa",border:"1px solid #dee2e6",textAlign:"right",fontWeight:"bold"},printTdSmall:{padding:"0.15rem 0.2rem",border:"1px solid #dee2e6"},printTdDateSmall:{padding:"0.15rem 0.2rem",border:"1px solid #dee2e6",whiteSpace:"nowrap"},printTdRightSmall:{padding:"0.15rem 0.2rem",border:"1px solid #dee2e6",textAlign:"right"},printFooter:{background:"#f8f9fa"}},kfe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];function _fe({isOpen:n,onClose:e,onSaved:t,invoiceId:r,distributionId:i,isAdmin:o}){const{token:a}=gn(),[l,d]=k.useState(null),[c,u]=k.useState(null),[f,p]=k.useState({}),[g,m]=k.useState("OFFSET"),[y,v]=k.useState(""),[x,w]=k.useState([!0,!0,!0,!0,!0,!1,!1]),[S,_]=k.useState(4),[b,C]=k.useState(""),[T,F]=k.useState(""),[A,D]=k.useState(!1),[P,L]=k.useState(!1),[W,O]=k.useState(null),[U,M]=k.useState(!1),[I,H]=k.useState(!1),[z,G]=k.useState(""),[te,re]=k.useState("");k.useEffect(()=>{n&&(O(null),p({}),m("OFFSET"),v(""),w([!0,!0,!0,!0,!0,!1,!1]),_(4),C(""),F(""),u(null),d(null),H(!1),G(""),re(""))},[n,r,i]),k.useEffect(()=>{!n||!a||(i?(M(!0),fetch(`/api/cost-distributions/${i}`,{headers:{Authorization:`Bearer ${a}`}}).then(ee=>{if(!ee.ok)throw new Error("Failed to load distribution");return ee.json()}).then(ee=>{u(ee),F(ee.notes||""),M(!1)}).catch(ee=>{O(ee.message),M(!1)})):r&&(M(!0),fetch(`/api/cost-distributions/invoice/${r}/availability`,{headers:{Authorization:`Bearer ${a}`}}).then(ee=>{if(!ee.ok)throw new Error("Failed to load invoice data");return ee.json()}).then(ee=>{d(ee);const Z={};for(const ge of ee.line_items)!ge.is_non_stock&&ge.available_qty>0&&(Z[ge.id]={selected:!1,qty:ge.available_qty});if(p(Z),ee.invoice_date){const ge=new Date(ee.invoice_date),Te=ge.getDay(),Be=Te===0?1:8-Te;ge.setDate(ge.getDate()+Be),C(ge.toISOString().slice(0,10))}M(!1)}).catch(ee=>{O(ee.message),M(!1)})))},[n,a,r,i]);const me=k.useMemo(()=>{if(!c)return 0;const ee=new Date().toISOString().slice(0,10),Z=c.entries.filter(ge=>!ge.is_source_offset&&!ge.is_overpay&&ge.entry_date>ee).reduce((ge,Te)=>ge+Te.amount,0);return Math.round(Z*100)/100},[c]),J=k.useMemo(()=>{if(!c||!z)return me;const ee=c.entries.filter(Z=>!Z.is_source_offset&&!Z.is_overpay&&Z.entry_date>=z).reduce((Z,ge)=>Z+ge.amount,0);return Math.round(ee*100)/100},[c,z,me]);k.useEffect(()=>{if(I&&c&&z){const ee=c.entries.filter(Z=>!Z.is_source_offset&&!Z.is_overpay&&Z.entry_date>=z).reduce((Z,ge)=>Z+ge.amount,0);re((Math.round(ee*100)/100).toFixed(2))}},[z,I,c]);const ne=k.useMemo(()=>{if(!l)return 0;let ee=0;for(const Z of l.line_items){const ge=f[Z.id];ge!=null&&ge.selected&&Z.unit_price&&(ee+=ge.qty*Z.unit_price)}return Math.round(ee*100)/100},[l,f]),ye=k.useMemo(()=>{if(g!=="DISTRIBUTE"||!b||S<1||ne<=0)return[];const ee=x.reduce((He,Ge,ae)=>(Ge&&He.push(ae),He),[]);if(ee.length===0)return[];const Z=[],ge=new Date(b);for(let He=0;He({date:He,amount:Ge===Te.length-1?Math.round((ne-Be*(Te.length-1))*100)/100:Be}))},[g,b,S,x,ne]),ke=async()=>{if(!(!a||!r)){O(null),D(!0);try{const ee=Object.entries(f).filter(([Te,Be])=>Be.selected).map(([Te,Be])=>({line_item_id:parseInt(Te),selected_quantity:Be.qty}));if(ee.length===0){O("Please select at least one line item"),D(!1);return}const Z={invoice_id:r,method:g,notes:T||null,line_selections:ee};if(g==="OFFSET"){if(!y){O("Please select a target date"),D(!1);return}Z.target_date=y}else{const Te=x.reduce((Be,he,He)=>(he&&Be.push(He),Be),[]);if(Te.length===0){O("Please select at least one day"),D(!1);return}if(!b){O("Please select a start date"),D(!1);return}Z.days_of_week=Te,Z.num_weeks=S,Z.start_date=b}const ge=await fetch("/api/cost-distributions/",{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!ge.ok){const Te=await ge.json();throw new Error(Te.detail||"Failed to create distribution")}t(),e()}catch(ee){O(ee.message)}finally{D(!1)}}},Ye=async()=>{if(!(!a||!i)){D(!0);try{if(!(await fetch(`/api/cost-distributions/${i}`,{method:"PUT",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify({notes:T})})).ok)throw new Error("Failed to update");t(),e()}catch(ee){O(ee.message)}finally{D(!1)}}},De=async()=>{if(!(!a||!i)&&confirm("Are you sure you want to cancel this distribution? This will remove all scheduled entries.")){L(!0);try{const ee=await fetch(`/api/cost-distributions/${i}`,{method:"DELETE",headers:{Authorization:`Bearer ${a}`}});if(!ee.ok){const Z=await ee.json();throw new Error(Z.detail||"Failed to delete")}t(),e()}catch(ee){O(ee.message)}finally{L(!1)}}},qe=async ee=>{if(!(!a||!i||!z)){D(!0);try{const Z={entry_date:z};!ee&&te&&(Z.amount=parseFloat(te));const ge=await fetch(`/api/cost-distributions/${i}/settle-early`,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!ge.ok){const Te=await ge.json();throw new Error(Te.detail||"Failed to settle")}t(),e()}catch(Z){O(Z.message)}finally{D(!1)}}};if(!n)return null;const ue=!!i&&!!c,Ze=(c==null?void 0:c.status)==="ACTIVE";return s.jsx("div",{style:tt.overlay,onClick:e,children:s.jsxs("div",{style:tt.modal,onClick:ee=>ee.stopPropagation(),children:[s.jsxs("div",{style:tt.header,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("h2",{style:{margin:0,fontSize:"1.1rem"},children:ue?`Cost Distribution #${c.id}`:"New Cost Distribution"}),c&&s.jsx("span",{style:{...tt.statusBadge,background:c.status==="ACTIVE"?"#e3f2fd":c.status==="COMPLETED"?"#e8f5e9":"#ffebee",color:c.status==="ACTIVE"?"#1565c0":c.status==="COMPLETED"?"#2e7d32":"#c62828"},children:c.status})]}),s.jsx("button",{onClick:e,style:tt.closeBtn,children:"×"})]}),s.jsxs("div",{style:tt.body,children:[U&&s.jsx("div",{style:tt.loadingText,children:"Loading..."}),W&&s.jsx("div",{style:tt.error,children:W}),(l||c)&&s.jsxs("div",{style:tt.fieldRow,children:[s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Invoice Date"}),s.jsx("input",{type:"text",disabled:!0,value:(c==null?void 0:c.invoice_date)||(l==null?void 0:l.invoice_date)||"",style:tt.input})]}),s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Invoice #"}),s.jsx("input",{type:"text",disabled:!0,value:(c==null?void 0:c.invoice_number)||(l==null?void 0:l.invoice_number)||"",style:tt.input})]}),s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Supplier"}),s.jsx("input",{type:"text",disabled:!0,value:(c==null?void 0:c.supplier_name)||(l==null?void 0:l.supplier_name)||"",style:tt.input})]})]}),s.jsxs("label",{style:{...tt.field,marginBottom:"1rem"},children:[s.jsx("span",{style:tt.label,children:"Notes"}),s.jsx("textarea",{value:T,onChange:ee=>F(ee.target.value),style:tt.textarea,placeholder:"Optional notes...",disabled:ue&&!Ze})]}),!ue&&l&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:tt.sectionTitle,children:"Line Items"}),s.jsx("div",{style:tt.lineItemsContainer,children:s.jsxs("table",{style:tt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:tt.th}),s.jsx("th",{style:{...tt.th,textAlign:"left"},children:"Description"}),s.jsx("th",{style:tt.th,children:"Unit"}),s.jsx("th",{style:tt.th,children:"Available"}),s.jsx("th",{style:tt.th,children:"Distribute Qty"}),s.jsx("th",{style:tt.th,children:"Price"}),s.jsx("th",{style:tt.th,children:"Value"})]})}),s.jsx("tbody",{children:l.line_items.filter(ee=>!ee.is_non_stock).map(ee=>{const Z=f[ee.id],ge=ee.available_qty<=0,Te=Z!=null&&Z.selected?Math.round(Z.qty*(ee.unit_price||0)*100)/100:0;return s.jsxs("tr",{style:{opacity:ge?.4:1},children:[s.jsx("td",{style:tt.td,children:s.jsx("input",{type:"checkbox",checked:(Z==null?void 0:Z.selected)||!1,disabled:ge,onChange:Be=>p(he=>({...he,[ee.id]:{...he[ee.id],selected:Be.target.checked}}))})}),s.jsx("td",{style:{...tt.td,textAlign:"left",maxWidth:"200px",overflow:"hidden",textOverflow:"ellipsis"},children:ee.description||"-"}),s.jsx("td",{style:tt.td,children:ee.unit||"-"}),s.jsx("td",{style:tt.td,children:ee.available_qty.toFixed(2)}),s.jsx("td",{style:tt.td,children:Z!=null&&Z.selected?s.jsx("input",{type:"number",value:Z.qty,min:.001,max:ee.available_qty,step:.001,onChange:Be=>{const he=Math.min(parseFloat(Be.target.value)||0,ee.available_qty);p(He=>({...He,[ee.id]:{...He[ee.id],qty:he}}))},style:{...tt.qtyInput}}):"-"}),s.jsxs("td",{style:tt.td,children:["£",(ee.unit_price||0).toFixed(2)]}),s.jsx("td",{style:{...tt.td,fontWeight:Z!=null&&Z.selected?600:400},children:Z!=null&&Z.selected?`£${Te.toFixed(2)}`:"-"})]},ee.id)})}),s.jsx("tfoot",{children:s.jsxs("tr",{style:tt.totalRow,children:[s.jsx("td",{colSpan:6,style:{...tt.td,textAlign:"right",fontWeight:600},children:"Total to Distribute:"}),s.jsxs("td",{style:{...tt.td,fontWeight:700,fontSize:"0.95rem"},children:["£",ne.toFixed(2)]})]})})]})}),s.jsx("h3",{style:tt.sectionTitle,children:"Distribution Method"}),s.jsxs("div",{style:tt.tabs,children:[s.jsx("button",{style:g==="OFFSET"?tt.tabActive:tt.tab,onClick:()=>m("OFFSET"),children:"Offset to Date"}),s.jsx("button",{style:g==="DISTRIBUTE"?tt.tabActive:tt.tab,onClick:()=>m("DISTRIBUTE"),children:"Distribute Over Period"})]}),g==="OFFSET"&&s.jsx("div",{style:tt.methodContent,children:s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Target Date"}),s.jsx("input",{type:"date",value:y,onChange:ee=>v(ee.target.value),style:tt.input})]})}),g==="DISTRIBUTE"&&s.jsxs("div",{style:tt.methodContent,children:[s.jsxs("div",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Days of Week"}),s.jsx("div",{style:tt.dowRow,children:kfe.map((ee,Z)=>s.jsx("button",{style:x[Z]?tt.dowBtnActive:tt.dowBtn,onClick:()=>{const ge=[...x];ge[Z]=!ge[Z],w(ge)},children:ee},Z))})]}),s.jsxs("div",{style:tt.fieldRow,children:[s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"For how many weeks?"}),s.jsx("input",{type:"number",value:S,min:1,max:52,onChange:ee=>_(parseInt(ee.target.value)||1),style:{...tt.input,maxWidth:"80px"}})]}),s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Starting from"}),s.jsx("input",{type:"date",value:b,onChange:ee=>C(ee.target.value),style:tt.input})]})]}),ye.length>0&&s.jsxs("div",{style:tt.preview,children:[s.jsxs("div",{style:tt.previewTitle,children:["Preview: ",ye.length," entries, £",ne.toFixed(2)," total"]}),s.jsx("div",{style:tt.previewGrid,children:ye.map(ee=>s.jsxs("div",{style:tt.previewEntry,children:[s.jsx("span",{style:tt.previewDate,children:new Date(ee.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}),s.jsxs("span",{style:tt.previewAmount,children:["£",ee.amount.toFixed(2)]})]},ee.date))})]})]})]}),ue&&c&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:tt.summaryRow,children:[s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Total Value"}),s.jsxs("span",{style:tt.summaryValue,children:["£",c.total_distributed_value.toFixed(2)]})]}),s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Remaining"}),s.jsxs("span",{style:{...tt.summaryValue,color:c.remaining_balance>0?"#e65100":"#2e7d32"},children:["£",c.remaining_balance.toFixed(2)]})]}),s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Method"}),s.jsx("span",{style:tt.summaryValue,children:c.method})]}),s.jsxs("div",{style:tt.summaryItem,children:[s.jsx("span",{style:tt.summaryLabel,children:"Created"}),s.jsxs("span",{style:tt.summaryValue,children:[c.created_by_name||"Unknown",", ",new Date(c.created_at).toLocaleDateString("en-GB")]})]})]}),s.jsx("h3",{style:tt.sectionTitle,children:"Distributed Items"}),s.jsx("div",{style:tt.lineItemsContainer,children:s.jsxs("table",{style:tt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...tt.th,textAlign:"left"},children:"Description"}),s.jsx("th",{style:tt.th,children:"Qty"}),s.jsx("th",{style:tt.th,children:"Price"}),s.jsx("th",{style:tt.th,children:"Value"})]})}),s.jsx("tbody",{children:c.line_selections.map(ee=>s.jsxs("tr",{children:[s.jsx("td",{style:{...tt.td,textAlign:"left"},children:ee.description||"-"}),s.jsx("td",{style:tt.td,children:ee.selected_quantity}),s.jsxs("td",{style:tt.td,children:["£",ee.unit_price.toFixed(2)]}),s.jsxs("td",{style:tt.td,children:["£",ee.distributed_value.toFixed(2)]})]},ee.id))})]})}),s.jsx("h3",{style:tt.sectionTitle,children:"Schedule"}),s.jsx("div",{style:tt.lineItemsContainer,children:s.jsxs("table",{style:tt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...tt.th,textAlign:"left"},children:"Date"}),s.jsx("th",{style:tt.th,children:"Amount"}),s.jsx("th",{style:tt.th,children:"Type"})]})}),s.jsx("tbody",{children:c.entries.map(ee=>s.jsxs("tr",{style:{background:ee.is_source_offset?"#fff3e0":ee.is_overpay?"#e3f2fd":"transparent"},children:[s.jsx("td",{style:{...tt.td,textAlign:"left"},children:new Date(ee.entry_date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric"})}),s.jsxs("td",{style:{...tt.td,color:ee.amount<0?"#c62828":"#2e7d32",fontWeight:600},children:[ee.amount<0?"-":"","£",Math.abs(ee.amount).toFixed(2)]}),s.jsx("td",{style:tt.td,children:ee.is_source_offset?"Source Offset":ee.is_overpay?"Settled Early":"Scheduled"})]},ee.id))})]})}),Ze&&me>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{style:tt.sectionTitle,children:"Settle Early"}),I?s.jsxs("div",{style:tt.settleForm,children:[s.jsxs("div",{style:tt.fieldRow,children:[s.jsxs("label",{style:tt.field,children:[s.jsx("span",{style:tt.label,children:"Settle Date"}),s.jsx("input",{type:"date",value:z,onChange:ee=>G(ee.target.value),style:tt.input})]}),s.jsxs("label",{style:tt.field,children:[s.jsxs("span",{style:tt.label,children:["Amount (max £",J.toFixed(2),")"]}),s.jsx("input",{type:"number",value:te,min:.01,max:J,step:.01,onChange:ee=>re(ee.target.value),style:{...tt.input,maxWidth:"120px"}})]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.5rem"},children:[s.jsx("button",{style:tt.submitBtn,onClick:()=>qe(),disabled:A||!z,children:A?"Settling...":"Confirm Settle"}),s.jsx("button",{style:tt.settleAllBtn,onClick:()=>qe(!0),disabled:A,children:"Settle All"}),s.jsx("button",{style:tt.cancelBtn,onClick:()=>H(!1),children:"Cancel"})]})]}):s.jsx("button",{style:tt.settleBtn,onClick:()=>{H(!0),G(new Date().toISOString().slice(0,10)),re(me.toFixed(2))},children:"Settle Early..."})]})]})]}),s.jsxs("div",{style:tt.footer,children:[s.jsx("div",{style:{display:"flex",gap:"0.5rem"},children:ue&&o&&(c==null?void 0:c.status)!=="CANCELLED"&&s.jsx("button",{style:tt.deleteBtn,onClick:De,disabled:P,children:P?"Cancelling...":"Cancel Distribution"})}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{style:tt.cancelBtn,onClick:e,children:"Close"}),!ue&&s.jsx("button",{style:tt.submitBtn,onClick:ke,disabled:A||ne<=0,children:A?"Saving...":"Create Distribution"}),ue&&Ze&&s.jsx("button",{style:tt.submitBtn,onClick:Ye,disabled:A,children:A?"Saving...":"Save Notes"})]})]})]})})}const tt={overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"12px",maxWidth:"850px",width:"95%",maxHeight:"90vh",display:"flex",flexDirection:"column",overflow:"hidden"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.5rem",borderBottom:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#999",lineHeight:1},statusBadge:{padding:"0.2rem 0.6rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:600},body:{flex:1,overflowY:"auto",padding:"1.5rem"},loadingText:{textAlign:"center",padding:"2rem",color:"#999"},error:{background:"#ffebee",color:"#c62828",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},fieldRow:{display:"flex",gap:"1rem",marginBottom:"1rem"},field:{display:"flex",flexDirection:"column",gap:"0.3rem",flex:1},label:{fontSize:"0.8rem",fontWeight:500,color:"#666"},input:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},textarea:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",minHeight:"50px",resize:"vertical",fontFamily:"inherit"},sectionTitle:{fontSize:"0.95rem",fontWeight:600,margin:"1rem 0 0.5rem 0",color:"#333"},lineItemsContainer:{maxHeight:"300px",overflowY:"auto",border:"1px solid #eee",borderRadius:"6px",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{padding:"0.5rem 0.4rem",background:"#f5f5f5",fontWeight:600,textAlign:"center",borderBottom:"2px solid #ddd",fontSize:"0.8rem",position:"sticky",top:0,zIndex:1},td:{padding:"0.4rem",borderBottom:"1px solid #f0f0f0",textAlign:"center",fontSize:"0.85rem"},totalRow:{background:"#f8f9fa"},qtyInput:{width:"70px",padding:"0.3rem",border:"1px solid #ddd",borderRadius:"4px",textAlign:"center",fontSize:"0.85rem"},tabs:{display:"flex",gap:"0",marginBottom:"1rem"},tab:{flex:1,padding:"0.6rem 1rem",border:"1px solid #ddd",background:"#f5f5f5",cursor:"pointer",fontSize:"0.9rem",fontWeight:500,color:"#666",textAlign:"center"},tabActive:{flex:1,padding:"0.6rem 1rem",border:"1px solid #1a1a2e",background:"#1a1a2e",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500,textAlign:"center"},methodContent:{padding:"1rem",background:"#fafafa",borderRadius:"6px",marginBottom:"1rem"},dowRow:{display:"flex",gap:"0.25rem"},dowBtn:{padding:"0.4rem 0.6rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.8rem",fontWeight:500,color:"#666",minWidth:"42px",textAlign:"center"},dowBtnActive:{padding:"0.4rem 0.6rem",border:"1px solid #1565c0",borderRadius:"4px",background:"#e3f2fd",cursor:"pointer",fontSize:"0.8rem",fontWeight:600,color:"#1565c0",minWidth:"42px",textAlign:"center"},preview:{marginTop:"1rem",padding:"0.75rem",border:"1px solid #c8e6c9",borderRadius:"6px",background:"#f1f8e9"},previewTitle:{fontSize:"0.85rem",fontWeight:600,color:"#33691e",marginBottom:"0.5rem"},previewGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:"0.25rem"},previewEntry:{display:"flex",justifyContent:"space-between",padding:"0.2rem 0.4rem",fontSize:"0.8rem",background:"white",borderRadius:"3px"},previewDate:{color:"#555"},previewAmount:{fontWeight:600,color:"#2e7d32"},summaryRow:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:"0.75rem",marginBottom:"1rem"},summaryItem:{display:"flex",flexDirection:"column",gap:"0.2rem",padding:"0.75rem",background:"#f5f5f5",borderRadius:"6px"},summaryLabel:{fontSize:"0.75rem",fontWeight:500,color:"#999",textTransform:"uppercase"},summaryValue:{fontSize:"0.95rem",fontWeight:600,color:"#333"},settleBtn:{padding:"0.5rem 1rem",border:"1px solid #e65100",borderRadius:"6px",background:"#fff3e0",color:"#e65100",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},settleForm:{padding:"1rem",background:"#fff3e0",borderRadius:"6px",border:"1px solid #ffcc80"},settleAllBtn:{padding:"0.5rem 1rem",border:"1px solid #e65100",borderRadius:"6px",background:"#e65100",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},footer:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.5rem",borderTop:"1px solid #eee"},cancelBtn:{padding:"0.5rem 1rem",border:"1px solid #ddd",borderRadius:"6px",background:"white",cursor:"pointer",fontSize:"0.9rem"},submitBtn:{padding:"0.5rem 1rem",border:"none",borderRadius:"6px",background:"#1a1a2e",color:"white",cursor:"pointer",fontSize:"0.9rem",fontWeight:500},deleteBtn:{padding:"0.5rem 1rem",border:"1px solid #c62828",borderRadius:"6px",background:"#ffebee",color:"#c62828",cursor:"pointer",fontSize:"0.85rem"}};pf.register(Bj,Ij,y5,U6,H6,W6);const GP=n=>{const e=new Date(n);return`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][e.getDay()]} ${e.getDate()}`},KP=(n,e)=>{const t=new Date(n),r=new Date(e),i=t.toLocaleDateString("en-GB",{month:"short"}),o=r.toLocaleDateString("en-GB",{month:"short"});return i===o?`${t.getDate()} - ${r.getDate()} ${i}`:`${t.getDate()} ${i} - ${r.getDate()} ${o}`};function Cfe(){const{token:n,user:e}=gn(),t=go(),r=pi(),[i,o]=k.useState(0),[a,l]=k.useState(!1),[d,c]=k.useState(!1),[u,f]=k.useState(!1),[p,g]=k.useState(null),[m,y]=k.useState(null),[v,x]=k.useState(null),[w,S]=k.useState(!1),[_,b]=k.useState(!1),[C,T]=k.useState(null),[F,A]=k.useState(null),[D,P]=k.useState(!1),[L,W]=k.useState(new Set),{data:O,isLoading:U,error:M,refetch:I}=Oe({queryKey:["budget","weekly",i],queryFn:async()=>{const X=await fetch(`/api/budget/weekly?week_offset=${i}`,{headers:{Authorization:`Bearer ${n}`}});if(!X.ok)throw new Error("Failed to fetch budget data");return X.json()},enabled:!!n}),{data:H}=Oe({queryKey:["budget","weekly",i-1],queryFn:async()=>{const X=await fetch(`/api/budget/weekly?week_offset=${i-1}`,{headers:{Authorization:`Bearer ${n}`}});return X.ok?X.json():null},enabled:!!n}),{data:z}=Oe({queryKey:["budget","weekly",i-2],queryFn:async()=>{const X=await fetch(`/api/budget/weekly?week_offset=${i-2}`,{headers:{Authorization:`Bearer ${n}`}});return X.ok?X.json():null},enabled:!!n}),G=()=>o(X=>X-1),te=()=>o(X=>X+1),re=()=>o(0),[me,J]=k.useState({}),[ne,ye]=k.useState(!1),{data:ke,refetch:Ye,isLoading:De}=Oe({queryKey:["cover-overrides","weekly",i],queryFn:async()=>{const X=await fetch(`/api/cover-overrides/weekly?week_offset=${i}`,{headers:{Authorization:`Bearer ${n}`}});if(!X.ok)throw new Error("Failed to fetch override data");return X.json()},enabled:!!n&&a}),{data:qe}=Oe({queryKey:["cost-distributions","weekly",i,O==null?void 0:O.week_start,O==null?void 0:O.week_end],queryFn:async()=>{const X=await fetch(`/api/cost-distributions/weekly?week_start=${O.week_start}&week_end=${O.week_end}`,{headers:{Authorization:`Bearer ${n}`}});if(!X.ok)throw new Error("Failed to fetch distribution data");return X.json()},enabled:!!n&&!!O});k.useEffect(()=>{qe&&qe.distributions.some(X=>X.status==="ACTIVE"&&(X.bf_balance!==0||X.cf_balance!==0))&&P(!0)},[qe]);const{data:ue}=Oe({queryKey:["resos","resident-covers",O==null?void 0:O.week_start,O==null?void 0:O.week_end],queryFn:async()=>{const X=await fetch(`/api/resos/resident-covers?start_date=${O.week_start}&end_date=${O.week_end}`,{headers:{Authorization:`Bearer ${n}`}});return X.ok?(await X.json()).dates??{}:{}},enabled:!!n&&!!O&&a}),Ze=Ue({mutationFn:async()=>{const X=await fetch("/api/cover-overrides/snapshot",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({week_offset:i})});if(!X.ok)throw new Error("Failed to create snapshot");return X.json()},onSuccess:()=>{Ye(),I()}}),ee=Object.keys(me).length>0,Z=(X,pe,we)=>{const Ne=`${X}|${pe}`;return Ne in me?me[Ne]:we},ge=(X,pe)=>`${X}|${pe}`in me?!0:!!(ke!=null&&ke.overrides.find(Ne=>Ne.override_date===X&&Ne.period===pe)),Te=(X,pe,we,Ne)=>{const st=`${X}|${pe}`,Ve=st in me?me[st]:we;J(Re=>({...Re,[st]:Math.max(0,Ve+Ne)}))},Be=async()=>{ye(!0);try{await Promise.all(Object.entries(me).map(([X,pe])=>{const[we,Ne]=X.split("|");return fetch("/api/cover-overrides",{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({override_date:we,period:Ne,override_covers:pe})})})),J({}),Ye(),I()}finally{ye(!1)}},he=async X=>{await fetch(`/api/cover-overrides/${X}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}}),Ye(),I()},He=async(X,pe,we)=>{await fetch("/api/cover-overrides/spend-rates",{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({week_offset:i,period:X,food_spend:pe,drinks_spend:we})}),Ye(),I()},Ge=X=>{const pe=new Date;pe.setHours(0,0,0,0);const we=new Date(X);return we.setHours(0,0,0,0),we<=pe},ae=X=>{const pe=new Date;pe.setHours(0,0,0,0);const we=new Date(X);return we.setHours(0,0,0,0),weX.dates.map(pe=>{const we=X.daily_totals[pe]??0;let Ne=0;return X.suppliers.forEach(st=>{((st.purchase_orders_by_date||{})[pe]||[]).forEach(Re=>{Ne+=Re.total_amount||0})}),we+Ne}),de=O?(()=>{const X=K(O),pe=H?K(H):Array(7).fill(0),we=z?K(z):Array(7).fill(0),Ne=H?KP(H.week_start,H.week_end):"Week -2",st=z?KP(z.week_start,z.week_end):"Week -3";return{labels:O.daily_data.map(Ve=>Ve.day_name),datasets:[{label:st,data:we,backgroundColor:"rgba(189, 195, 199, 0.4)",borderColor:"rgba(189, 195, 199, 0.6)",borderWidth:1,borderRadius:3,order:3},{label:Ne,data:pe,backgroundColor:"rgba(52, 152, 219, 0.35)",borderColor:"rgba(52, 152, 219, 0.5)",borderWidth:1,borderRadius:3,order:2},{label:"This Week",data:X,backgroundColor:"rgba(46, 204, 113, 0.7)",borderColor:"rgba(39, 174, 96, 0.9)",borderWidth:1,borderRadius:3,order:1}]}})():null,Y={responsive:!0,maintainAspectRatio:!1,plugins:{legend:{position:"top"},title:{display:!1},tooltip:{callbacks:{label:X=>{var pe;return`${X.dataset.label}: £${((pe=X.parsed.y)==null?void 0:pe.toFixed(2))??"0.00"}`}}}},scales:{y:{beginAtZero:!0,ticks:{callback:X=>`£${Number(X).toLocaleString()}`}}}};if(U)return s.jsx("div",{style:xe.container,children:s.jsx("div",{style:xe.loading,children:"Loading budget data..."})});if(M||!O)return s.jsx("div",{style:xe.container,children:s.jsxs("div",{style:xe.error,children:[s.jsx("p",{children:"Failed to load budget data."}),s.jsx("p",{style:{fontSize:"0.9rem",color:"#666"},children:"Make sure the Forecast API is configured in Settings."}),s.jsx("button",{onClick:()=>I(),style:xe.retryBtn,children:"Retry"})]})});const Q=O.total_budget>0?Math.round(O.total_spent/O.total_budget*100):0;return s.jsxs("div",{style:xe.container,children:[s.jsxs("div",{style:xe.header,children:[s.jsx("h2",{style:xe.title,children:"Spend Budget"}),s.jsxs("div",{style:xe.weekNav,children:[s.jsx("button",{onClick:G,style:xe.navBtn,children:"<"}),s.jsx("button",{onClick:re,style:xe.currentBtn,children:i===0?"This Week":"Current"}),s.jsx("button",{onClick:te,style:xe.navBtn,children:">"})]})]}),s.jsxs("div",{style:xe.weekInfo,children:[KP(O.week_start,O.week_end),O.forecast_source!=="forecast_api"&&s.jsx("span",{style:xe.warningBadge,children:"No forecast data"})]}),O.forecast_summary&&(()=>{var st,Ve;const X=O.forecast_summary,pe=X.daily_covers,we=pe.length>0,Ne=we?pe.every(Re=>ae(Re.date)):O.dates.every(Re=>ae(Re));return s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("button",{onClick:()=>l(!a),style:xe.forecastToggle,children:[a?"▾ Hide":"▸ Show"," Forecast Breakdown"]}),a&&s.jsx("div",{style:xe.forecastTableContainer,children:s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh,children:"Service"}),(we?pe:O.dates.map(Re=>({date:Re,day_name:GP(Re)}))).map(Re=>s.jsx("th",{style:xe.forecastTh,children:"day_name"in Re&&Re.day_name?Re.day_name:GP(Re.date)},Re.date)),s.jsx("th",{style:{...xe.forecastTh,...xe.forecastTotalCol},children:"Total"})]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:"Hotel"}),we?pe.map(Re=>{const Le=ae(Re.date),rt=Le?xe.fcActual:xe.fcOtb,$e=Le?xe.fcActual:xe.fcPickup;return s.jsxs("td",{style:xe.forecastTd,children:[s.jsx("span",{style:rt,children:Re.otb_rooms}),s.jsxs("span",{style:{...rt,fontSize:"0.75rem"},children:[" (",Re.otb_guests,")"]}),Re.pickup_rooms>0&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:$e,children:[" +",Re.pickup_rooms]}),s.jsxs("span",{style:{...$e,fontSize:"0.75rem"},children:[" (",Re.pickup_guests,")"]})]})]},Re.date)}):O.dates.map(Re=>s.jsx("td",{style:xe.forecastTd,children:"-"},Re)),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol},children:Ne?s.jsxs("span",{style:xe.fcActual,children:[X.forecast_rooms," (",X.forecast_guests,")"]}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:xe.fcOtb,children:[X.otb_rooms," (",X.otb_guests,")"]}),X.pickup_rooms>0&&s.jsxs("span",{style:xe.fcPickup,children:[" +",X.pickup_rooms," (",X.pickup_guests,")"]})]})})]}),["breakfast","lunch","dinner"].map(Re=>{const Le=X[Re];return s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:Re.charAt(0).toUpperCase()+Re.slice(1)}),we?pe.map(rt=>{const $e=rt[Re],ce=ae(rt.date),Je=ce?xe.fcActual:xe.fcOtb,jt=ce?xe.fcActual:xe.fcPickup;return s.jsx("td",{style:xe.forecastTd,children:ce?s.jsx("span",{style:Je,children:$e.forecast}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:Je,children:$e.otb}),$e.pickup>0&&s.jsxs("span",{style:jt,children:[" +",$e.pickup]})]})},rt.date)}):O.dates.map(rt=>s.jsx("td",{style:xe.forecastTd,children:"-"},rt)),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol},children:Ne?s.jsx("span",{style:xe.fcActual,children:Le.forecast}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:xe.fcOtb,children:Le.otb}),Le.pickup>0&&s.jsxs("span",{style:xe.fcPickup,children:[" +",Le.pickup]}),s.jsxs("span",{style:xe.fcTotal,children:[" = ",Le.forecast]})]})})]},Re)}),ue&&s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:{...xe.forecastServiceCell,fontSize:"0.8rem",color:"#888",fontStyle:"italic"},children:"inc Residents"}),we?pe.map(Re=>{const Le=ue[Re.date]||{},rt=Le.lunch||{covers:0,bookings:0},$e=Le.dinner||{covers:0,bookings:0},ce=rt.bookings+$e.bookings,Je=rt.covers+$e.covers;return s.jsx("td",{style:{...xe.forecastTd,fontSize:"0.8rem",color:"#888",fontStyle:"italic"},children:Je>0?`${ce}/${Je}`:"-"},Re.date)}):O.dates.map(Re=>s.jsx("td",{style:{...xe.forecastTd,fontSize:"0.8rem",color:"#888"},children:"-"},Re)),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol,fontSize:"0.8rem",color:"#888",fontStyle:"italic"},children:(()=>{let Re=0,Le=0;return Object.values(ue).forEach(rt=>{const $e=rt.lunch||{covers:0,bookings:0},ce=rt.dinner||{covers:0,bookings:0};Re+=$e.bookings+ce.bookings,Le+=$e.covers+ce.covers}),Le>0?`${Re}/${Le}`:"-"})()})]})]})]})}),a&&De&&s.jsx("div",{style:{textAlign:"center",padding:"1rem",color:"#888",fontSize:"0.85rem"},children:"Loading override data..."}),a&&ke&&!ke.has_snapshot&&s.jsxs("div",{style:{textAlign:"center",padding:"1rem"},children:[s.jsx("button",{onClick:()=>Ze.mutate(),disabled:Ze.isPending,style:xe.snapshotBtn,children:Ze.isPending?"Creating Snapshot...":"Snapshot Forecast & Override"}),s.jsx("div",{style:{fontSize:"0.8rem",color:"#888",marginTop:"0.5rem"},children:"Takes a snapshot of the current forecast as a baseline for overrides"})]}),a&&(ke==null?void 0:ke.has_snapshot)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:xe.snapshotInfoBar,children:[s.jsxs("span",{children:["Snapshot: £",((st=ke.snapshot_revenue)==null?void 0:st.toLocaleString(void 0,{minimumFractionDigits:2}))??"-",ke.adjusted_revenue!=null&&Math.abs(ke.adjusted_revenue-(ke.snapshot_revenue??0))>1&&s.jsxs("span",{style:{marginLeft:"0.5rem",fontWeight:"bold",color:ke.adjusted_revenue>(ke.snapshot_revenue??0)?"#27ae60":"#e74c3c"},children:["→ £",ke.adjusted_revenue.toLocaleString(void 0,{minimumFractionDigits:2})]})]}),s.jsx("button",{onClick:()=>{window.confirm("Re-snapshot will update the baseline forecast. Continue?")&&Ze.mutate()},style:xe.resnapshotBtn,disabled:Ze.isPending,children:Ze.isPending?"...":"Re-snapshot"})]}),s.jsxs("div",{style:xe.overrideTableContainer,children:[s.jsxs("div",{style:{...xe.overrideSectionHeader,cursor:"pointer",userSelect:"none"},onClick:()=>c(!d),children:[d?"▾":"▸"," Food Spend Per Cover (Gross inc VAT)"]}),d&&s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh}),ke.spend_rates.map(Re=>s.jsx("th",{style:xe.forecastTh,children:Re.period.charAt(0).toUpperCase()+Re.period.slice(1)},Re.period))]})}),s.jsx("tbody",{children:s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:"Food £/hd"}),ke.spend_rates.map(Re=>{const Le=Re.food_spend_effective*ke.vat_rate;return s.jsx("td",{style:xe.forecastTd,children:s.jsx("input",{type:"number",step:"0.50",defaultValue:Le.toFixed(2),style:{...xe.spendInput,...Re.food_spend_override!==null?xe.spendInputOverridden:{}},onBlur:rt=>{const $e=parseFloat(rt.target.value);if(!isNaN($e)&&Math.abs($e-Le)>.001){const ce=Math.round($e/ke.vat_rate*100)/100;He(Re.period,ce,null)}},onKeyDown:rt=>{rt.key==="Enter"&&rt.target.blur()}},`food-${Re.period}-${Le.toFixed(2)}`)},Re.period)})]})})]})]}),s.jsxs("div",{style:xe.overrideTableContainer,children:[s.jsxs("div",{style:{...xe.overrideSectionHeader,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{children:"Cover Overrides (Lunch & Dinner)"}),ee&&s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>J({}),style:xe.discardBtn,children:"Discard"}),s.jsx("button",{onClick:Be,disabled:ne,style:xe.saveOverrideBtn,children:ne?"Saving...":"Save"})]})]}),s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh,children:"Service"}),ke.recalc_days.map(Re=>s.jsx("th",{style:xe.forecastTh,children:Re.day_name},Re.date))]})}),s.jsx("tbody",{children:["lunch","dinner"].map(Re=>s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:Re.charAt(0).toUpperCase()+Re.slice(1)}),ke.recalc_days.map(Le=>{const rt=Le.periods[Re];if(!rt)return s.jsx("td",{style:xe.forecastTd,children:"-"},Le.date);const $e=ke.overrides.find(Se=>Se.override_date===Le.date&&Se.period===Re),ce=Z(Le.date,Re,($e==null?void 0:$e.override_covers)??rt.effective),Je=ge(Le.date,Re),ct=`${Le.date}|${Re}`in me;return Le.is_past?s.jsx("td",{style:{...xe.forecastTd,color:"#999"},children:rt.effective},Le.date):s.jsx("td",{style:xe.forecastTd,children:s.jsxs("div",{style:xe.stepperCell,children:[s.jsx("button",{onClick:()=>Te(Le.date,Re,($e==null?void 0:$e.override_covers)??rt.effective,-1),style:xe.stepperBtn,children:"−"}),s.jsx("span",{style:Je?xe.overriddenValue:void 0,children:ce}),s.jsx("button",{onClick:()=>Te(Le.date,Re,($e==null?void 0:$e.override_covers)??rt.effective,1),style:xe.stepperBtn,children:"+"}),$e&&!ct&&s.jsx("button",{onClick:()=>he($e.id),style:xe.deleteOverrideBtn,title:"Remove override",children:"×"})]})},Le.date)})]},Re))})]})]}),s.jsxs("div",{style:xe.overrideTableContainer,children:[s.jsx("div",{style:xe.overrideSectionHeader,children:"Recalculated Forecast"}),s.jsxs("table",{style:xe.forecastTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:xe.forecastTh,children:"Service"}),ke.recalc_days.map(Re=>s.jsx("th",{style:xe.forecastTh,children:Re.day_name},Re.date)),s.jsx("th",{style:{...xe.forecastTh,...xe.forecastTotalCol},children:"Total"})]})}),s.jsxs("tbody",{children:[["breakfast","lunch","dinner"].map(Re=>{let Le=0;return s.jsxs("tr",{style:xe.forecastTr,children:[s.jsx("td",{style:xe.forecastServiceCell,children:Re.charAt(0).toUpperCase()+Re.slice(1)}),ke.recalc_days.map(rt=>{const $e=rt.periods[Re];return $e?(Le+=$e.effective,rt.is_past?s.jsxs("td",{style:xe.forecastTd,children:[s.jsx("span",{style:xe.fcActual,children:$e.actual??$e.effective}),$e.variance!=null&&$e.variance!==0&&s.jsxs("span",{style:{fontSize:"0.7rem",marginLeft:"2px",color:$e.variance>0?"#27ae60":"#e74c3c"},children:[$e.variance>0?"▲":"▼",Math.abs($e.variance)]})]},rt.date):s.jsxs("td",{style:xe.forecastTd,children:[s.jsx("span",{style:xe.fcOtb,children:$e.otb}),$e.pickup>0&&s.jsx("span",{style:{...xe.fcPickup,...$e.is_overridden?xe.overriddenValue:{}},children:" +"+$e.pickup})]},rt.date)):s.jsx("td",{style:xe.forecastTd,children:"-"},rt.date)}),s.jsx("td",{style:{...xe.forecastTd,...xe.forecastTotalCol},children:Le})]},Re)}),s.jsxs("tr",{style:{...xe.forecastTr,borderTop:"2px solid #ddd"},children:[s.jsx("td",{style:{...xe.forecastServiceCell,fontStyle:"italic",color:"#666"},children:"Revenue"}),ke.recalc_days.map(Re=>s.jsxs("td",{style:{...xe.forecastTd,fontSize:"0.8rem",color:"#666"},children:["£",Re.day_revenue.toLocaleString(void 0,{maximumFractionDigits:0})]},Re.date)),s.jsxs("td",{style:{...xe.forecastTd,...xe.forecastTotalCol,fontSize:"0.8rem"},children:["£",((Ve=ke.adjusted_revenue)==null?void 0:Ve.toLocaleString(void 0,{maximumFractionDigits:0}))??"-"]})]})]})]})]})]})]})})(),s.jsxs("div",{style:xe.summaryCards,children:[s.jsxs("div",{style:xe.card,children:[s.jsx("div",{style:xe.cardLabel,children:O.has_overrides?"Adjusted Revenue":"Forecast Revenue"}),s.jsxs("div",{style:xe.cardValue,children:["£",O.forecast_revenue.toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsx("div",{style:xe.cardSubtext,children:O.has_overrides&&O.snapshot_revenue!=null?`Snapshot: £${O.snapshot_revenue.toLocaleString(void 0,{minimumFractionDigits:2})}`:`OTB: £${O.otb_revenue.toLocaleString(void 0,{minimumFractionDigits:2})}`})]}),s.jsxs("div",{style:xe.card,children:[s.jsx("div",{style:xe.cardLabel,children:"Budget"}),s.jsxs("div",{style:xe.cardValue,children:["£",O.total_budget.toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsxs("div",{style:xe.cardSubtext,children:["OTB: £",O.min_budget.toLocaleString(void 0,{minimumFractionDigits:2})]})]}),s.jsxs("div",{style:xe.card,children:[s.jsx("div",{style:xe.cardLabel,children:"Spent"}),s.jsxs("div",{style:{...xe.cardValue,color:O.total_remaining<0?"#e74c3c":"#333"},children:["£",O.total_spent.toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsxs("div",{style:xe.cardSubtext,children:[Q,"% used"]})]}),s.jsxs("div",{style:{...xe.card,...O.total_remaining<0?xe.cardOver:xe.cardUnder},children:[s.jsx("div",{style:xe.cardLabel,children:"Remaining"}),s.jsxs("div",{style:xe.cardValue,children:[O.total_remaining<0?"-":"","£",Math.abs(O.total_remaining).toLocaleString(void 0,{minimumFractionDigits:2})]}),s.jsx("div",{style:xe.cardSubtext,children:O.total_remaining<0?"OVER BUDGET":`${100-Q}% remaining`})]})]}),s.jsxs("div",{style:xe.section,children:[s.jsx("h3",{style:xe.sectionTitle,children:"Weekly Budget by Supplier"}),s.jsx("div",{style:xe.tableContainer,children:s.jsxs("table",{style:xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...xe.th,...xe.supplierHeader},children:"Supplier"}),O.dates.map(X=>s.jsx("th",{style:{...xe.th,...Ge(X)?{}:xe.futureDate},children:GP(X)},X)),s.jsx("th",{style:{...xe.th,...xe.budgetHeader},children:"Budget"}),s.jsx("th",{style:{...xe.th,...xe.spentHeader},children:"Spent"}),s.jsx("th",{style:{...xe.th,...xe.orderedHeader},children:"Ordered"}),s.jsx("th",{style:{...xe.th,...xe.remainingHeader},children:"Remaining"}),s.jsx("th",{style:{...xe.th,...xe.statusHeader},children:"Status"})]})}),s.jsx("tbody",{children:O.suppliers.map(X=>Object.values(X.invoices_by_date).some(we=>we.length>0)||Object.values(X.purchase_orders_by_date||{}).some(we=>we.length>0)||X.allocated_budget>0?s.jsxs("tr",{style:xe.tr,children:[s.jsxs("td",{style:xe.supplierCell,children:[s.jsx("div",{children:X.supplier_name}),X.historical_pct>0&&s.jsxs("div",{style:xe.supplierPct,children:["(",X.historical_pct.toFixed(1),"%)"]})]}),O.dates.map(we=>{const Ne=X.invoices_by_date[we]||[],st=(X.purchase_orders_by_date||{})[we]||[],Ve=Ne.length>0||st.length>0;return s.jsx("td",{style:{...xe.td,...!Ve&&X.supplier_id?xe.clickableCell:{}},onClick:()=>{!Ve&&X.supplier_id&&(y(X.supplier_id),x(we),g(null),f(!0))},children:Ve?s.jsxs("div",{style:xe.invoicesCell,children:[Ne.map(Re=>{const Le=Re.document_type==="credit_note"||Re.net_stock<0;return s.jsxs("button",{onClick:()=>{w&&!Le?(T(Re.id),A(null),b(!0),S(!1)):t(`/invoice/${Re.id}`)},style:{...xe.invoiceBtn,...Le?xe.creditNoteBtn:{},...w&&!Le?xe.invoiceBtnSelectMode:{}},title:w&&!Le?"Click to distribute this invoice":Re.invoice_number||`Invoice #${Re.id}`,children:[Le&&"-","£",Math.abs(Re.net_stock).toFixed(2),Le&&" CR"]},Re.id)}),st.map(Re=>s.jsxs("button",{onClick:Le=>{Le.stopPropagation(),g(Re.id),y(null),x(null),f(!0)},style:xe.poBtn,title:Re.order_reference?`PO: ${Re.order_reference}`:`PO #${Re.id}`,children:["£",(Re.total_amount||0).toFixed(2)]},`po-${Re.id}`))]}):s.jsx("span",{style:xe.emptyCell,children:X.supplier_id?"+":"-"})},we)}),s.jsxs("td",{style:xe.budgetCell,children:["£",X.allocated_budget.toFixed(2)]}),s.jsxs("td",{style:xe.spentCell,children:["£",X.actual_spent.toFixed(2),X.cd_total!==0&&s.jsxs("div",{style:{fontSize:"0.65rem",color:X.cd_total>0?"#e65100":"#2e7d32"},children:["(",X.cd_total>0?"+":"-","£",Math.abs(X.cd_total).toFixed(2)," dist)"]})]}),s.jsx("td",{style:xe.orderedCell,children:X.po_ordered>0?`£${X.po_ordered.toFixed(2)}`:"-"}),s.jsxs("td",{style:{...xe.remainingCell,...X.remaining<0?xe.overBudget:{}},children:[X.remaining<0?"-":"","£",Math.abs(X.remaining).toFixed(2)]}),s.jsx("td",{style:xe.statusCell,children:s.jsx("span",{style:{...xe.statusBadge,...X.status==="over"?xe.statusOver:X.status==="on_track"?xe.statusOnTrack:xe.statusUnder},children:X.status==="over"?"!":X.status==="on_track"?"~":""})})]},X.supplier_id??X.supplier_name):null)}),s.jsxs("tfoot",{children:[qe&&qe.week_total!==0&&s.jsxs("tr",{style:{...xe.footerRow,background:"#fff8e1"},children:[s.jsx("td",{style:{...xe.footerLabel,color:"#e65100",fontWeight:600},children:"Distributed"}),O.dates.map(X=>{const pe=qe.daily_totals[X]??0;return s.jsx("td",{style:{...xe.footerTd,color:pe<0?"#c62828":pe>0?"#2e7d32":"#999",fontWeight:500},children:pe!==0?s.jsxs(s.Fragment,{children:[pe<0?"-":"+","£",Math.abs(pe).toFixed(2)]}):"-"},X)}),s.jsx("td",{style:xe.footerTd}),s.jsxs("td",{style:{...xe.footerTd,color:"#e65100",fontWeight:600},children:[qe.week_total<0?"-":"+","£",Math.abs(qe.week_total).toFixed(2)]}),s.jsx("td",{style:xe.footerTd}),s.jsx("td",{style:xe.footerTd}),s.jsx("td",{style:xe.footerTd})]}),s.jsxs("tr",{style:xe.footerRow,children:[s.jsx("td",{style:xe.footerLabel,children:"Daily Total"}),O.dates.map(X=>{const pe=O.daily_totals[X]??0,we=Ge(X);return s.jsx("td",{style:xe.footerTd,children:we?`£${pe.toFixed(2)}`:"-"},X)}),s.jsxs("td",{style:xe.footerTd,children:["£",O.total_budget.toFixed(2)]}),s.jsxs("td",{style:xe.footerTd,children:["£",O.total_spent.toFixed(2)]}),s.jsx("td",{style:xe.footerTd,children:O.total_po_ordered>0?`£${O.total_po_ordered.toFixed(2)}`:"-"}),s.jsxs("td",{style:{...xe.footerTd,...O.total_remaining<0?xe.overBudget:{}},children:[O.total_remaining<0?"-":"","£",Math.abs(O.total_remaining).toFixed(2)]}),s.jsx("td",{style:xe.footerTd})]}),s.jsxs("tr",{style:xe.footerRow,children:[s.jsx("td",{style:xe.footerLabel,children:"% of Budget"}),O.daily_data.map(X=>{if(X.actual_spent===null||O.total_budget===0)return s.jsx("td",{style:xe.footerTd,children:"-"},X.date);const pe=X.actual_spent/O.total_budget*100;return s.jsx("td",{style:xe.footerTd,children:X.actual_spent===0?"0%":`${pe.toFixed(0)}%`},X.date)}),s.jsx("td",{colSpan:5})]})]})]})})]}),s.jsxs("div",{style:xe.section,children:[s.jsxs("div",{style:xe.distributionHeader,onClick:()=>P(!D),children:[s.jsxs("span",{style:{cursor:"pointer"},children:[D?"▾":"▸"," Distributed Costs"]}),qe&&qe.distributions.length>0&&s.jsxs("span",{style:xe.distributionSummary,children:["BF: ",qe.bf_balance<0?"-":"","£",Math.abs(qe.bf_balance).toFixed(2)," | ","Movement: ",qe.week_total<0?"-":qe.week_total>0?"+":"","£",Math.abs(qe.week_total).toFixed(2)," | ","CF: ",qe.cf_balance<0?"-":"","£",Math.abs(qe.cf_balance).toFixed(2)]})]}),D&&O&&s.jsx("div",{style:{overflowX:"auto",marginTop:"0.5rem"},children:s.jsxs("table",{style:xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...xe.th,...xe.supplierHeader,minWidth:"180px"},children:"Distribution"}),s.jsx("th",{style:{...xe.th,minWidth:"70px"},children:"BF"}),O.dates.map(X=>s.jsx("th",{style:{...xe.th,minWidth:"70px"},children:new Date(X).toLocaleDateString("en-GB",{weekday:"short",day:"numeric"})},X)),s.jsx("th",{style:{...xe.th,minWidth:"70px"},children:"CF"})]})}),s.jsxs("tbody",{children:[qe==null?void 0:qe.distributions.map(X=>{const pe=L.has(X.distribution_id);return s.jsxs(k.Fragment,{children:[s.jsxs("tr",{children:[s.jsxs("td",{style:{...xe.supplierCell,fontSize:"0.8rem",padding:"0.3rem 0.5rem"},children:[s.jsx("span",{style:{cursor:"pointer",color:"#555",marginRight:"0.3rem",fontSize:"0.7rem"},onClick:()=>W(we=>{const Ne=new Set(we);return Ne.has(X.distribution_id)?Ne.delete(X.distribution_id):Ne.add(X.distribution_id),Ne}),children:pe?"▾":"▸"}),s.jsx("span",{style:{cursor:"pointer",color:"#1565c0"},onClick:()=>{A(X.distribution_id),T(X.invoice_id),b(!0)},title:"Click to view/edit distribution",children:X.title})]}),s.jsx("td",{style:{...xe.dayCell,fontWeight:600,fontSize:"0.8rem",color:"#555"},children:X.bf_balance!==0?s.jsxs(s.Fragment,{children:[X.bf_balance<0?"-":"","£",Math.abs(X.bf_balance).toFixed(2)]}):"-"}),O.dates.map(we=>{const Ne=X.entries_by_date[we];return s.jsx("td",{style:{...xe.dayCell,fontSize:"0.8rem"},children:Ne!=null?s.jsxs("span",{style:{color:Ne<0?"#c62828":"#2e7d32",fontWeight:500},children:[Ne<0?"-":"","£",Math.abs(Ne).toFixed(2)]}):"-"},we)}),s.jsx("td",{style:{...xe.dayCell,fontWeight:600,fontSize:"0.8rem",color:X.cf_balance<0?"#c62828":X.cf_balance===0?"#2e7d32":"#555"},children:X.cf_balance!==0?s.jsxs(s.Fragment,{children:[X.cf_balance<0?"-":"","£",Math.abs(X.cf_balance).toFixed(2)]}):"£0.00"})]}),pe&&s.jsx("tr",{children:s.jsxs("td",{colSpan:O.dates.length+3,style:{padding:"0.3rem 0.5rem 0.5rem 1.5rem",background:"#fafafa",fontSize:"0.75rem",color:"#555",borderTop:"none"},children:[s.jsxs("div",{style:{fontWeight:600},children:[X.supplier_name||"Unknown"," ",X.invoice_number||""]}),s.jsx("div",{children:X.summary}),X.notes&&s.jsx("div",{style:{fontStyle:"italic",marginTop:"0.2rem",color:"#888"},children:X.notes})]})})]},X.distribution_id)}),qe&&qe.distributions.length>0&&s.jsxs("tr",{style:{background:"#f8f9fa",borderTop:"2px solid #ddd"},children:[s.jsx("td",{style:{...xe.supplierCell,fontWeight:600,fontSize:"0.8rem"},children:"Total Movement"}),s.jsx("td",{style:xe.dayCell}),O.dates.map(X=>{const pe=qe.daily_totals[X]??0;return s.jsx("td",{style:{...xe.dayCell,fontWeight:600,fontSize:"0.8rem"},children:pe!==0?s.jsxs("span",{style:{color:pe<0?"#c62828":"#2e7d32"},children:[pe<0?"-":"+","£",Math.abs(pe).toFixed(2)]}):"-"},X)}),s.jsx("td",{style:xe.dayCell})]}),qe&&qe.distributions.length>0&&(()=>{let X=qe.bf_balance;return s.jsxs("tr",{style:{background:"#f0f4f8"},children:[s.jsx("td",{style:{...xe.supplierCell,fontWeight:700,fontSize:"0.8rem"},children:"Balance"}),s.jsx("td",{style:{...xe.dayCell,fontWeight:700,fontSize:"0.8rem"},children:X!==0?s.jsxs(s.Fragment,{children:[X<0?"-":"","£",Math.abs(X).toFixed(2)]}):"-"}),O.dates.map(pe=>(X+=qe.daily_totals[pe]??0,s.jsx("td",{style:{...xe.dayCell,fontWeight:700,fontSize:"0.8rem",color:X<0?"#c62828":X===0?"#2e7d32":"#333"},children:X!==0?s.jsxs(s.Fragment,{children:[X<0?"-":"","£",Math.abs(X).toFixed(2)]}):"£0.00"},pe))),s.jsx("td",{style:{...xe.dayCell,fontWeight:700,fontSize:"0.8rem",color:qe.cf_balance<0?"#c62828":qe.cf_balance===0?"#2e7d32":"#333"},children:qe.cf_balance!==0?s.jsxs(s.Fragment,{children:[qe.cf_balance<0?"-":"","£",Math.abs(qe.cf_balance).toFixed(2)]}):"£0.00"})]})})(),s.jsx("tr",{children:s.jsx("td",{colSpan:O.dates.length+3,style:{padding:"0.5rem",textAlign:"left",borderTop:"1px solid #e0e0e0"},children:w?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[s.jsx("button",{onClick:()=>S(!1),style:xe.spreadCostBtnActive,children:"Cancel"}),s.jsx("span",{style:xe.selectModeHint,children:"Click an invoice in the table above to spread its cost"})]}):s.jsx("button",{onClick:()=>S(!0),style:xe.addDistributionBtn,children:"+ Add Distribution"})})})]})]})})]}),s.jsxs("div",{style:xe.section,children:[s.jsx("h3",{style:xe.sectionTitle,children:"Daily Spend Comparison"}),s.jsx("div",{style:xe.chartContainer,children:de&&s.jsx(Qre,{data:de,options:Y})})]}),s.jsx(TT,{isOpen:u,onClose:()=>{f(!1),g(null),y(null),x(null)},onSaved:()=>{I()},poId:p,defaultSupplierId:m,defaultDate:v}),s.jsx(_fe,{isOpen:_,onClose:()=>{b(!1),T(null),A(null)},onSaved:()=>{I(),r.invalidateQueries({queryKey:["cost-distributions"]})},invoiceId:C,distributionId:F,isAdmin:e==null?void 0:e.is_admin})]})}const xe={container:{padding:"1rem"},loading:{textAlign:"center",padding:"3rem",color:"#666"},error:{textAlign:"center",padding:"3rem",background:"#fff3f3",borderRadius:"8px"},retryBtn:{marginTop:"1rem",padding:"0.5rem 1rem",background:"#3498db",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},title:{margin:0,fontSize:"1.5rem",fontWeight:"bold"},weekNav:{display:"flex",gap:"0.5rem"},navBtn:{padding:"0.5rem 1rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"1rem"},currentBtn:{padding:"0.5rem 1rem",background:"#3498db",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},weekInfo:{fontSize:"1.1rem",color:"#666",marginBottom:"1rem",display:"flex",alignItems:"center",gap:"0.5rem"},warningBadge:{background:"#f39c12",color:"white",padding:"0.2rem 0.5rem",borderRadius:"4px",fontSize:"0.8rem"},forecastToggle:{background:"none",border:"1px solid #ddd",borderRadius:"4px",padding:"0.5rem 1rem",cursor:"pointer",fontSize:"0.9rem",color:"#555",fontWeight:"500"},forecastTableContainer:{overflowX:"auto",background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",marginTop:"0.5rem"},forecastTable:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},forecastTh:{padding:"0.6rem 0.5rem",borderBottom:"2px solid #e0e0e0",textAlign:"center",fontWeight:"bold",background:"#f5f5f5",whiteSpace:"nowrap",fontSize:"0.8rem"},forecastTr:{borderBottom:"1px solid #e0e0e0"},forecastServiceCell:{padding:"0.5rem 0.75rem",fontWeight:"600",textAlign:"left",whiteSpace:"nowrap",color:"#333"},forecastTd:{padding:"0.5rem",textAlign:"center",whiteSpace:"nowrap"},forecastTotalCol:{background:"#f0f7ff",fontWeight:"600"},fcActual:{color:"#27ae60",fontWeight:"500"},fcOtb:{color:"#2980b9",fontWeight:"500"},fcPickup:{color:"#e67e22",fontSize:"0.85rem"},fcTotal:{color:"#555",fontWeight:"600"},summaryCards:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"1rem",marginBottom:"2rem"},card:{background:"white",padding:"1rem",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",textAlign:"center"},cardLabel:{fontSize:"0.9rem",color:"#666",marginBottom:"0.5rem"},cardValue:{fontSize:"1.5rem",fontWeight:"bold",color:"#333"},cardSubtext:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},cardOver:{background:"#ffebee",borderLeft:"4px solid #e74c3c"},cardUnder:{background:"#e8f5e9",borderLeft:"4px solid #27ae60"},section:{marginBottom:"2rem"},sectionTitle:{fontSize:"1.2rem",fontWeight:"bold",marginBottom:"1rem",color:"#333"},tableContainer:{overflowX:"auto",background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{padding:"0.75rem 0.5rem",borderBottom:"2px solid #e0e0e0",textAlign:"center",fontWeight:"bold",background:"#f5f5f5",whiteSpace:"nowrap"},supplierHeader:{textAlign:"left",minWidth:"150px"},budgetHeader:{background:"#e3f2fd"},spentHeader:{background:"#fff3e0"},remainingHeader:{background:"#e8f5e9"},statusHeader:{width:"50px"},tr:{borderBottom:"1px solid #e0e0e0"},td:{padding:"0.5rem",textAlign:"center",verticalAlign:"top"},supplierCell:{padding:"0.5rem",textAlign:"left",fontWeight:"500"},supplierPct:{fontSize:"0.75rem",color:"#888"},futureDate:{opacity:.6},invoicesCell:{display:"flex",flexDirection:"column",gap:"0.25rem",alignItems:"center"},invoiceBtn:{padding:"0.25rem 0.5rem",background:"#d4edda",border:"1px solid #28a745",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",whiteSpace:"nowrap",color:"#155724"},creditNoteBtn:{background:"#ffebee",borderColor:"#c62828",color:"#c62828"},poBtn:{padding:"0.25rem 0.5rem",background:"#e3f2fd",border:"1px dashed #42a5f5",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontStyle:"italic",color:"#1565c0",whiteSpace:"nowrap"},emptyCell:{color:"#ccc"},clickableCell:{cursor:"pointer"},budgetCell:{padding:"0.5rem",background:"#e3f2fd",fontWeight:"500"},spentCell:{padding:"0.5rem",background:"#fff3e0"},orderedHeader:{textAlign:"center"},orderedCell:{padding:"0.5rem",background:"#e3f2fd",textAlign:"center",color:"#1565c0",fontStyle:"italic",fontSize:"0.85rem"},remainingCell:{padding:"0.5rem",background:"#e8f5e9",fontWeight:"500"},overBudget:{background:"#ffebee",color:"#c62828"},statusCell:{padding:"0.5rem",textAlign:"center"},statusBadge:{display:"inline-block",width:"24px",height:"24px",borderRadius:"50%",lineHeight:"24px",textAlign:"center",fontWeight:"bold"},statusUnder:{background:"#c8e6c9",color:"#2e7d32"},statusOnTrack:{background:"#fff9c4",color:"#f57f17"},statusOver:{background:"#ffcdd2",color:"#c62828"},footerRow:{background:"#f5f5f5",fontWeight:"500"},footerLabel:{padding:"0.5rem",textAlign:"left",fontWeight:"bold",fontSize:"0.85rem"},footerTd:{padding:"0.5rem",textAlign:"center",fontSize:"0.85rem"},chartContainer:{height:"300px",background:"white",padding:"1rem",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},snapshotBtn:{padding:"0.75rem 1.5rem",background:"#3498db",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.95rem",fontWeight:"600"},snapshotInfoBar:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.5rem 0.75rem",background:"#f0f7ff",borderRadius:"6px",fontSize:"0.85rem",color:"#555",marginBottom:"0.75rem",marginTop:"0.75rem"},resnapshotBtn:{background:"none",border:"1px solid #aaa",borderRadius:"4px",padding:"0.25rem 0.5rem",cursor:"pointer",fontSize:"0.8rem",color:"#666"},overrideTableContainer:{background:"white",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",marginBottom:"0.75rem",overflow:"hidden"},overrideSectionHeader:{padding:"0.5rem 0.75rem",fontSize:"0.85rem",fontWeight:"600",color:"#555",borderBottom:"1px solid #e0e0e0",background:"#fafafa"},spendInput:{width:"65px",textAlign:"center",border:"1px solid #ddd",borderRadius:"3px",padding:"3px 4px",fontSize:"0.8rem"},spendInputOverridden:{fontWeight:"bold",borderColor:"#3498db",background:"#f0f7ff"},stepperCell:{display:"flex",alignItems:"center",justifyContent:"center",gap:"4px"},stepperBtn:{width:"22px",height:"22px",border:"1px solid #ccc",borderRadius:"3px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.85rem",display:"flex",alignItems:"center",justifyContent:"center",padding:0,lineHeight:"1"},overriddenValue:{fontWeight:"bold",textDecoration:"underline"},deleteOverrideBtn:{background:"none",border:"none",color:"#e74c3c",cursor:"pointer",fontSize:"0.85rem",padding:"0 2px",lineHeight:"1"},saveOverrideBtn:{padding:"0.25rem 0.75rem",background:"#27ae60",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontWeight:"600"},discardBtn:{padding:"0.25rem 0.75rem",background:"#f0f0f0",color:"#666",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},spreadCostBtnActive:{padding:"0.5rem 1rem",background:"#e3f2fd",border:"1px solid #42a5f5",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:500,color:"#1565c0",boxShadow:"0 0 0 2px rgba(66,165,245,0.3)"},selectModeHint:{padding:"0.4rem 0.75rem",background:"#e3f2fd",borderRadius:"4px",color:"#1565c0",fontSize:"0.8rem"},invoiceBtnSelectMode:{cursor:"crosshair",boxShadow:"0 0 0 2px rgba(66,165,245,0.5)",border:"2px solid #42a5f5"},addDistributionBtn:{padding:"0.4rem 0.75rem",background:"none",border:"1px dashed #aaa",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontWeight:500,color:"#666"},distributionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.6rem 0.75rem",background:"#f5f5f5",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},distributionSummary:{fontSize:"0.8rem",color:"#666",fontWeight:400}},Au=n=>n.toISOString().split("T")[0],XP=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Au(t),end:Au(r)}},Afe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()},BK="gp-report-from-date",IK="gp-report-to-date",Tfe=()=>{const n=sessionStorage.getItem(BK),e=sessionStorage.getItem(IK);if(n&&e)return{from:n,to:e};const t=new Date;t.setDate(t.getDate()-1);const r=new Date(t);return r.setDate(t.getDate()-30),{from:Au(r),to:Au(t)}};function Ffe(){var Le,rt,$e,ce,Je,jt,ct;const{token:n}=gn(),e=Tfe(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(""),[d,c]=k.useState("custom"),[u,f]=k.useState(e.from),[p,g]=k.useState(e.to);k.useEffect(()=>{sessionStorage.setItem(BK,u),sessionStorage.setItem(IK,p)},[u,p]);const m=Afe(),[y,v]=k.useState({wastage:!1,transfer:!0,staffFood:!0,manualAdjustment:!0,disputes:!0,cdDeductions:!0,cdReallocations:!0}),x=t!==u||i!==p,w=()=>{f(t),g(i)};k.useEffect(()=>{if(a){const[Se,ot]=a.split("-").map(Number),ut=XP(Se,ot);r(ut.start),o(ut.end),f(ut.start),g(ut.end)}},[a]);const S=Se=>{r(Se),Se>i&&o(Se),l(""),c("custom")},_=Se=>{o(Se),Se{l(Se),c(Se?"month":"custom")},C=()=>{const Se=new Date;Se.setDate(Se.getDate()-1);const ot=new Date(Se);ot.setDate(Se.getDate()-30);const ut=Au(ot),Ot=Au(Se);r(ut),o(Ot),f(ut),g(Ot),l(""),c("last30")},T=()=>{const Se=new Date,ot=`${Se.getFullYear()}-${Se.getMonth()}`,ut=XP(Se.getFullYear(),Se.getMonth());r(ut.start),o(ut.end),f(ut.start),g(ut.end),l(ot),c("month")},F=()=>{const Se=new Date,ot=new Date(Se.getFullYear(),Se.getMonth()-1,1),ut=`${ot.getFullYear()}-${ot.getMonth()}`,Ot=XP(ot.getFullYear(),ot.getMonth());r(Ot.start),o(Ot.end),f(Ot.start),g(Ot.end),l(ut),c("month")},A=()=>{const Se=new Date,ot=Se.getDay(),ut=new Date(Se);ut.setDate(Se.getDate()-(ot===0?6:ot-1));const Ot=new Date;Ot.setDate(Ot.getDate()-1);const An=Au(ut),on=Au(Ot);r(An),o(on),f(An),g(on),l(""),c("week")},D=()=>{const Se=new Date,ot=Se.getDay(),ut=new Date(Se);ut.setDate(Se.getDate()-(ot===0?6:ot-1)-7);const Ot=new Date(ut);Ot.setDate(ut.getDate()+6);const An=Au(ut),on=Au(Ot);r(An),o(on),f(An),g(on),l(""),c("week")},P=()=>{if(d==="last30")return"Last 30 Days: ";if(d==="week")return"Week: ";if(d==="month"&&a){const[Se,ot]=a.split("-").map(Number);return`Month of ${new Date(Se,ot,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},{data:L,isLoading:W,error:O}=Oe({queryKey:["gp-range",u,p],queryFn:async()=>{const Se=await fetch(`/api/reports/gp/range?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!Se.ok)throw new Error("Failed to fetch GP data");return Se.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:U}=Oe({queryKey:["gp-daily",u,p],queryFn:async()=>{const Se=await fetch(`/api/reports/gp/daily?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!Se.ok)throw new Error("Failed to fetch chart data");return Se.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:M,isLoading:I}=Oe({queryKey:["gp-top-sellers",u,p],queryFn:async()=>{const Se=await fetch(`/api/reports/gp/top-sellers?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});return Se.ok?Se.json():{from_date:u,to_date:p,source:"newbook",categories:[],top_by_qty:[],top_by_revenue:[],package_favorites:[],total_charges_processed:0,total_items_aggregated:0}},staleTime:5*60*1e3,gcTime:30*60*1e3}),H=(Se,ot=!1)=>{const ut=Number(Se);return ut<0&&ot?`-£${Math.abs(ut).toFixed(2)} CR`:`£${ut.toFixed(2)}`},z=()=>{var Ai,Ks;if(!((Ai=U==null?void 0:U.data)!=null&&Ai.length))return null;const Se=500,ot=200,ut={top:20,right:20,bottom:30,left:50},Ot=Se-ut.left-ut.right,An=ot-ut.top-ut.bottom,on=U.data,Ke=Math.max(...on.map(un=>Math.max(un.net_sales,un.net_purchases)),1),Rt=un=>ut.left+un/(on.length-1||1)*Ot,vt=un=>ut.top+An-un/Ke*An,Cr=on.map((un,Fr)=>`${Fr===0?"M":"L"} ${Rt(Fr)} ${vt(un.net_sales)}`).join(" "),Qt=on.map((un,Fr)=>`${Fr===0?"M":"L"} ${Rt(Fr)} ${vt(un.net_purchases)}`).join(" "),Ci=[0,Ke/2,Ke].map(un=>({value:un,y:vt(un),label:`£${(un/1e3).toFixed(un>=1e3?0:1)}k`})),Lr=[{index:0,label:new Date(on[0].date).toLocaleDateString("en-GB",{day:"numeric",month:"short"})},{index:Math.floor(on.length/2),label:new Date((Ks=on[Math.floor(on.length/2)])==null?void 0:Ks.date).toLocaleDateString("en-GB",{day:"numeric",month:"short"})},{index:on.length-1,label:new Date(on[on.length-1].date).toLocaleDateString("en-GB",{day:"numeric",month:"short"})}],Gs=[];return on.forEach((un,Fr)=>{new Date(un.date).getDay()===1&&Fr>0&&Gs.push(Fr)}),s.jsxs("div",{style:Ee.chartContainer,children:[s.jsx("h4",{style:Ee.chartTitle,children:"Daily Sales & Purchases"}),s.jsxs("svg",{width:Se,height:ot,style:Ee.chartSvg,children:[Ci.map((un,Fr)=>s.jsxs("g",{children:[s.jsx("line",{x1:ut.left,y1:un.y,x2:Se-ut.right,y2:un.y,stroke:"#eee",strokeDasharray:"4,4"}),s.jsx("text",{x:ut.left-5,y:un.y+4,textAnchor:"end",fontSize:"10",fill:"#666",children:un.label})]},Fr)),Gs.map((un,Fr)=>s.jsx("line",{x1:Rt(un),y1:ut.top,x2:Rt(un),y2:ot-ut.bottom,stroke:"#ccc",strokeDasharray:"4,4"},`week-${Fr}`)),Lr.map((un,Fr)=>s.jsx("text",{x:Rt(un.index),y:ot-8,textAnchor:"middle",fontSize:"10",fill:"#666",children:un.label},Fr)),s.jsx("path",{d:Cr,fill:"none",stroke:"#28a745",strokeWidth:"2"}),s.jsx("path",{d:Qt,fill:"none",stroke:"#dc3545",strokeWidth:"2"})]}),s.jsxs("div",{style:Ee.chartLegend,children:[s.jsxs("span",{style:Ee.legendItem,children:[s.jsx("span",{style:{...Ee.legendColor,background:"#28a745"}})," Net Sales"]}),s.jsxs("span",{style:Ee.legendItem,children:[s.jsx("span",{style:{...Ee.legendColor,background:"#dc3545"}})," Net Purchases"]})]})]})};if(W)return s.jsx("div",{style:Ee.loading,children:"Loading GP data..."});if(O)return s.jsxs("div",{style:Ee.error,children:["Error loading GP data: ",O.message]});const{period_label:G="",net_food_sales:te=0,net_food_purchases:re=0,gross_profit:me=0,gross_profit_percent:J=0,wastage_total:ne=null,transfer_total:ye=null,staff_food_total:ke=null,manual_adjustment_total:Ye=null,disputes_total:De=null,cd_deductions_total:qe=null,cd_reallocations_total:ue=null}=L||{},Ze=me<0,ee=ne!==null&&ne>0,Z=ye!==null&&ye>0,ge=ke!==null&&ke>0,Te=Ye!==null&&Ye>0,Be=De!==null&&De>0,he=qe!==null&&qe!==0,He=ue!==null&&ue!==0,Ge=ee||Z||ge||Te||Be||he||He,ae=Number(te)||0,K=Number(re)||0,de=Number(qe)||0,Y=Number(ue)||0,Q=()=>{let Se=0;return y.cdDeductions&&he&&(Se+=de),y.cdReallocations&&He&&(Se+=Y),Se},X=()=>{let Se=0;return y.wastage&&ee&&(Se+=Number(ne)||0),y.transfer&&Z&&(Se+=Number(ye)||0),y.staffFood&&ge&&(Se+=Number(ke)||0),y.manualAdjustment&&Te&&(Se+=Number(Ye)||0),y.disputes&&Be&&(Se+=Number(De)||0),Se},pe=Q(),we=X(),Ne=K+pe,st=we>0||pe!==0,Ve=ae>0?(ae-Ne+we)/ae*100:0,Re=Se=>{v(ot=>({...ot,[Se]:!ot[Se]}))};return s.jsxs("div",{children:[s.jsx("div",{style:Ee.header,children:s.jsx("h2",{style:Ee.title,children:"Kitchen Flash Report"})}),s.jsxs("div",{style:Ee.dateControls,children:[s.jsxs("div",{style:Ee.dateRow,children:[s.jsxs("div",{style:Ee.dateField,children:[s.jsx("label",{style:Ee.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:t,onChange:Se=>S(Se.target.value),style:Ee.dateInput})]}),s.jsxs("div",{style:Ee.dateField,children:[s.jsx("label",{style:Ee.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:i,onChange:Se=>_(Se.target.value),style:Ee.dateInput})]}),s.jsxs("div",{style:Ee.dateField,children:[s.jsx("label",{style:Ee.dateLabel,children:"Month"}),s.jsxs("select",{value:a,onChange:Se=>b(Se.target.value),style:Ee.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),m.map(Se=>s.jsx("option",{value:`${Se.year}-${Se.month}`,children:Se.label},`${Se.year}-${Se.month}`))]})]})]}),s.jsxs("div",{style:Ee.presetRow,children:[s.jsx("button",{onClick:C,style:Ee.presetBtn,children:"Last 30 Days"}),s.jsx("button",{onClick:A,style:Ee.presetBtn,children:"This Week"}),s.jsx("button",{onClick:D,style:Ee.presetBtn,children:"Last Week"}),s.jsx("button",{onClick:T,style:Ee.presetBtn,children:"This Month"}),s.jsx("button",{onClick:F,style:Ee.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:w,disabled:!x,style:{...Ee.generateBtn,...x?{}:Ee.generateBtnDisabled},children:x?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:Ee.periodLabel,children:[P(),G]}),s.jsxs("div",{style:Ee.mainContent,children:[s.jsxs("div",{style:Ee.sectionContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Gross Profit Estimate"}),s.jsxs("div",{style:Ee.calculationContainer,children:[s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Net Food Sales"}),s.jsx("span",{style:Ee.calcValue,children:H(te)})]}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Net Food Purchases"}),s.jsx("span",{style:Ee.calcValue,children:H(re)})]}),s.jsx("div",{style:Ee.divider}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabelBold,children:"Gross Profit"}),s.jsx("span",{style:{...Ee.calcValueBold,...Ze?Ee.negativeValue:Ee.positiveValue},children:H(me)})]}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabelBold,children:"Gross Profit %"}),s.jsxs("span",{style:{...Ee.calcValueBold,...Ze?Ee.negativeValue:Ee.positiveValue},children:[Number(J).toFixed(1),"%"]})]}),Ge&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:Ee.wastageSection}),s.jsx("div",{style:Ee.allowancesHeader,children:"Adjustments"}),he&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.cdDeductions,onChange:()=>Re("cdDeductions")}),s.jsx("span",{children:"Distributed Deductions"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#2e7d32"},children:H(qe||0)})]}),He&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.cdReallocations,onChange:()=>Re("cdReallocations")}),s.jsx("span",{children:"Distributed Reallocations"})]}),s.jsxs("span",{style:{...Ee.calcValue,color:"#e65100"},children:["+",H(ue||0)]})]}),ee&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.wastage,onChange:()=>Re("wastage")}),s.jsx("span",{children:"Wastage"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#e74c3c"},children:H(ne||0)})]}),Z&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.transfer,onChange:()=>Re("transfer")}),s.jsx("span",{children:"Transfers"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#3498db"},children:H(ye||0)})]}),ge&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.staffFood,onChange:()=>Re("staffFood")}),s.jsx("span",{children:"Staff Food"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#9b59b6"},children:H(ke||0)})]}),Te&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.manualAdjustment,onChange:()=>Re("manualAdjustment")}),s.jsx("span",{children:"Manual Adjustments"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#34495e"},children:H(Ye||0)})]}),Be&&s.jsxs("div",{style:Ee.allowanceRow,children:[s.jsxs("label",{style:Ee.allowanceCheckbox,children:[s.jsx("input",{type:"checkbox",checked:y.disputes,onChange:()=>Re("disputes")}),s.jsx("span",{children:"Open Disputes"})]}),s.jsx("span",{style:{...Ee.calcValue,color:"#e67e22"},children:H(De||0)})]}),s.jsx("div",{style:Ee.divider}),pe!==0&&s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Adjusted Purchases"}),s.jsx("span",{style:Ee.calcValue,children:H(Ne)})]}),we>0&&s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabel,children:"Selected Allowances"}),s.jsx("span",{style:{...Ee.calcValue,color:"#27ae60"},children:H(we)})]}),s.jsxs("div",{style:Ee.calcRow,children:[s.jsx("span",{style:Ee.calcLabelBold,children:"Adjusted GP %"}),s.jsxs("span",{style:{...Ee.calcValueBold,color:st?"#27ae60":"#999"},children:[Ve.toFixed(1),"%"]})]})]})]})]}),s.jsx("div",{style:Ee.sectionContainer,children:z()})]}),s.jsxs("div",{style:Ee.breakdownRow,children:[s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Supplier Breakdown"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Supplier"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Purchases"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"%"})]})}),s.jsx("tbody",{children:(Le=L==null?void 0:L.supplier_breakdown)!=null&&Le.length?L.supplier_breakdown.map((Se,ot)=>{const ut=Se.net_purchases<0;return s.jsxs("tr",{style:ut?{background:"#d4edda"}:{},children:[s.jsxs("td",{style:Ee.tableCell,children:[Se.supplier_name,ut&&s.jsx("span",{style:{color:"#28a745",fontWeight:"bold",marginLeft:"0.5rem"},children:"(CR)"})]}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",...ut?{color:"#28a745",fontWeight:"bold"}:{}},children:H(Se.net_purchases,!0)}),s.jsxs("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:[Number(Se.percentage).toFixed(1),"%"]})]},Se.supplier_id||`unknown-${ot}`)}):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No supplier data"})})})]})]}),s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Revenue Breakdown"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"GL Account"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Revenue"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"%"})]})}),s.jsx("tbody",{children:(rt=L==null?void 0:L.gl_account_breakdown)!=null&&rt.length?L.gl_account_breakdown.map(Se=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:Se.gl_account_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:H(Se.net_revenue)}),s.jsxs("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:[Number(Se.percentage).toFixed(1),"%"]})]},Se.gl_account_id)):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No revenue data"})})})]})]})]}),I?s.jsx("div",{style:{...Ee.breakdownContainer,textAlign:"center",marginBottom:"1.5rem"},children:s.jsx("div",{style:{color:"#666",padding:"2rem"},children:"Loading top sellers..."})}):(M==null?void 0:M.source)==="sambapos"&&(($e=M==null?void 0:M.categories)==null?void 0:$e.length)>0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Ee.topSellersSection,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Quantity"}),s.jsx("div",{style:Ee.categoryGrid,children:M.categories.map(Se=>s.jsxs("div",{style:Ee.categoryColumn,children:[s.jsx("h4",{style:Ee.categoryHeader,children:Se.category}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:Se.top_by_qty.length>0?Se.top_by_qty.map(ot=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:ot.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:ot.qty})]},ot.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:2,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]},Se.category))})]}),s.jsxs("div",{style:Ee.topSellersSection,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Gross Revenue"}),s.jsx("div",{style:Ee.categoryGrid,children:M.categories.map(Se=>s.jsxs("div",{style:Ee.categoryColumn,children:[s.jsx("h4",{style:Ee.categoryHeader,children:Se.category}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Gross"})]})}),s.jsx("tbody",{children:Se.top_by_revenue.length>0?Se.top_by_revenue.map(ot=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:ot.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:H(ot.revenue)})]},ot.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:2,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]},Se.category))})]})]}):(M==null?void 0:M.source)==="sambapos"&&(!(M!=null&&M.categories)||M.categories.length===0)?s.jsxs("div",{style:{...Ee.breakdownContainer,textAlign:"center",marginBottom:"1.5rem"},children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers"}),s.jsxs("p",{style:{color:"#666",margin:"2rem 0"},children:["No categories configured. ",s.jsx("a",{href:"/sambapos",style:{color:"#e94560"},children:"Configure SambaPOS categories"})," to see top sellers by category."]})]}):s.jsxs("div",{style:Ee.breakdownRow,children:[s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Quantity"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"#"}),s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Revenue"})]})}),s.jsx("tbody",{children:(ce=M==null?void 0:M.top_by_qty)!=null&&ce.length?M.top_by_qty.map((Se,ot)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Ee.tableCell,color:"#999",width:"30px"},children:ot+1}),s.jsx("td",{style:Ee.tableCell,children:Se.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:Se.qty}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:H(Se.revenue)})]},Se.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No top sellers data"})})})]})]}),s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Top Sellers by Gross Revenue"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"#"}),s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Gross"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:(Je=M==null?void 0:M.top_by_revenue)!=null&&Je.length?M.top_by_revenue.map((Se,ot)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Ee.tableCell,color:"#999",width:"30px"},children:ot+1}),s.jsx("td",{style:Ee.tableCell,children:Se.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:H(Se.revenue)}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:Se.qty})]},Se.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No top sellers data"})})})]})]}),s.jsxs("div",{style:Ee.breakdownContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Package Guest Favorites"}),s.jsxs("table",{style:Ee.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"#"}),s.jsx("th",{style:Ee.tableHeader,children:"Item"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:(jt=M==null?void 0:M.package_favorites)!=null&&jt.length?M.package_favorites.map((Se,ot)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Ee.tableCell,color:"#999",width:"30px"},children:ot+1}),s.jsx("td",{style:Ee.tableCell,children:Se.item_name}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:Se.qty})]},Se.item_name)):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No package data"})})})]})]})]}),s.jsxs("div",{style:Ee.dailyTableContainer,children:[s.jsx("h3",{style:Ee.sectionTitle,children:"Daily Breakdown"}),s.jsx("div",{style:Ee.tableWrapper,children:s.jsxs("table",{style:Ee.dailyTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ee.tableHeader,children:"Date"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Sales"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Net Purchases"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Occupancy"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Lunch Covers"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Dinner Covers"}),s.jsx("th",{style:{...Ee.tableHeader,textAlign:"right"},children:"Total Covers"})]})}),s.jsx("tbody",{children:(ct=U==null?void 0:U.data)!=null&&ct.length?[...U.data].reverse().map(Se=>s.jsxs("tr",{children:[s.jsx("td",{style:Ee.tableCell,children:new Date(Se.date).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:H(Se.net_sales)}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace"},children:H(Se.net_purchases)}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.occupancy??"—"}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.lunch_covers??"—"}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.dinner_covers??"—"}),s.jsx("td",{style:{...Ee.tableCell,textAlign:"right",fontFamily:"monospace",color:"#999"},children:Se.total_covers??"—"})]},Se.date)):s.jsx("tr",{children:s.jsx("td",{colSpan:7,style:{...Ee.tableCell,textAlign:"center",color:"#999"},children:"No daily data"})})})]})})]})]})}const Ee={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},header:{marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},mainContent:{display:"flex",gap:"1.5rem",flexWrap:"wrap",alignItems:"stretch"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem",flex:"1 1 auto",minWidth:"300px"},sectionTitle:{margin:"0 0 1.5rem 0",color:"#1a1a2e"},calculationContainer:{maxWidth:"400px"},calcRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 0"},calcLabel:{color:"#555",fontSize:"1rem"},calcValue:{fontSize:"1rem",fontFamily:"monospace"},calcLabelBold:{color:"#1a1a2e",fontSize:"1.1rem",fontWeight:"bold"},calcValueBold:{fontSize:"1.2rem",fontWeight:"bold",fontFamily:"monospace"},divider:{borderTop:"2px solid #dee2e6",margin:"0.5rem 0"},wastageSection:{borderTop:"1px dashed #e67e22",margin:"0.75rem 0 0.5rem 0"},allowancesHeader:{fontSize:"0.9rem",fontWeight:600,color:"#666",marginBottom:"0.5rem",textTransform:"uppercase",letterSpacing:"0.5px"},allowanceRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.4rem 0"},allowanceCheckbox:{display:"flex",alignItems:"center",gap:"0.5rem",cursor:"pointer",fontSize:"0.95rem",color:"#444"},positiveValue:{color:"#155724"},negativeValue:{color:"#dc3545"},chartContainer:{width:"100%"},chartTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1rem",fontWeight:600},chartSvg:{display:"block",maxWidth:"100%"},chartLegend:{display:"flex",gap:"1.5rem",marginTop:"0.75rem",justifyContent:"center"},legendItem:{display:"flex",alignItems:"center",gap:"0.4rem",fontSize:"0.85rem",color:"#555"},legendColor:{width:"12px",height:"12px",borderRadius:"2px",display:"inline-block"},breakdownRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1.5rem"},breakdownContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",flex:"1 1 300px",minWidth:"280px"},breakdownTable:{width:"100%",borderCollapse:"collapse"},tableHeader:{textAlign:"left",padding:"0.75rem 0.5rem",borderBottom:"2px solid #dee2e6",color:"#1a1a2e",fontWeight:600,fontSize:"0.85rem"},tableCell:{padding:"0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},dailyTableContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem"},tableWrapper:{overflowX:"auto"},dailyTable:{width:"100%",borderCollapse:"collapse",minWidth:"700px"},topSellersSection:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1.5rem"},categoryGrid:{display:"flex",gap:"1rem",flexWrap:"wrap"},categoryColumn:{flex:"1 1 180px",minWidth:"160px",maxWidth:"250px"},categoryHeader:{margin:"0 0 0.75rem 0",padding:"0.5rem 0.75rem",background:"#f8f9fa",borderRadius:"6px",fontSize:"0.95rem",fontWeight:600,color:"#1a1a2e",borderLeft:"3px solid #e94560"}},Tu=n=>n.toISOString().split("T")[0],YP=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Tu(t),end:Tu(r)}},UN=n=>n?n.split(` -`)[0].trim():"",Dfe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()},MK="purchases-report-from-date",zK="purchases-report-to-date",Efe=()=>{const n=sessionStorage.getItem(MK),e=sessionStorage.getItem(zK);if(n&&e)return{from:n,to:e};const t=new Date;t.setDate(t.getDate()-1);const r=new Date(t);return r.setDate(t.getDate()-30),{from:Tu(r),to:Tu(t)}},HN=["#e94560","#0ea5e9","#22c55e","#f59e0b","#8b5cf6","#ec4899","#14b8a6","#f97316","#6366f1","#84cc16"];function Pfe(){var G,te,re,me;const{token:n}=gn(),e=Efe(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(""),[d,c]=k.useState("custom"),[u,f]=k.useState(e.from),[p,g]=k.useState(e.to),[m,y]=k.useState(null);k.useEffect(()=>{sessionStorage.setItem(MK,u),sessionStorage.setItem(zK,p)},[u,p]);const v=Dfe(),x=t!==u||i!==p,w=()=>{f(t),g(i)};k.useEffect(()=>{if(a){const[J,ne]=a.split("-").map(Number),ye=YP(J,ne);r(ye.start),o(ye.end),f(ye.start),g(ye.end)}},[a]);const S=J=>{r(J),J>i&&o(J),l(""),c("custom")},_=J=>{o(J),J{l(J),c(J?"month":"custom")},C=()=>{const J=new Date;J.setDate(J.getDate()-1);const ne=new Date(J);ne.setDate(J.getDate()-30);const ye=Tu(ne),ke=Tu(J);r(ye),o(ke),f(ye),g(ke),l(""),c("last30")},T=()=>{const J=new Date,ne=`${J.getFullYear()}-${J.getMonth()}`,ye=YP(J.getFullYear(),J.getMonth());r(ye.start),o(ye.end),f(ye.start),g(ye.end),l(ne),c("month")},F=()=>{const J=new Date,ne=new Date(J.getFullYear(),J.getMonth()-1,1),ye=`${ne.getFullYear()}-${ne.getMonth()}`,ke=YP(ne.getFullYear(),ne.getMonth());r(ke.start),o(ke.end),f(ke.start),g(ke.end),l(ye),c("month")},A=()=>{const J=new Date,ne=J.getDay(),ye=new Date(J);ye.setDate(J.getDate()-(ne===0?6:ne-1));const ke=new Date;ke.setDate(ke.getDate()-1);const Ye=Tu(ye),De=Tu(ke);r(Ye),o(De),f(Ye),g(De),l(""),c("week")},D=()=>{const J=new Date,ne=J.getDay(),ye=new Date(J);ye.setDate(J.getDate()-(ne===0?6:ne-1)-7);const ke=new Date(ye);ke.setDate(ye.getDate()+6);const Ye=Tu(ye),De=Tu(ke);r(Ye),o(De),f(Ye),g(De),l(""),c("week")},P=()=>{if(d==="last30")return"Last 30 Days: ";if(d==="week")return"Week: ";if(d==="month"&&a){const[J,ne]=a.split("-").map(Number);return`Month of ${new Date(J,ne,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},{data:L,isLoading:W,error:O}=Oe({queryKey:["purchases-summary",u,p],queryFn:async()=>{const J=await fetch(`/api/reports/purchases/summary?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!J.ok)throw new Error("Failed to fetch purchases summary");return J.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:U}=Oe({queryKey:["purchases-daily-supplier",u,p],queryFn:async()=>{const J=await fetch(`/api/reports/purchases/daily-by-supplier?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!J.ok)throw new Error("Failed to fetch chart data");return J.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:M}=Oe({queryKey:["purchases-top-items",u,p,m],queryFn:async()=>{let J=`/api/reports/purchases/top-items?from_date=${u}&to_date=${p}`;m!==null&&(J+=`&supplier_id=${m}`);const ne=await fetch(J,{headers:{Authorization:`Bearer ${n}`}});if(!ne.ok)throw new Error("Failed to fetch top items");return ne.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),I=(J,ne=!1)=>{const ye=Number(J);return ye<0&&ne?`-£${Math.abs(ye).toFixed(2)} CR`:`£${ye.toFixed(2)}`},H=J=>{const ne=new Date(J),ye=ne.getDay(),ke=ne.getDate()-ye+(ye===0?-6:1);return new Date(ne.setDate(ke)).toISOString().split("T")[0]},z=()=>{var He,Ge;if(!((He=U==null?void 0:U.data)!=null&&He.length)||!((Ge=U==null?void 0:U.suppliers)!=null&&Ge.length))return s.jsx("div",{style:Et.noData,children:"No chart data available"});const J=650,ne=280,ye={top:20,right:20,bottom:40,left:60},ke=J-ye.left-ye.right,Ye=ne-ye.top-ye.bottom,De=U.suppliers,qe={};De.forEach((ae,K)=>{qe[ae]=HN[K%HN.length]});const ue={};U.data.forEach(ae=>{const K=H(ae.date);ue[K]||(ue[K]={},De.forEach(de=>{ue[K][de]=0})),ue[K][ae.supplier_name]=(ue[K][ae.supplier_name]||0)+(Number(ae.net_purchases)||0)});const Ze=Object.keys(ue).sort();if(Ze.length===0)return s.jsx("div",{style:Et.noData,children:"No chart data available"});let ee=1;Ze.forEach(ae=>{De.forEach(K=>{const de=ue[ae][K]||0;de>ee&&(ee=de)})});const Z=ke/Ze.length,ge=Z*.8,Te=Math.min(ge/De.length,25),Be=ae=>ye.top+Ye-ae/ee*Ye,he=[0,ee/2,ee].map(ae=>({value:ae,y:Be(ae),label:`£${(Number(ae)/1e3).toFixed(Number(ae)>=1e3?0:1)}k`}));return s.jsxs("div",{style:Et.chartContainer,children:[s.jsx("h4",{style:Et.chartTitle,children:"Weekly Purchases by Supplier"}),s.jsxs("svg",{width:J,height:ne,style:Et.chartSvg,children:[he.map((ae,K)=>s.jsxs("g",{children:[s.jsx("line",{x1:ye.left,y1:ae.y,x2:J-ye.right,y2:ae.y,stroke:"#eee",strokeDasharray:"4,4"}),s.jsx("text",{x:ye.left-5,y:ae.y+4,textAnchor:"end",fontSize:"10",fill:"#666",children:ae.label})]},K)),Ze.map((ae,K)=>{const de=ye.left+(K+.5)*Z,Y=de-De.length*Te/2;return s.jsxs("g",{children:[s.jsx("text",{x:de,y:ne-8,textAnchor:"middle",fontSize:"9",fill:"#666",children:new Date(ae).toLocaleDateString("en-GB",{day:"numeric",month:"short"})}),De.map((Q,X)=>{const pe=ue[ae][Q]||0;if(pe<=0)return null;const we=pe/ee*Ye,Ne=Y+X*Te;return s.jsx("rect",{x:Ne,y:ye.top+Ye-we,width:Te-1,height:we,fill:qe[Q]},`${ae}-${Q}`)})]},ae)})]}),s.jsx("div",{style:Et.chartLegend,children:De.map(ae=>s.jsxs("span",{style:Et.legendItem,children:[s.jsx("span",{style:{...Et.legendColor,background:qe[ae]}}),ae]},ae))})]})};return W?s.jsx("div",{style:Et.loading,children:"Loading purchases data..."}):O?s.jsxs("div",{style:Et.error,children:["Error loading purchases data: ",O.message]}):s.jsxs("div",{children:[s.jsx("div",{style:Et.header,children:s.jsx("h2",{style:Et.title,children:"Purchases Report"})}),s.jsxs("div",{style:Et.dateControls,children:[s.jsxs("div",{style:Et.dateRow,children:[s.jsxs("div",{style:Et.dateField,children:[s.jsx("label",{style:Et.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:t,onChange:J=>S(J.target.value),style:Et.dateInput})]}),s.jsxs("div",{style:Et.dateField,children:[s.jsx("label",{style:Et.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:i,onChange:J=>_(J.target.value),style:Et.dateInput})]}),s.jsxs("div",{style:Et.dateField,children:[s.jsx("label",{style:Et.dateLabel,children:"Month"}),s.jsxs("select",{value:a,onChange:J=>b(J.target.value),style:Et.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),v.map(J=>s.jsx("option",{value:`${J.year}-${J.month}`,children:J.label},`${J.year}-${J.month}`))]})]})]}),s.jsxs("div",{style:Et.presetRow,children:[s.jsx("button",{onClick:C,style:Et.presetBtn,children:"Last 30 Days"}),s.jsx("button",{onClick:A,style:Et.presetBtn,children:"This Week"}),s.jsx("button",{onClick:D,style:Et.presetBtn,children:"Last Week"}),s.jsx("button",{onClick:T,style:Et.presetBtn,children:"This Month"}),s.jsx("button",{onClick:F,style:Et.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:w,disabled:!x,style:{...Et.generateBtn,...x?{}:Et.generateBtnDisabled},children:x?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:Et.periodLabel,children:[P(),L==null?void 0:L.period_label]}),s.jsxs("div",{style:Et.mainContent,children:[s.jsxs("div",{style:Et.sectionContainer,children:[s.jsx("h3",{style:Et.sectionTitle,children:"Supplier Breakdown"}),s.jsxs("div",{style:Et.totalRow,children:[s.jsx("span",{children:"Total Purchases:"}),s.jsx("span",{style:{...Et.totalValue,...((L==null?void 0:L.total_purchases)||0)<0?{color:"#28a745"}:{}},children:I((L==null?void 0:L.total_purchases)||0,!0)})]}),s.jsxs("table",{style:Et.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Et.tableHeader,children:"Supplier"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Net Purchases"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"%"})]})}),s.jsx("tbody",{children:(G=L==null?void 0:L.supplier_breakdown)!=null&&G.length?L.supplier_breakdown.map((J,ne)=>{const ye=J.net_purchases<0;return s.jsxs("tr",{style:ye?{background:"#d4edda"}:{},children:[s.jsxs("td",{style:Et.tableCell,children:[J.supplier_name,ye&&s.jsx("span",{style:{color:"#28a745",fontWeight:"bold",marginLeft:"0.5rem"},children:"(CR)"})]}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",...ye?{color:"#28a745",fontWeight:"bold"}:{}},children:I(J.net_purchases,!0)}),s.jsxs("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace"},children:[Number(J.percentage).toFixed(1),"%"]})]},J.supplier_id||`unknown-${ne}`)}):s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Et.tableCell,textAlign:"center",color:"#999"},children:"No supplier data"})})})]})]}),s.jsx("div",{style:Et.sectionContainer,children:z()})]}),s.jsxs("div",{style:Et.topItemsFilterRow,children:[s.jsx("span",{style:Et.filterLabel,children:"Filter by Supplier:"}),s.jsxs("select",{value:m===null?"":m,onChange:J=>y(J.target.value===""?null:Number(J.target.value)),style:Et.supplierSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),(te=L==null?void 0:L.supplier_breakdown)==null?void 0:te.map(J=>s.jsx("option",{value:J.supplier_id??"",children:J.supplier_name},J.supplier_id??"unknown"))]})]}),s.jsxs("div",{style:Et.breakdownRow,children:[s.jsxs("div",{style:Et.breakdownContainer,children:[s.jsx("h3",{style:Et.sectionTitle,children:"Top 10 Line Items by Quantity"}),s.jsxs("table",{style:Et.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Et.tableHeader,children:"#"}),s.jsx("th",{style:Et.tableHeader,children:"Item"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Value"})]})}),s.jsx("tbody",{children:(re=M==null?void 0:M.top_by_quantity)!=null&&re.length?M.top_by_quantity.map((J,ne)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Et.tableCell,color:"#999",width:"30px"},children:ne+1}),s.jsx("td",{style:Et.tableCell,children:UN(J.description)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:Number(J.total_quantity).toFixed(1)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:I(J.total_value)})]},`qty-${ne}`)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Et.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]}),s.jsxs("div",{style:Et.breakdownContainer,children:[s.jsx("h3",{style:Et.sectionTitle,children:"Top 10 Line Items by Value"}),s.jsxs("table",{style:Et.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Et.tableHeader,children:"#"}),s.jsx("th",{style:Et.tableHeader,children:"Item"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Value"}),s.jsx("th",{style:{...Et.tableHeader,textAlign:"right"},children:"Qty"})]})}),s.jsx("tbody",{children:(me=M==null?void 0:M.top_by_value)!=null&&me.length?M.top_by_value.map((J,ne)=>s.jsxs("tr",{children:[s.jsx("td",{style:{...Et.tableCell,color:"#999",width:"30px"},children:ne+1}),s.jsx("td",{style:Et.tableCell,children:UN(J.description)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:I(J.total_value)}),s.jsx("td",{style:{...Et.tableCell,textAlign:"right",fontFamily:"monospace",color:"#666"},children:Number(J.total_quantity).toFixed(1)})]},`val-${ne}`)):s.jsx("tr",{children:s.jsx("td",{colSpan:4,style:{...Et.tableCell,textAlign:"center",color:"#999"},children:"No data"})})})]})]})]})]})}const Et={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},noData:{padding:"2rem",textAlign:"center",color:"#999"},header:{marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},mainContent:{display:"flex",gap:"1.5rem",flexWrap:"wrap",alignItems:"stretch"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem",flex:"1 1 auto",minWidth:"300px"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e"},totalRow:{display:"flex",justifyContent:"space-between",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",marginBottom:"1rem",fontWeight:600},totalValue:{fontFamily:"monospace",color:"#e94560"},breakdownTable:{width:"100%",borderCollapse:"collapse"},tableHeader:{textAlign:"left",padding:"0.75rem 0.5rem",borderBottom:"2px solid #dee2e6",color:"#1a1a2e",fontWeight:600,fontSize:"0.85rem"},tableCell:{padding:"0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},chartContainer:{width:"100%"},chartTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1rem",fontWeight:600},chartSvg:{display:"block",maxWidth:"100%"},chartLegend:{display:"flex",gap:"0.5rem 1rem",marginTop:"0.75rem",flexWrap:"wrap",justifyContent:"center",padding:"0.25rem",maxWidth:"450px",margin:"0.75rem auto 0"},legendItem:{display:"flex",alignItems:"center",gap:"0.25rem",fontSize:"0.7rem",color:"#555",whiteSpace:"nowrap"},legendColor:{width:"10px",height:"10px",borderRadius:"2px",display:"inline-block",flexShrink:0},breakdownRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1.5rem"},breakdownContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",flex:"1 1 300px",minWidth:"280px"},topItemsFilterRow:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem",padding:"0.75rem 1rem",background:"white",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},filterLabel:{fontSize:"0.9rem",color:"#555",fontWeight:500},supplierSelect:{padding:"0.5rem 0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.9rem",minWidth:"200px",cursor:"pointer"}},Fu=n=>n.toISOString().split("T")[0],QP=(n,e)=>{const t=new Date(n,e,1),r=new Date(n,e+1,0);return{start:Fu(t),end:Fu(r)}},Rfe=()=>{const n=[],e=new Date;for(let t=-12;t<=2;t++){const r=new Date(e.getFullYear(),e.getMonth()+t,1),i=r.toLocaleDateString("en-GB",{month:"long",year:"numeric"});n.push({label:i,year:r.getFullYear(),month:r.getMonth()})}return n.reverse()},OK="allowances-report-from-date",LK="allowances-report-to-date",Bfe=()=>{const n=sessionStorage.getItem(OK),e=sessionStorage.getItem(LK);if(n&&e)return{from:n,to:e};const t=new Date;t.setDate(t.getDate()-1);const r=new Date(t);return r.setDate(t.getDate()-30),{from:Fu(r),to:Fu(t)}},sd={wastage:"#e74c3c",transfer:"#3498db",staff_food:"#9b59b6",manual_adjustment:"#34495e"};function Ife(){var H;const{token:n}=gn(),e=Bfe(),[t,r]=k.useState(e.from),[i,o]=k.useState(e.to),[a,l]=k.useState(""),[d,c]=k.useState("custom"),[u,f]=k.useState(e.from),[p,g]=k.useState(e.to);k.useEffect(()=>{sessionStorage.setItem(OK,u),sessionStorage.setItem(LK,p)},[u,p]);const m=Rfe(),y=t!==u||i!==p,v=()=>{f(t),g(i)};k.useEffect(()=>{if(a){const[z,G]=a.split("-").map(Number),te=QP(z,G);r(te.start),o(te.end),f(te.start),g(te.end)}},[a]);const x=z=>{r(z),z>i&&o(z),l(""),c("custom")},w=z=>{o(z),z{l(z),c(z?"month":"custom")},_=()=>{const z=new Date;z.setDate(z.getDate()-1);const G=new Date(z);G.setDate(z.getDate()-30);const te=Fu(G),re=Fu(z);r(te),o(re),f(te),g(re),l(""),c("last30")},b=()=>{const z=new Date,G=`${z.getFullYear()}-${z.getMonth()}`,te=QP(z.getFullYear(),z.getMonth());r(te.start),o(te.end),f(te.start),g(te.end),l(G),c("month")},C=()=>{const z=new Date,G=new Date(z.getFullYear(),z.getMonth()-1,1),te=`${G.getFullYear()}-${G.getMonth()}`,re=QP(G.getFullYear(),G.getMonth());r(re.start),o(re.end),f(re.start),g(re.end),l(te),c("month")},T=()=>{const z=new Date,G=z.getDay(),te=new Date(z);te.setDate(z.getDate()-(G===0?6:G-1));const re=new Date;re.setDate(re.getDate()-1);const me=Fu(te),J=Fu(re);r(me),o(J),f(me),g(J),l(""),c("week")},F=()=>{const z=new Date,G=z.getDay(),te=new Date(z);te.setDate(z.getDate()-(G===0?6:G-1)-7);const re=new Date(te);re.setDate(te.getDate()+6);const me=Fu(te),J=Fu(re);r(me),o(J),f(me),g(J),l(""),c("week")},A=()=>{if(d==="last30")return"Last 30 Days: ";if(d==="week")return"Week: ";if(d==="month"&&a){const[z,G]=a.split("-").map(Number);return`Month of ${new Date(z,G,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}: `}else return"Custom Dates: "},{data:D,isLoading:P,error:L}=Oe({queryKey:["allowances-summary",u,p],queryFn:async()=>{const z=await fetch(`/api/reports/allowances/summary?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch allowances summary");return z.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:W}=Oe({queryKey:["allowances-daily",u,p],queryFn:async()=>{const z=await fetch(`/api/reports/allowances/daily?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch chart data");return z.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),{data:O}=Oe({queryKey:["disputes-period-summary",u,p],queryFn:async()=>{const z=await fetch(`/api/reports/disputes/period-summary?from_date=${u}&to_date=${p}`,{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch disputes summary");return z.json()},staleTime:5*60*1e3,gcTime:30*60*1e3}),U=z=>`£${Number(z).toFixed(2)}`,M=z=>{const G=new Date(z),te=G.getDay(),re=G.getDate()-te+(te===0?-6:1);return new Date(G.setDate(re)).toISOString().split("T")[0]},I=()=>{var ee;if(!((ee=W==null?void 0:W.data)!=null&&ee.length))return s.jsx("div",{style:Bt.noData,children:"No chart data available"});const z=550,G=250,te={top:20,right:20,bottom:40,left:60},re=z-te.left-te.right,me=G-te.top-te.bottom,J=[{key:"wastage",color:sd.wastage,label:"Wastage"},{key:"transfer",color:sd.transfer,label:"Transfers"},{key:"staff_food",color:sd.staff_food,label:"Staff Food"},{key:"manual_adjustment",color:sd.manual_adjustment,label:"Manual Adj."}],ne={};W.data.forEach(Z=>{const ge=M(Z.date);ne[ge]||(ne[ge]={wastage:0,transfer:0,staff_food:0,manual_adjustment:0}),ne[ge].wastage+=Number(Z.wastage)||0,ne[ge].transfer+=Number(Z.transfer)||0,ne[ge].staff_food+=Number(Z.staff_food)||0,ne[ge].manual_adjustment+=Number(Z.manual_adjustment)||0});const ye=Object.keys(ne).sort();if(ye.length===0)return s.jsx("div",{style:Bt.noData,children:"No chart data available"});let ke=1;ye.forEach(Z=>{J.forEach(ge=>{const Te=ne[Z][ge.key]||0;Te>ke&&(ke=Te)})});const Ye=re/ye.length,De=Ye*.8,qe=Math.min(De/J.length,25),ue=Z=>te.top+me-Z/ke*me,Ze=[0,ke/2,ke].map(Z=>({value:Z,y:ue(Z),label:`£${Number(Z).toFixed(0)}`}));return s.jsxs("div",{style:Bt.chartContainer,children:[s.jsx("h4",{style:Bt.chartTitle,children:"Weekly Allowances"}),s.jsxs("svg",{width:z,height:G,style:Bt.chartSvg,children:[Ze.map((Z,ge)=>s.jsxs("g",{children:[s.jsx("line",{x1:te.left,y1:Z.y,x2:z-te.right,y2:Z.y,stroke:"#eee",strokeDasharray:"4,4"}),s.jsx("text",{x:te.left-5,y:Z.y+4,textAnchor:"end",fontSize:"10",fill:"#666",children:Z.label})]},ge)),ye.map((Z,ge)=>{const Te=te.left+(ge+.5)*Ye,Be=Te-J.length*qe/2;return s.jsxs("g",{children:[s.jsx("text",{x:Te,y:G-8,textAnchor:"middle",fontSize:"9",fill:"#666",children:new Date(Z).toLocaleDateString("en-GB",{day:"numeric",month:"short"})}),J.map((he,He)=>{const Ge=ne[Z][he.key]||0;if(Ge<=0)return null;const ae=Ge/ke*me,K=Be+He*qe;return s.jsx("rect",{x:K,y:te.top+me-ae,width:qe-1,height:ae,fill:he.color},`${Z}-${he.key}`)})]},Z)})]}),s.jsx("div",{style:Bt.chartLegend,children:J.map(({key:Z,color:ge,label:Te})=>s.jsxs("span",{style:Bt.legendItem,children:[s.jsx("span",{style:{...Bt.legendColor,background:ge}}),Te]},Z))})]})};return P?s.jsx("div",{style:Bt.loading,children:"Loading allowances data..."}):L?s.jsxs("div",{style:Bt.error,children:["Error loading allowances data: ",L.message]}):s.jsxs("div",{children:[s.jsx("div",{style:Bt.header,children:s.jsx("h2",{style:Bt.title,children:"Allowances Report"})}),s.jsxs("div",{style:Bt.dateControls,children:[s.jsxs("div",{style:Bt.dateRow,children:[s.jsxs("div",{style:Bt.dateField,children:[s.jsx("label",{style:Bt.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:t,onChange:z=>x(z.target.value),style:Bt.dateInput})]}),s.jsxs("div",{style:Bt.dateField,children:[s.jsx("label",{style:Bt.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:i,onChange:z=>w(z.target.value),style:Bt.dateInput})]}),s.jsxs("div",{style:Bt.dateField,children:[s.jsx("label",{style:Bt.dateLabel,children:"Month"}),s.jsxs("select",{value:a,onChange:z=>S(z.target.value),style:Bt.monthSelect,children:[s.jsx("option",{value:"",children:"Custom Range"}),m.map(z=>s.jsx("option",{value:`${z.year}-${z.month}`,children:z.label},`${z.year}-${z.month}`))]})]})]}),s.jsxs("div",{style:Bt.presetRow,children:[s.jsx("button",{onClick:_,style:Bt.presetBtn,children:"Last 30 Days"}),s.jsx("button",{onClick:T,style:Bt.presetBtn,children:"This Week"}),s.jsx("button",{onClick:F,style:Bt.presetBtn,children:"Last Week"}),s.jsx("button",{onClick:b,style:Bt.presetBtn,children:"This Month"}),s.jsx("button",{onClick:C,style:Bt.presetBtn,children:"Last Month"}),s.jsx("button",{onClick:v,disabled:!y,style:{...Bt.generateBtn,...y?{}:Bt.generateBtnDisabled},children:y?"Generate Report":"Report Generated"})]})]}),s.jsxs("div",{style:Bt.periodLabel,children:[A(),D==null?void 0:D.period_label]}),s.jsxs("div",{style:Bt.mainContent,children:[s.jsxs("div",{style:Bt.sectionContainer,children:[s.jsx("h3",{style:Bt.sectionTitle,children:"Allowances Breakdown"}),s.jsxs("table",{style:Bt.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Bt.tableHeader,children:"Type"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Entries"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Total"})]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.wastage}}),"Wastage"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.wastage_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.wastage},children:U((D==null?void 0:D.wastage_total)||0)})]}),s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.transfer}}),"Transfers"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.transfer_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.transfer},children:U((D==null?void 0:D.transfer_total)||0)})]}),s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.staff_food}}),"Staff Food"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.staff_food_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.staff_food},children:U((D==null?void 0:D.staff_food_total)||0)})]}),s.jsxs("tr",{children:[s.jsxs("td",{style:Bt.tableCell,children:[s.jsx("span",{style:{...Bt.typeDot,background:sd.manual_adjustment}}),"Manual Adjustments"]}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace"},children:(D==null?void 0:D.manual_adjustment_count)||0}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",color:sd.manual_adjustment},children:U((D==null?void 0:D.manual_adjustment_total)||0)})]})]}),s.jsx("tfoot",{children:s.jsxs("tr",{style:{borderTop:"2px solid #dee2e6"},children:[s.jsx("td",{style:{...Bt.tableCell,fontWeight:"bold"},children:"Total"}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold"},children:((D==null?void 0:D.wastage_count)||0)+((D==null?void 0:D.transfer_count)||0)+((D==null?void 0:D.staff_food_count)||0)+((D==null?void 0:D.manual_adjustment_count)||0)}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:"bold",color:"#27ae60"},children:U((D==null?void 0:D.total_allowances)||0)})]})})]})]}),s.jsx("div",{style:Bt.sectionContainer,children:I()})]}),s.jsxs("div",{style:Bt.disputesSection,children:[s.jsx("h3",{style:Bt.sectionTitle,children:"Disputes Summary"}),s.jsx("p",{style:Bt.disputesSubtitle,children:"Cases opened in selected period (by invoice date)"}),s.jsxs("table",{style:Bt.breakdownTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Bt.tableHeader,children:"Status"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Count"}),s.jsx("th",{style:{...Bt.tableHeader,textAlign:"right"},children:"Difference Value"})]})}),s.jsx("tbody",{children:((H=O==null?void 0:O.rows)==null?void 0:H.map((z,G)=>s.jsxs("tr",{style:z.label==="Total Cases"?{background:"#f8f9fa"}:{},children:[s.jsx("td",{style:{...Bt.tableCell,fontWeight:z.label==="Total Cases"?"bold":"normal"},children:z.label}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:z.label==="Total Cases"?"bold":"normal"},children:z.count}),s.jsx("td",{style:{...Bt.tableCell,textAlign:"right",fontFamily:"monospace",fontWeight:z.label==="Total Cases"?"bold":"normal",color:z.label==="Resolved"?"#27ae60":z.label==="Still Open"?"#e67e22":void 0},children:U(z.difference_value)})]},G)))||s.jsx("tr",{children:s.jsx("td",{colSpan:3,style:{...Bt.tableCell,textAlign:"center",color:"#999"},children:"No disputes data"})})})]})]})]})}const Bt={loading:{padding:"2rem",textAlign:"center",color:"#666"},error:{padding:"2rem",textAlign:"center",color:"#c00",background:"#fee",borderRadius:"8px"},noData:{padding:"2rem",textAlign:"center",color:"#999"},header:{marginBottom:"1.5rem"},title:{color:"#1a1a2e",margin:0},dateControls:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"1rem"},dateRow:{display:"flex",gap:"1.5rem",flexWrap:"wrap",marginBottom:"1rem"},dateField:{display:"flex",flexDirection:"column",gap:"0.25rem"},dateLabel:{fontSize:"0.85rem",color:"#666",fontWeight:500},dateInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"150px"},monthSelect:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"1rem",minWidth:"180px",background:"white"},presetRow:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},presetBtn:{padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},generateBtn:{padding:"0.4rem 1rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem",fontWeight:"bold",marginLeft:"auto"},generateBtnDisabled:{background:"#ccc",cursor:"default"},periodLabel:{fontSize:"1.1rem",fontWeight:"bold",color:"#1a1a2e",marginBottom:"1rem",textAlign:"center"},mainContent:{display:"flex",gap:"1.5rem",flexWrap:"wrap",alignItems:"stretch"},sectionContainer:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem",flex:"1 1 auto",minWidth:"300px"},sectionTitle:{margin:"0 0 1rem 0",color:"#1a1a2e"},breakdownTable:{width:"100%",borderCollapse:"collapse"},tableHeader:{textAlign:"left",padding:"0.75rem 0.5rem",borderBottom:"2px solid #dee2e6",color:"#1a1a2e",fontWeight:600,fontSize:"0.85rem"},tableCell:{padding:"0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},typeDot:{display:"inline-block",width:"10px",height:"10px",borderRadius:"50%",marginRight:"8px"},chartContainer:{width:"100%"},chartTitle:{margin:"0 0 1rem 0",color:"#1a1a2e",fontSize:"1rem",fontWeight:600},chartSvg:{display:"block",maxWidth:"100%"},chartLegend:{display:"flex",gap:"0.5rem 0.75rem",marginTop:"0.5rem",flexWrap:"wrap",justifyContent:"center",maxHeight:"60px",overflowY:"auto",padding:"0.25rem"},legendItem:{display:"flex",alignItems:"center",gap:"0.25rem",fontSize:"0.7rem",color:"#555",whiteSpace:"nowrap"},legendColor:{width:"10px",height:"10px",borderRadius:"2px",display:"inline-block",flexShrink:0},disputesSection:{background:"white",borderRadius:"12px",padding:"1.5rem",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",marginBottom:"2rem"},disputesSubtitle:{color:"#666",fontSize:"0.85rem",margin:"0 0 1rem 0"}};function Mfe(){const{token:n}=gn(),e=go(),t=pi(),r=new Date().toISOString().slice(0,10),i=new Date(Date.now()-7*864e5).toISOString().slice(0,10),[o,a]=k.useState(i),[l,d]=k.useState(r),[c,u]=k.useState(!1),[f,p]=k.useState(i),[g,m]=k.useState(r),[y,v]=k.useState(new Set),[x,w]=k.useState(null),[S,_]=k.useState(""),{data:b,isLoading:C,error:T}=Oe({queryKey:["sales-gp",f,g],queryFn:async()=>{const U=await fetch(`/api/reports/sales-gp?from_date=${f}&to_date=${g}`,{headers:{Authorization:`Bearer ${n}`}});if(!U.ok){const M=await U.json().catch(()=>({detail:"Request failed"}));throw new Error(M.detail||"Request failed")}return U.json()},enabled:!!n&&c}),{data:F}=Oe({queryKey:["recipes-for-mapping",S],queryFn:async()=>{const U=`/api/recipes?recipe_type=dish${S?`&search=${encodeURIComponent(S)}`:""}`;return(await fetch(U,{headers:{Authorization:`Bearer ${n}`}})).json()},enabled:!!n&&!!x}),A=Ue({mutationFn:async({recipeId:U,menuItemName:M,portionName:I})=>{if(!(await fetch(`/api/recipes/${U}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({kds_menu_item_name:M,sambapos_portion_name:I==="Normal"?null:I})})).ok)throw new Error("Failed to update recipe")},onSuccess:()=>{w(null),_(""),t.invalidateQueries({queryKey:["sales-gp"]})}}),D=()=>{p(o),m(l),u(!0)},P=U=>{v(M=>{const I=new Set(M);return I.has(U)?I.delete(U):I.add(U),I})},L=U=>Number(U).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2}),W=U=>U!=null?`${Number(U).toFixed(1)}%`:"—",O=U=>U==null?"#888":U>=70?"#16a34a":U>=60?"#ca8a04":"#dc2626";return s.jsxs("div",{style:Ct.container,children:[s.jsx("h2",{style:Ct.pageTitle,children:"Sales GP% Report"}),s.jsxs("div",{style:Ct.dateBar,children:[s.jsxs("div",{style:Ct.dateGroup,children:[s.jsx("label",{style:Ct.dateLabel,children:"From"}),s.jsx("input",{type:"date",value:o,onChange:U=>a(U.target.value),style:Ct.dateInput})]}),s.jsxs("div",{style:Ct.dateGroup,children:[s.jsx("label",{style:Ct.dateLabel,children:"To"}),s.jsx("input",{type:"date",value:l,onChange:U=>d(U.target.value),style:Ct.dateInput})]}),s.jsx("button",{onClick:D,style:Ct.generateBtn,children:"Generate"})]}),C&&s.jsx("div",{style:Ct.loading,children:"Loading sales data from SambaPOS..."}),T&&s.jsx("div",{style:Ct.error,children:T.message}),b&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Ct.summaryBanner,children:[s.jsxs("div",{style:Ct.summaryMain,children:[s.jsx("div",{style:Ct.summaryLabel,children:"Estimated Sales GP%"}),s.jsx("div",{style:{...Ct.summaryValue,color:O(b.mapped_gp_percent)},children:W(b.mapped_gp_percent)}),s.jsx("div",{style:Ct.summarySubtext,children:"mapped items only"})]}),s.jsxs("div",{style:Ct.summaryStats,children:[s.jsxs("div",{style:Ct.statBox,children:[s.jsx("div",{style:Ct.statLabel,children:"Mapped Revenue"}),s.jsxs("div",{style:Ct.statValue,children:["£",L(b.mapped_revenue_net)]})]}),s.jsxs("div",{style:Ct.statBox,children:[s.jsx("div",{style:Ct.statLabel,children:"Mapped Cost"}),s.jsxs("div",{style:Ct.statValue,children:["£",L(b.mapped_total_cost)]})]}),s.jsxs("div",{style:Ct.statBox,children:[s.jsx("div",{style:Ct.statLabel,children:"Total Revenue"}),s.jsxs("div",{style:Ct.statValue,children:["£",L(b.total_all_revenue_net)]})]})]}),s.jsxs("div",{style:Ct.coverageSection,children:[s.jsxs("div",{style:Ct.coverageLabel,children:["Coverage: ",Number(b.mapped_revenue_percent).toFixed(1),"% of food sales revenue is costed",s.jsxs("span",{style:{color:"#888",marginLeft:"0.5rem"},children:["(",b.mapped_item_count," mapped, ",b.unmapped_item_count," unmapped)"]})]}),s.jsx("div",{style:Ct.coverageBarBg,children:s.jsx("div",{style:{...Ct.coverageBarFill,width:`${Math.min(Number(b.mapped_revenue_percent),100)}%`}})})]})]}),b.courses.map(U=>s.jsxs("div",{style:Ct.courseSection,children:[s.jsxs("div",{style:Ct.courseHeader,onClick:()=>P(U.course_name),children:[s.jsxs("div",{style:Ct.courseTitle,children:[s.jsx("span",{style:Ct.collapseIcon,children:y.has(U.course_name)?"▸":"▾"}),U.course_name]}),s.jsxs("div",{style:Ct.courseStats,children:[s.jsxs("span",{style:{marginRight:"1.5rem"},children:["Revenue: £",L(U.course_revenue)]}),s.jsxs("span",{style:{marginRight:"1.5rem"},children:["Cost: £",L(U.course_cost)]}),s.jsxs("span",{style:{fontWeight:700,color:O(U.course_gp_percent)},children:["GP: ",W(U.course_gp_percent)]})]})]}),!y.has(U.course_name)&&s.jsxs("table",{style:Ct.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ct.th,children:"Item"}),s.jsx("th",{style:Ct.th,children:"Portion"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Net Revenue"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Cost/Portion"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Total Cost"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"GP%"})]})}),s.jsx("tbody",{children:U.items.map((M,I)=>s.jsxs("tr",{style:Ct.tr,children:[s.jsx("td",{style:Ct.td,children:M.recipe_id?s.jsx("span",{title:`Recipe: ${M.recipe_name}`,onClick:()=>e(`/dishes/${M.recipe_id}`),style:{cursor:"pointer",color:"#3b82f6",textDecoration:"underline dotted",textUnderlineOffset:"3px"},children:M.menu_item_name}):M.menu_item_name}),s.jsx("td",{style:{...Ct.td,color:M.portion_name==="Normal"?"#ccc":"#555"},children:M.portion_name==="Normal"?"—":M.portion_name}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:[M.total_qty,M.dbb_qty>0&&s.jsxs("span",{title:`${M.dbb_qty} of ${M.total_qty} sold as DBB package — original price used for GP calculation`,style:Ct.dbbBadge,children:[M.dbb_qty," DBB"]})]}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:["£",L(M.total_revenue_net)]}),s.jsx("td",{style:{...Ct.td,textAlign:"right"},children:M.cost_per_portion!=null?`£${L(M.cost_per_portion)}`:"—"}),s.jsx("td",{style:{...Ct.td,textAlign:"right"},children:M.total_cost!=null?`£${L(M.total_cost)}`:"—"}),s.jsx("td",{style:{...Ct.td,textAlign:"right",fontWeight:600,color:O(M.item_gp_percent)},children:W(M.item_gp_percent)})]},I))})]})]},U.course_name)),b.unmapped_items.length>0&&s.jsxs("div",{style:Ct.unmappedSection,children:[s.jsxs("div",{style:Ct.unmappedHeader,children:[s.jsx("span",{children:"Unmapped Items"}),s.jsxs("span",{style:Ct.unmappedSubtext,children:["£",L(b.unmapped_revenue_net)," unmapped (",(100-Number(b.mapped_revenue_percent)).toFixed(1),"% of sales)"]})]}),s.jsxs("table",{style:Ct.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ct.th,children:"Item"}),s.jsx("th",{style:Ct.th,children:"Portion"}),s.jsx("th",{style:Ct.th,children:"Category"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Qty"}),s.jsx("th",{style:{...Ct.th,textAlign:"right"},children:"Net Revenue"}),s.jsx("th",{style:{...Ct.th,textAlign:"center"},children:"Action"})]})}),s.jsx("tbody",{children:b.unmapped_items.map((U,M)=>s.jsxs("tr",{style:Ct.tr,children:[s.jsx("td",{style:Ct.td,children:U.menu_item_name}),s.jsx("td",{style:{...Ct.td,color:U.portion_name==="Normal"?"#ccc":"#555"},children:U.portion_name==="Normal"?"—":U.portion_name}),s.jsx("td",{style:{...Ct.td,color:"#888"},children:U.category}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:[U.total_qty,U.dbb_qty>0&&s.jsxs("span",{title:`${U.dbb_qty} of ${U.total_qty} sold as DBB package — original price used`,style:Ct.dbbBadge,children:[U.dbb_qty," DBB"]})]}),s.jsxs("td",{style:{...Ct.td,textAlign:"right"},children:["£",L(U.total_revenue_net)]}),s.jsx("td",{style:{...Ct.td,textAlign:"center"},children:s.jsx("button",{onClick:()=>{w(U),_("")},style:Ct.mapBtn,children:"Map"})})]},M))})]})]})]}),x&&s.jsx("div",{style:Ct.overlay,children:s.jsxs("div",{style:Ct.modal,children:[s.jsxs("div",{style:Ct.modalHeader,children:[s.jsxs("h3",{style:{margin:0},children:["Map: ",x.menu_item_name,x.portion_name!=="Normal"&&` (${x.portion_name})`]}),s.jsx("button",{onClick:()=>{w(null),_("")},style:Ct.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ct.modalBody,children:[s.jsx("input",{value:S,onChange:U=>_(U.target.value),style:{...Ct.searchInput,marginBottom:"0.75rem"},placeholder:"Search dish recipes...",autoFocus:!0}),F?F.length===0?s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"No dish recipes found."}):s.jsx("div",{style:{maxHeight:"350px",overflow:"auto"},children:F.map(U=>s.jsxs("div",{onClick:()=>A.mutate({recipeId:U.id,menuItemName:x.menu_item_name,portionName:x.portion_name}),style:Ct.recipeRow,onMouseEnter:M=>M.currentTarget.style.background="#f0f7ff",onMouseLeave:M=>M.currentTarget.style.background="transparent",children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600},children:U.name}),s.jsxs("div",{style:{fontSize:"0.75rem",color:"#888"},children:[U.menu_section_name||"No course",U.cost_per_portion!=null&&` • Cost: £${Number(U.cost_per_portion).toFixed(2)}`]})]}),U.kds_menu_item_name&&s.jsxs("div",{style:{fontSize:"0.7rem",color:"#999"},children:["Already mapped: ",U.kds_menu_item_name]})]},U.id))}):s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"Loading recipes..."})]})]})})]})}const Ct={container:{maxWidth:"1100px",margin:"0 auto",padding:"1.5rem"},pageTitle:{fontSize:"1.4rem",fontWeight:700,marginBottom:"1rem"},dateBar:{display:"flex",gap:"1rem",alignItems:"flex-end",marginBottom:"1.5rem",flexWrap:"wrap"},dateGroup:{display:"flex",flexDirection:"column",gap:"0.2rem"},dateLabel:{fontSize:"0.75rem",fontWeight:600,color:"#666"},dateInput:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},generateBtn:{padding:"0.5rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},loading:{padding:"2rem",textAlign:"center",color:"#888"},error:{padding:"1rem",color:"#dc3545",background:"#fde8e8",borderRadius:"6px",marginBottom:"1rem"},summaryBanner:{background:"#f8f9fa",padding:"1.25rem",borderRadius:"8px",border:"2px solid #e0e0e0",marginBottom:"1.5rem"},summaryMain:{textAlign:"center",marginBottom:"1rem"},summaryLabel:{fontSize:"0.85rem",fontWeight:600,color:"#666",textTransform:"uppercase"},summaryValue:{fontSize:"2.5rem",fontWeight:800,lineHeight:1.2},summarySubtext:{fontSize:"0.75rem",color:"#999"},summaryStats:{display:"flex",justifyContent:"center",gap:"2rem",marginBottom:"1rem",flexWrap:"wrap"},statBox:{textAlign:"center"},statLabel:{fontSize:"0.75rem",color:"#666",fontWeight:600},statValue:{fontSize:"1.1rem",fontWeight:700},coverageSection:{borderTop:"1px solid #e0e0e0",paddingTop:"0.75rem"},coverageLabel:{fontSize:"0.8rem",color:"#555",marginBottom:"0.4rem"},coverageBarBg:{height:"8px",background:"#e0e0e0",borderRadius:"4px",overflow:"hidden"},coverageBarFill:{height:"100%",background:"#16a34a",borderRadius:"4px",transition:"width 0.3s"},courseSection:{marginBottom:"1rem",border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},courseHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",cursor:"pointer",flexWrap:"wrap",gap:"0.5rem"},courseTitle:{fontWeight:700,fontSize:"1rem"},collapseIcon:{marginRight:"0.5rem",fontSize:"0.85rem"},courseStats:{fontSize:"0.85rem",color:"#555"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666",background:"#fafafa"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.75rem",fontSize:"0.85rem"},unmappedSection:{marginTop:"1.5rem",border:"1px solid #f0c040",borderRadius:"8px",overflow:"hidden"},unmappedHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#fffbeb",fontWeight:700,fontSize:"1rem",flexWrap:"wrap",gap:"0.5rem"},unmappedSubtext:{fontSize:"0.85rem",fontWeight:400,color:"#92400e"},mapBtn:{padding:"0.25rem 0.75rem",background:"#3b82f6",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem",fontWeight:600},dbbBadge:{display:"inline-block",marginLeft:"0.35rem",padding:"0.1rem 0.35rem",background:"#ede9fe",color:"#6d28d9",borderRadius:"4px",fontSize:"0.7rem",fontWeight:700,cursor:"default",whiteSpace:"nowrap"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"500px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},searchInput:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},recipeRow:{padding:"0.6rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",display:"flex",justifyContent:"space-between",alignItems:"center"}};function zfe(){const{token:n}=gn(),e=k.useRef(null),[t,r]=k.useState(!1),[i,o]=k.useState(null),[a,l]=k.useState(!1),[d,c]=k.useState(!0),[u,f]=k.useState(new Set),p=Ue({mutationFn:async b=>{const C=new FormData;C.append("file",b);const T=await fetch("/api/reports/purchases/reconcile",{method:"POST",headers:{Authorization:`Bearer ${n}`},body:C});if(!T.ok){const F=await T.json().catch(()=>({detail:"Upload failed"}));throw new Error(F.detail||"Upload failed")}return T.json()},onSuccess:b=>{o(b),l(b.matched_count>20)}}),g=k.useCallback(b=>{if(!b.name.toLowerCase().endsWith(".xlsx")){alert("Please upload an XLSX file");return}p.mutate(b)},[p]),m=k.useCallback(b=>{var T;b.preventDefault(),r(!1);const C=(T=b.dataTransfer.files)==null?void 0:T[0];C&&g(C)},[g]),y=k.useCallback(b=>{var T;const C=(T=b.target.files)==null?void 0:T[0];C&&g(C),b.target.value=""},[g]),v=(b,C,T)=>{const F=[C.join(","),...T.map(L=>L.map(W=>`"${W}"`).join(","))].join(` -`),A=new Blob([F],{type:"text/csv"}),D=URL.createObjectURL(A),P=document.createElement("a");P.href=D,P.download=b,P.click(),URL.revokeObjectURL(D)},x=b=>new Date(b+"T00:00:00").toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}),w=i,S=(w==null?void 0:w.xero_only.filter(b=>b.is_expected_external))||[],_=(w==null?void 0:w.xero_only.filter(b=>!b.is_expected_external))||[];return s.jsxs("div",{style:Xe.container,children:[s.jsx("h2",{style:Xe.pageTitle,children:"Xero Reconciliation"}),!p.isPending&&s.jsxs("div",{style:{...Xe.dropZone,...t?Xe.dropZoneActive:{}},onDragOver:b=>{b.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:m,onClick:()=>{var b;return(b=e.current)==null?void 0:b.click()},children:[s.jsx("input",{ref:e,type:"file",accept:".xlsx",style:{display:"none"},onChange:y}),s.jsx("div",{style:Xe.dropIcon,children:"📄"}),s.jsx("div",{style:Xe.dropText,children:w?"Drop a new Xero XLSX to re-run":"Drop Xero Account Transactions XLSX here"}),s.jsx("div",{style:Xe.dropSubtext,children:"or click to browse"})]}),p.isPending&&s.jsx("div",{style:Xe.loading,children:"Parsing XLSX and reconciling against Flash invoices..."}),p.isError&&s.jsx("div",{style:Xe.error,children:p.error.message}),w&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Xe.summaryBar,children:[s.jsxs("div",{style:Xe.summaryPeriod,children:["Period: ",x(w.period_start)," – ",x(w.period_end)]}),s.jsxs("div",{style:Xe.summaryGrid,children:[s.jsxs("div",{style:Xe.summaryItem,children:[s.jsx("div",{style:Xe.summaryLabel,children:"Flash Total (net stock)"}),s.jsx("div",{style:Xe.summaryValue,children:w.flash_total})]}),s.jsxs("div",{style:Xe.summaryItem,children:[s.jsx("div",{style:Xe.summaryLabel,children:"Xero Total (net)"}),s.jsx("div",{style:Xe.summaryValue,children:w.xero_total})]}),s.jsxs("div",{style:Xe.summaryItem,children:[s.jsx("div",{style:Xe.summaryLabel,children:"Difference"}),s.jsx("div",{style:{...Xe.summaryValue,color:w.difference==="£0.00"?"#16a34a":"#dc2626"},children:w.difference})]})]}),s.jsxs("div",{style:Xe.summaryCounts,children:[s.jsxs("span",{style:Xe.countBadgeGreen,children:["✅ ",w.matched_count," matched"]}),s.jsxs("span",{style:Xe.countBadgeAmber,children:["⚠️ ",w.discrepancy_count," discrepancies"]}),s.jsxs("span",{style:Xe.countBadgeBlue,children:["❓ ",w.flash_only_count," Flash-only"]}),s.jsxs("span",{style:Xe.countBadgeBlue,children:["❓ ",w.xero_only_count," Xero-only"]})]}),w.non_stock_excluded_count>0&&s.jsxs("div",{style:Xe.footnote,children:[w.non_stock_excluded_count," non-stock Flash entries excluded (",w.non_stock_excluded_total,") — these post to other Xero accounts"]}),w.llm_matches_attempted&&s.jsx("div",{style:Xe.footnote,children:"AI-assisted matching was used for some discrepancies"})]}),s.jsxs("div",{style:Xe.section,children:[s.jsxs("div",{style:Xe.sectionHeader,onClick:()=>l(!a),children:[s.jsxs("span",{children:[s.jsx("span",{style:Xe.collapseIcon,children:a?"▸":"▾"}),"✅ Matched (",w.matched_count,")"]}),s.jsx("button",{onClick:b=>{b.stopPropagation(),v("reconciliation_matched.csv",["Date","Supplier","Ref","Amount"],w.matched.map(C=>[C.date,C.supplier,C.ref,C.amount]))},style:Xe.csvBtn,children:"Download CSV"})]}),!a&&w.matched.length>0&&s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Supplier"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Amount"}),s.jsx("th",{style:{...Xe.th,textAlign:"center",width:"40px"},children:"✓"})]})}),s.jsx("tbody",{children:w.matched.map((b,C)=>s.jsxs("tr",{style:Xe.tr,children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:b.supplier}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.amount}),s.jsxs("td",{style:{...Xe.td,textAlign:"center"},children:[s.jsx("span",{style:{color:"#16a34a"},children:"✓"}),b.match_source==="ai"&&s.jsx("span",{style:Xe.aiBadge,children:"AI"})]})]},C))})]}),!a&&w.matched.length===0&&s.jsx("div",{style:Xe.emptyMsg,children:"No exact matches found."})]}),s.jsxs("div",{style:{...Xe.section,borderColor:"#f59e0b"},children:[s.jsxs("div",{style:Xe.sectionHeaderAmber,children:[s.jsxs("span",{children:["⚠️ Discrepancies (",w.discrepancy_count,")"]}),s.jsx("button",{onClick:()=>v("reconciliation_discrepancies.csv",["Date","Supplier","Ref","Flash Amount","Xero Amount","Difference","Differs"],w.discrepancies.map(b=>[b.date,b.supplier,b.ref,b.flash_amount,b.xero_amount,b.difference,b.differs.join("; ")])),style:Xe.csvBtn,children:"Download CSV"})]}),w.discrepancies.length>0?s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...Xe.th,width:"30px"}}),s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Supplier"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Flash"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Xero"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Diff"}),s.jsx("th",{style:Xe.th,children:"What differs"})]})}),s.jsx("tbody",{children:w.discrepancies.map((b,C)=>{const T=u.has(C);return s.jsxs(k.Fragment,{children:[s.jsxs("tr",{style:{...Xe.tr,cursor:"pointer"},onClick:()=>f(F=>{const A=new Set(F);return A.has(C)?A.delete(C):A.add(C),A}),children:[s.jsx("td",{style:{...Xe.td,color:"#999",fontSize:"0.75rem"},children:T?"▾":"▸"}),s.jsx("td",{style:Xe.td,children:b.differs.includes("date")?s.jsxs("span",{children:[s.jsx("span",{style:Xe.amberHighlight,children:b.flash_date?x(b.flash_date):"—"}),s.jsx("span",{style:{color:"#999",margin:"0 0.25rem"},children:"/"}),s.jsx("span",{style:Xe.amberHighlight,children:b.xero_date?x(b.xero_date):"—"})]}):x(b.date)}),s.jsx("td",{style:Xe.td,children:b.flash_id?s.jsx("span",{title:"Open invoice",onClick:F=>{F.stopPropagation(),window.open(`/invoice/${b.flash_id}`,"_blank")},style:{cursor:"pointer",color:"#3b82f6",textDecoration:"underline dotted",textUnderlineOffset:"3px"},children:b.supplier}):b.supplier}),s.jsx("td",{style:Xe.td,children:b.differs.includes("ref")?s.jsxs("span",{children:[s.jsx("span",{style:Xe.amberHighlight,children:b.flash_ref||"—"}),s.jsx("span",{style:{color:"#999",margin:"0 0.25rem"},children:"/"}),s.jsx("span",{style:Xe.amberHighlight,children:b.xero_ref||"—"})]}):b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.flash_amount}),s.jsx("td",{style:{...Xe.td,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.xero_amount}),s.jsx("td",{style:{...Xe.td,textAlign:"right",fontWeight:600,color:"#dc2626"},children:b.difference}),s.jsxs("td",{style:Xe.td,children:[b.differs.map(F=>s.jsx("span",{style:Xe.differBadge,children:F},F)),b.match_source==="ai"&&s.jsx("span",{style:Xe.aiBadge,children:"AI"})]})]}),T&&s.jsx("tr",{style:{background:"#f8f9fa"},children:s.jsxs("td",{colSpan:8,style:{padding:0},children:[s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"0.8rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.detailTh,children:"Source"}),s.jsx("th",{style:Xe.detailTh,children:"Date"}),s.jsx("th",{style:Xe.detailTh,children:"Supplier / Description"}),s.jsx("th",{style:Xe.detailTh,children:"Ref"}),s.jsx("th",{style:{...Xe.detailTh,textAlign:"right"},children:"Net Amount"})]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{style:Xe.detailRow,children:[s.jsx("td",{style:Xe.detailTd,children:s.jsx("span",{style:Xe.flashBadge,children:"Flash"})}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("date")?{background:"#fef3c7"}:{}},children:b.flash_date?x(b.flash_date):"—"}),s.jsx("td",{style:Xe.detailTd,children:b.flash_supplier||b.supplier}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("ref")?{background:"#fef3c7"}:{}},children:b.flash_ref||"—"}),s.jsx("td",{style:{...Xe.detailTd,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.flash_amount})]}),s.jsxs("tr",{style:Xe.detailRow,children:[s.jsx("td",{style:Xe.detailTd,children:s.jsx("span",{style:Xe.xeroBadge,children:"Xero"})}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("date")?{background:"#fef3c7"}:{}},children:b.xero_date?x(b.xero_date):"—"}),s.jsx("td",{style:Xe.detailTd,children:b.xero_description||b.supplier}),s.jsx("td",{style:{...Xe.detailTd,...b.differs.includes("ref")?{background:"#fef3c7"}:{}},children:b.xero_ref||"—"}),s.jsx("td",{style:{...Xe.detailTd,textAlign:"right",...b.differs.includes("amount")?{background:"#fef3c7"}:{}},children:b.xero_amount})]})]})]}),b.amount_insight&&s.jsxs("div",{style:Xe.insightBar,children:[s.jsx("span",{style:Xe.insightIcon,children:"💡"}),b.amount_insight]})]})})]},C)})})]}):s.jsx("div",{style:Xe.emptyMsg,children:"No discrepancies found — all matches are exact."})]}),s.jsxs("div",{style:Xe.section,children:[s.jsxs("div",{style:Xe.sectionHeader,children:[s.jsxs("span",{children:["❓ In Flash but not in Xero (",w.flash_only_count,")"]}),s.jsx("button",{onClick:()=>v("reconciliation_flash_only.csv",["Date","Supplier","Ref","Net Stock"],w.flash_only.map(b=>[b.date,b.supplier,b.ref,b.net_stock])),style:Xe.csvBtn,children:"Download CSV"})]}),w.flash_only.length>0?s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Supplier"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Flash Net Stock"})]})}),s.jsx("tbody",{children:w.flash_only.map((b,C)=>s.jsxs("tr",{style:Xe.tr,children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:s.jsx("span",{title:"Open invoice",onClick:()=>window.open(`/invoice/${b.flash_id}`,"_blank"),style:{cursor:"pointer",color:"#3b82f6",textDecoration:"underline dotted",textUnderlineOffset:"3px"},children:b.supplier})}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.net_stock})]},C))})]}):s.jsx("div",{style:Xe.emptyMsg,children:"All Flash invoices matched."})]}),s.jsxs("div",{style:Xe.section,children:[s.jsxs("div",{style:Xe.sectionHeader,children:[s.jsxs("span",{children:["❓ In Xero but not in Flash (",_.length,S.length>0?` + ${S.length} expected`:"",")"]}),s.jsx("button",{onClick:()=>v("reconciliation_xero_only.csv",["Date","Description","Ref","Net","Expected External"],w.xero_only.map(b=>[b.date,b.description,b.ref,b.net,b.is_expected_external?"Yes":"No"])),style:Xe.csvBtn,children:"Download CSV"})]}),_.length>0?s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Description"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Xero Net"})]})}),s.jsx("tbody",{children:_.map((b,C)=>s.jsxs("tr",{style:Xe.tr,children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:b.description}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.net})]},C))})]}):s.jsx("div",{style:Xe.emptyMsg,children:"No unexpected Xero-only entries."}),S.length>0&&s.jsxs("div",{style:Xe.externalSection,children:[s.jsxs("div",{style:Xe.externalHeader,onClick:()=>c(!d),children:[s.jsx("span",{style:Xe.collapseIcon,children:d?"▸":"▾"}),"Expected external (",S.length,") — Tesco, JVs, petty cash etc."]}),!d&&s.jsxs("table",{style:Xe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Xe.th,children:"Date"}),s.jsx("th",{style:Xe.th,children:"Description"}),s.jsx("th",{style:Xe.th,children:"Ref"}),s.jsx("th",{style:{...Xe.th,textAlign:"right"},children:"Xero Net"})]})}),s.jsx("tbody",{children:S.map((b,C)=>s.jsxs("tr",{style:{...Xe.tr,opacity:.6},children:[s.jsx("td",{style:Xe.td,children:x(b.date)}),s.jsx("td",{style:Xe.td,children:b.description}),s.jsx("td",{style:Xe.td,children:b.ref}),s.jsx("td",{style:{...Xe.td,textAlign:"right"},children:b.net})]},C))})]})]})]})]})]})}const Xe={container:{maxWidth:"1100px",margin:"0 auto",padding:"1.5rem"},pageTitle:{fontSize:"1.4rem",fontWeight:700,marginBottom:"1rem"},dropZone:{border:"2px dashed #ddd",borderRadius:"12px",padding:"2.5rem",textAlign:"center",cursor:"pointer",marginBottom:"1.5rem",background:"#fafafa",transition:"all 0.2s"},dropZoneActive:{borderColor:"#e94560",background:"#fff5f7"},dropIcon:{fontSize:"2.5rem",marginBottom:"0.5rem"},dropText:{fontSize:"1rem",fontWeight:600,color:"#333"},dropSubtext:{fontSize:"0.8rem",color:"#999",marginTop:"0.3rem"},loading:{padding:"2rem",textAlign:"center",color:"#888"},error:{padding:"1rem",color:"#dc3545",background:"#fde8e8",borderRadius:"6px",marginBottom:"1rem"},summaryBar:{background:"#1a1a2e",color:"white",padding:"1.25rem",borderRadius:"10px",marginBottom:"1.5rem"},summaryPeriod:{fontSize:"0.85rem",color:"#aaa",marginBottom:"0.75rem"},summaryGrid:{display:"flex",gap:"2rem",marginBottom:"0.75rem",flexWrap:"wrap"},summaryItem:{},summaryLabel:{fontSize:"0.7rem",textTransform:"uppercase",color:"#888",fontWeight:600},summaryValue:{fontSize:"1.3rem",fontWeight:700},summaryCounts:{display:"flex",gap:"0.75rem",flexWrap:"wrap",marginTop:"0.5rem"},countBadgeGreen:{fontSize:"0.8rem",background:"rgba(22,163,74,0.2)",color:"#4ade80",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeAmber:{fontSize:"0.8rem",background:"rgba(245,158,11,0.2)",color:"#fbbf24",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeBlue:{fontSize:"0.8rem",background:"rgba(59,130,246,0.2)",color:"#60a5fa",padding:"0.2rem 0.6rem",borderRadius:"4px"},footnote:{fontSize:"0.75rem",color:"#888",marginTop:"0.5rem",fontStyle:"italic"},section:{marginBottom:"1rem",border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",cursor:"pointer",fontWeight:700,fontSize:"0.95rem"},sectionHeaderAmber:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#fffbeb",fontWeight:700,fontSize:"0.95rem"},collapseIcon:{marginRight:"0.5rem",fontSize:"0.85rem"},csvBtn:{padding:"0.25rem 0.65rem",background:"transparent",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.75rem",cursor:"pointer",color:"#666"},emptyMsg:{padding:"1rem",textAlign:"center",color:"#999",fontSize:"0.85rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666",background:"#fafafa"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.75rem",fontSize:"0.85rem"},amberHighlight:{background:"#fef3c7",padding:"0.1rem 0.3rem",borderRadius:"3px"},differBadge:{display:"inline-block",background:"#fef3c7",color:"#92400e",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.7rem",fontWeight:600,marginRight:"0.3rem"},externalSection:{borderTop:"1px solid #e0e0e0",marginTop:"0.5rem"},externalHeader:{padding:"0.6rem 1rem",fontSize:"0.8rem",color:"#888",cursor:"pointer",fontStyle:"italic"},detailTh:{padding:"0.35rem 0.75rem",textAlign:"left",fontSize:"0.7rem",fontWeight:600,color:"#888",borderBottom:"1px solid #e0e0e0",background:"#f0f0f0"},detailRow:{borderBottom:"1px solid #eee"},detailTd:{padding:"0.35rem 0.75rem",fontSize:"0.8rem"},flashBadge:{display:"inline-block",background:"#dbeafe",color:"#1d4ed8",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.65rem",fontWeight:700},xeroBadge:{display:"inline-block",background:"#e0e7ff",color:"#4338ca",padding:"0.1rem 0.4rem",borderRadius:"3px",fontSize:"0.65rem",fontWeight:700},insightBar:{padding:"0.5rem 0.75rem",background:"#f0fdf4",borderTop:"1px solid #bbf7d0",fontSize:"0.8rem",color:"#166534",lineHeight:1.4},insightIcon:{marginRight:"0.4rem"},aiBadge:{display:"inline-block",background:"#f3e8ff",color:"#7c3aed",padding:"0.1rem 0.35rem",borderRadius:"3px",fontSize:"0.6rem",fontWeight:700,marginLeft:"0.3rem",verticalAlign:"middle"}};function qN(n,e){return e==="g"&&Math.abs(n)>=1e3?`${(n/1e3).toFixed(2)} kg`:e==="ml"&&Math.abs(n)>=1e3?`${(n/1e3).toFixed(2)} ltr`:e==="g"?`${n.toFixed(0)} g`:e==="ml"?`${n.toFixed(0)} ml`:e==="kg"?`${n.toFixed(2)} kg`:e==="ltr"?`${n.toFixed(2)} ltr`:e==="each"?`${n.toFixed(1)}`:`${n.toFixed(2)} ${e}`}function vx(n){return n==null?"—":`£${Number(n).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Ofe(n){if(n==null)return"—";const e=Number(n);return`${e>0?"+":""}${e.toFixed(1)}%`}function Lfe(n,e){if(n==null&&e==null)return"#666";const t=Math.abs(n??0),r=Math.abs(e??0);return t>50||r>50?"#dc2626":t>15||r>15?"#d97706":"#16a34a"}function Nfe(n,e){if(n==null&&e==null)return"transparent";const t=Math.abs(n??0),r=Math.abs(e??0);return t>50||r>50?"#fef2f2":t>15||r>15?"#fffbeb":"transparent"}function Wfe(){const{token:n}=gn(),e=new Date().toISOString().slice(0,10),t=new Date(Date.now()-30*864e5).toISOString().slice(0,10),[r,i]=k.useState(t),[o,a]=k.useState(e),[l,d]=k.useState(null),[c,u]=k.useState(!1),[f,p]=k.useState(null),[g,m]=k.useState(""),[y,v]=k.useState(!0),[x,w]=k.useState("variance_value"),[S,_]=k.useState(!0),b=async()=>{u(!0),p(null);try{const A=await fetch(`/api/reports/usage-variance?from_date=${r}&to_date=${o}`,{headers:{Authorization:`Bearer ${n}`}});if(!A.ok){const P=await A.json().catch(()=>({detail:"Request failed"}));throw new Error(P.detail||"Request failed")}const D=await A.json();d(D)}catch(A){p(A.message)}finally{u(!1)}},C=A=>new Date(A+"T00:00:00").toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"});let T=(l==null?void 0:l.items)??[];if(g){const A=g.toLowerCase();T=T.filter(D=>D.ingredient_name.toLowerCase().includes(A)||(D.category||"").toLowerCase().includes(A))}y||(T=T.filter(A=>Math.abs(A.variance_pct??0)>10||Math.abs(A.variance_value??0)>5)),T=[...T].sort((A,D)=>x==="name"?A.ingredient_name.localeCompare(D.ingredient_name):x==="variance_pct"?Math.abs(D.variance_pct??0)-Math.abs(A.variance_pct??0):Math.abs(D.variance_value??0)-Math.abs(A.variance_value??0));const F=l;return s.jsxs("div",{style:Mt.container,children:[s.jsx("h2",{style:Mt.pageTitle,children:"Theoretical vs Actual Usage"}),s.jsxs("div",{style:Mt.dateBar,children:[s.jsxs("label",{style:Mt.dateLabel,children:["From",s.jsx("input",{type:"date",value:r,onChange:A=>i(A.target.value),style:Mt.dateInput})]}),s.jsxs("label",{style:Mt.dateLabel,children:["To",s.jsx("input",{type:"date",value:o,onChange:A=>a(A.target.value),style:Mt.dateInput})]}),s.jsx("button",{onClick:b,disabled:c,style:Mt.generateBtn,children:c?"Loading...":"Generate"})]}),f&&s.jsx("div",{style:Mt.error,children:f}),F&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:Mt.summaryBar,children:[s.jsxs("div",{style:Mt.summaryPeriod,children:[C(F.from_date)," – ",C(F.to_date)]}),s.jsxs("div",{style:Mt.summaryGrid,children:[s.jsxs("div",{style:Mt.summaryItem,children:[s.jsx("div",{style:Mt.summaryLabel,children:"Theoretical Cost"}),s.jsx("div",{style:Mt.summaryValue,children:vx(F.total_theoretical_value)})]}),s.jsxs("div",{style:Mt.summaryItem,children:[s.jsx("div",{style:Mt.summaryLabel,children:"Actual Purchased"}),s.jsx("div",{style:Mt.summaryValue,children:vx(F.total_actual_value)})]}),s.jsxs("div",{style:Mt.summaryItem,children:[s.jsx("div",{style:Mt.summaryLabel,children:"Variance"}),s.jsx("div",{style:{...Mt.summaryValue,color:F.total_variance_value>50?"#f87171":F.total_variance_value<-50?"#fbbf24":"#4ade80"},children:vx(F.total_variance_value)})]})]}),s.jsxs("div",{style:Mt.summaryCounts,children:[s.jsxs("span",{style:Mt.countBadgeGreen,children:[F.mapped_dish_count," dishes mapped"]}),F.unmapped_dish_count>0&&s.jsxs("span",{style:Mt.countBadgeAmber,children:[F.unmapped_dish_count," unmapped"]}),s.jsxs("span",{style:Mt.countBadgeBlue,children:[F.ingredients_with_purchases," ingredients with purchases"]}),F.ingredients_without_purchases>0&&s.jsxs("span",{style:Mt.countBadgeBlue,children:[F.ingredients_without_purchases," theoretical only"]})]}),s.jsx("div",{style:Mt.footnote,children:"Variance = Actual - Theoretical. Positive = over-purchased. This report estimates usage from recipes and may not account for stock carried forward, staff meals, or wastage."})]}),s.jsxs("div",{style:Mt.controlsBar,children:[s.jsx("input",{type:"text",placeholder:"Search ingredient...",value:g,onChange:A=>m(A.target.value),style:Mt.searchInput}),s.jsxs("label",{style:Mt.toggleLabel,children:[s.jsx("input",{type:"checkbox",checked:!y,onChange:A=>v(!A.target.checked)})," ","Variances only"]}),s.jsxs("select",{value:x,onChange:A=>w(A.target.value),style:Mt.sortSelect,children:[s.jsx("option",{value:"variance_value",children:"Sort: Variance £"}),s.jsx("option",{value:"variance_pct",children:"Sort: Variance %"}),s.jsx("option",{value:"name",children:"Sort: Name"})]})]}),s.jsx("div",{style:Mt.tableWrap,children:s.jsxs("table",{style:Mt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Mt.th,children:"Ingredient"}),s.jsx("th",{style:Mt.th,children:"Category"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Theo. Qty"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Theo. £"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Actual Qty"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Actual £"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Variance £"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Variance %"}),s.jsx("th",{style:{...Mt.th,textAlign:"center"},children:"Dishes"}),s.jsx("th",{style:{...Mt.th,textAlign:"center"},children:"Invoices"})]})}),s.jsxs("tbody",{children:[T.map(A=>{const D=Nfe(A.variance_pct,A.variance_value),P=Lfe(A.variance_pct,A.variance_value);return s.jsxs("tr",{style:{...Mt.tr,background:D},children:[s.jsx("td",{style:Mt.td,children:s.jsx("span",{style:{fontWeight:600},children:A.ingredient_name})}),s.jsx("td",{style:{...Mt.td,color:"#888",fontSize:"0.8rem"},children:A.category||"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.theoretical_qty>0?qN(A.theoretical_qty,A.standard_unit):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.theoretical_value>0?vx(A.theoretical_value):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},title:A.actual_qty==null?"No mapped purchases in period":void 0,children:A.actual_qty!=null?qN(A.actual_qty,A.standard_unit):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.actual_value!=null?vx(A.actual_value):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right",fontWeight:600,color:P},children:A.variance_value!=null?vx(A.variance_value):"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right",fontWeight:600,color:P},children:Ofe(A.variance_pct)}),s.jsx("td",{style:{...Mt.td,textAlign:"center",color:"#888",fontSize:"0.8rem"},children:A.dishes_using}),s.jsx("td",{style:{...Mt.td,textAlign:"center",color:"#888",fontSize:"0.8rem"},children:A.invoice_count||"—"})]},A.ingredient_id)}),T.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:10,style:{...Mt.td,textAlign:"center",color:"#999"},children:g||!y?"No items match filters.":"No data."})})]})]})}),F.unmapped_sales.length>0&&s.jsxs("div",{style:Mt.section,children:[s.jsx("div",{style:Mt.sectionHeader,onClick:()=>_(!S),children:s.jsxs("span",{children:[s.jsx("span",{style:Mt.collapseIcon,children:S?"▸":"▾"}),"Unmapped Sales Items (",F.unmapped_sales.length,") — no recipe, can't calculate theoretical usage"]})}),!S&&s.jsxs("table",{style:Mt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Mt.th,children:"Menu Item"}),s.jsx("th",{style:Mt.th,children:"Portion"}),s.jsx("th",{style:Mt.th,children:"Category"}),s.jsx("th",{style:{...Mt.th,textAlign:"right"},children:"Qty Sold"})]})}),s.jsx("tbody",{children:F.unmapped_sales.map((A,D)=>s.jsxs("tr",{style:Mt.tr,children:[s.jsx("td",{style:Mt.td,children:A.menu_item_name}),s.jsx("td",{style:{...Mt.td,color:"#888"},children:A.portion_name!=="Normal"?A.portion_name:"—"}),s.jsx("td",{style:{...Mt.td,color:"#888"},children:A.category||"—"}),s.jsx("td",{style:{...Mt.td,textAlign:"right"},children:A.total_qty})]},D))})]})]})]})]})}const Mt={container:{maxWidth:"1200px",margin:"0 auto",padding:"1.5rem"},pageTitle:{fontSize:"1.4rem",fontWeight:700,marginBottom:"1rem"},dateBar:{display:"flex",gap:"1rem",alignItems:"flex-end",marginBottom:"1.5rem",flexWrap:"wrap"},dateLabel:{fontSize:"0.8rem",fontWeight:600,color:"#666",display:"flex",flexDirection:"column",gap:"0.25rem"},dateInput:{padding:"0.4rem 0.5rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.85rem"},generateBtn:{padding:"0.45rem 1.2rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",fontWeight:600,cursor:"pointer",fontSize:"0.85rem"},error:{padding:"1rem",color:"#dc3545",background:"#fde8e8",borderRadius:"6px",marginBottom:"1rem"},summaryBar:{background:"#1a1a2e",color:"white",padding:"1.25rem",borderRadius:"10px",marginBottom:"1.5rem"},summaryPeriod:{fontSize:"0.85rem",color:"#aaa",marginBottom:"0.75rem"},summaryGrid:{display:"flex",gap:"2rem",marginBottom:"0.75rem",flexWrap:"wrap"},summaryItem:{},summaryLabel:{fontSize:"0.7rem",textTransform:"uppercase",color:"#888",fontWeight:600},summaryValue:{fontSize:"1.3rem",fontWeight:700},summaryCounts:{display:"flex",gap:"0.75rem",flexWrap:"wrap",marginTop:"0.5rem"},countBadgeGreen:{fontSize:"0.8rem",background:"rgba(22,163,74,0.2)",color:"#4ade80",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeAmber:{fontSize:"0.8rem",background:"rgba(245,158,11,0.2)",color:"#fbbf24",padding:"0.2rem 0.6rem",borderRadius:"4px"},countBadgeBlue:{fontSize:"0.8rem",background:"rgba(59,130,246,0.2)",color:"#60a5fa",padding:"0.2rem 0.6rem",borderRadius:"4px"},footnote:{fontSize:"0.72rem",color:"#777",marginTop:"0.75rem",fontStyle:"italic",lineHeight:1.5},controlsBar:{display:"flex",gap:"1rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.4rem 0.6rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.85rem",width:"200px"},toggleLabel:{fontSize:"0.85rem",color:"#555",cursor:"pointer",userSelect:"none"},sortSelect:{padding:"0.35rem 0.5rem",border:"1px solid #ccc",borderRadius:"4px",fontSize:"0.8rem",color:"#555"},tableWrap:{overflowX:"auto"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.72rem",fontWeight:600,color:"#666",background:"#fafafa",whiteSpace:"nowrap"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.75rem",fontSize:"0.83rem",whiteSpace:"nowrap"},section:{marginTop:"1.5rem",border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.75rem 1rem",background:"#f8f9fa",cursor:"pointer",fontWeight:600,fontSize:"0.9rem",color:"#888"},collapseIcon:{marginRight:"0.5rem",fontSize:"0.85rem"}},oh=TK.invoices;function Ufe(){const{token:n}=gn(),e=k.useMemo(()=>wM(),[]),[t,r]=co(oh.query,""),[i,o]=co(oh.includeLineItems,!1),[a,l]=co(oh.supplier,""),[d,c]=co(oh.status,""),[u,f]=co(oh.dateFrom,e.from),[p,g]=co(oh.dateTo,e.to),[m,y]=co(oh.groupBy,""),[v,x]=co(oh.sortColumn,""),[w,S]=co(oh.sortDirection,"asc"),[_,b]=k.useState(new Set),C=Rg(t,300),{data:T}=Oe({queryKey:["suppliers"],queryFn:async()=>{const z=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!z.ok)throw new Error("Failed to fetch suppliers");return z.json()}}),{data:F,isLoading:A,error:D}=Oe({queryKey:["search-invoices",C,i,a,d,u,p,m],queryFn:async()=>{const z=new URLSearchParams;C&&z.set("q",C),i&&z.set("include_line_items","true"),a&&z.set("supplier_id",a),d&&z.set("status",d),u&&z.set("date_from",u),p&&z.set("date_to",p),m&&z.set("group_by",m),z.set("limit","200");const G=await fetch(`/api/search/invoices?${z}`,{headers:{Authorization:`Bearer ${n}`}});if(!G.ok)throw new Error("Search failed");return G.json()},enabled:!!n}),P=z=>{b(G=>{const te=new Set(G);return te.has(z)?te.delete(z):te.add(z),te})},L=z=>{v===z?S(w==="asc"?"desc":"asc"):(x(z),S("asc"))},W=z=>v!==z?null:w==="asc"?" ▲":" ▼",O=z=>{const G={pending:"#f59e0b",processed:"#3b82f6",reviewed:"#8b5cf6",confirmed:"#22c55e"};return s.jsx("span",{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"12px",backgroundColor:G[z]||"#9ca3af",color:"white"},children:z})},U=z=>z.net_total!==null?z.net_total:z.total!==null?z.total:null,M=z=>z.total!==null?z.total:z.net_total!==null?z.net_total:null,I=k.useMemo(()=>!(F!=null&&F.items)||!v?(F==null?void 0:F.items)||[]:[...F.items].sort((G,te)=>{let re,me;switch(v){case"invoice_number":re=G.invoice_number||"",me=te.invoice_number||"";break;case"supplier":re=G.supplier_name||G.vendor_name||"",me=te.supplier_name||te.vendor_name||"";break;case"date":re=G.invoice_date||"",me=te.invoice_date||"";break;case"net_total":re=U(G)??-1/0,me=U(te)??-1/0;break;case"gross_total":re=M(G)??-1/0,me=M(te)??-1/0;break;case"status":re=G.status||"",me=te.status||"";break;default:return 0}return typeof re=="string"&&typeof me=="string"?w==="asc"?re.localeCompare(me):me.localeCompare(re):w==="asc"?re-me:me-re}),[F==null?void 0:F.items,v,w]),H=k.useMemo(()=>{var G;if(!I||!m||!(F!=null&&F.groups))return null;const z={};for(const te of I){let re;m==="supplier"?re=te.supplier_name||"Unknown":m==="month"?re=((G=te.invoice_date)==null?void 0:G.substring(0,7))||"Unknown":re="All",z[re]||(z[re]=[]),z[re].push(te)}return z},[I,m,F==null?void 0:F.groups]);return s.jsxs("div",{style:{padding:"20px",maxWidth:"1400px",margin:"0 auto"},children:[s.jsx("h1",{style:{marginBottom:"20px"},children:"Search Invoices"}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"12px",marginBottom:"20px",padding:"16px",backgroundColor:"#f8fafc",borderRadius:"8px"},children:[s.jsx("input",{type:"text",placeholder:"Search invoice number, vendor...",value:t,onChange:z=>r(z.target.value),style:{flex:"1 1 250px",padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"4px",fontSize:"14px"}}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"14px",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:i,onChange:z=>o(z.target.checked)}),"Include line items"]}),s.jsxs("select",{value:a,onChange:z=>l(z.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Suppliers"}),T==null?void 0:T.map(z=>s.jsx("option",{value:z.id,children:z.name},z.id))]}),s.jsxs("select",{value:d,onChange:z=>c(z.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Statuses"}),s.jsx("option",{value:"pending",children:"Pending"}),s.jsx("option",{value:"processed",children:"Processed"}),s.jsx("option",{value:"reviewed",children:"Reviewed"}),s.jsx("option",{value:"confirmed",children:"Confirmed"})]}),s.jsxs("select",{value:m,onChange:z=>y(z.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"No Grouping"}),s.jsx("option",{value:"supplier",children:"Group by Supplier"}),s.jsx("option",{value:"month",children:"Group by Month"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("label",{style:{fontSize:"14px"},children:"From:"}),s.jsx("input",{type:"date",value:u,onChange:z=>f(z.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}}),s.jsx("label",{style:{fontSize:"14px"},children:"To:"}),s.jsx("input",{type:"date",value:p,onChange:z=>g(z.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}})]})]}),A&&s.jsx("p",{children:"Loading..."}),D&&s.jsxs("p",{style:{color:"red"},children:["Error: ",D.message]}),F&&s.jsxs("div",{children:[s.jsxs("p",{style:{marginBottom:"12px",color:"#6b7280"},children:["Found ",F.total_count," invoice",F.total_count!==1?"s":""]}),m&&F.groups?s.jsx("div",{children:F.groups.map(z=>s.jsxs("div",{style:{marginBottom:"16px",border:"1px solid #e5e7eb",borderRadius:"8px",overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>P(z.name),style:{padding:"12px 16px",backgroundColor:"#f1f5f9",cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("span",{style:{fontWeight:600},children:[_.has(z.name)?"▸":"▾"," ",z.name]}),s.jsxs("span",{style:{color:"#6b7280"},children:[z.count," invoice",z.count!==1?"s":"",z.total!==null&&` • ${Td(z.total)}`]})]}),!_.has(z.name)&&(H==null?void 0:H[z.name])&&s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f8fafc"},children:[s.jsxs("th",{style:od,onClick:()=>L("invoice_number"),children:["Invoice #",W("invoice_number")]}),s.jsxs("th",{style:od,onClick:()=>L("supplier"),children:["Supplier",W("supplier")]}),s.jsxs("th",{style:od,onClick:()=>L("date"),children:["Date",W("date")]}),s.jsxs("th",{style:od,onClick:()=>L("net_total"),children:["Net Total",W("net_total")]}),s.jsxs("th",{style:od,onClick:()=>L("gross_total"),children:["Gross Total",W("gross_total")]}),s.jsxs("th",{style:od,onClick:()=>L("status"),children:["Status",W("status")]})]})}),s.jsx("tbody",{children:H[z.name].map(G=>s.jsxs("tr",{style:{borderBottom:"1px solid #e5e7eb"},children:[s.jsx("td",{style:ad,children:s.jsx("a",{href:`/invoice/${G.id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none"},children:G.invoice_number||"-"})}),s.jsx("td",{style:ad,children:G.supplier_name||G.vendor_name||"-"}),s.jsx("td",{style:ad,children:Cm(G.invoice_date)}),s.jsx("td",{style:ad,children:Td(U(G))}),s.jsx("td",{style:ad,children:Td(M(G))}),s.jsx("td",{style:ad,children:O(G.status)})]},G.id))})]})]},z.name))}):s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f1f5f9"},children:[s.jsxs("th",{style:od,onClick:()=>L("invoice_number"),children:["Invoice #",W("invoice_number")]}),s.jsxs("th",{style:od,onClick:()=>L("supplier"),children:["Supplier",W("supplier")]}),s.jsxs("th",{style:od,onClick:()=>L("date"),children:["Date",W("date")]}),s.jsxs("th",{style:od,onClick:()=>L("net_total"),children:["Net Total",W("net_total")]}),s.jsxs("th",{style:od,onClick:()=>L("gross_total"),children:["Gross Total",W("gross_total")]}),s.jsxs("th",{style:od,onClick:()=>L("status"),children:["Status",W("status")]})]})}),s.jsx("tbody",{children:I.map(z=>s.jsxs("tr",{style:{borderBottom:"1px solid #e5e7eb"},children:[s.jsx("td",{style:ad,children:s.jsx("a",{href:`/invoice/${z.id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none"},children:z.invoice_number||"-"})}),s.jsx("td",{style:ad,children:z.supplier_name||z.vendor_name||"-"}),s.jsx("td",{style:ad,children:Cm(z.invoice_date)}),s.jsx("td",{style:ad,children:Td(U(z))}),s.jsx("td",{style:ad,children:Td(M(z))}),s.jsx("td",{style:ad,children:O(z.status)})]},z.id))})]})]})]})}const Hfe={padding:"12px",textAlign:"left",fontWeight:600,fontSize:"14px"},od={...Hfe,cursor:"pointer",userSelect:"none"},ad={padding:"12px",fontSize:"14px"},ah=TK.lineItems;function qfe(){const{token:n}=gn(),e=pi(),t=k.useMemo(()=>wM(),[]),[r,i]=co(ah.query,""),[o,a]=co(ah.supplier,""),[l,d]=co(ah.dateFrom,t.from),[c,u]=co(ah.dateTo,t.to),[f,p]=co(ah.groupBy,""),[g,m]=co(ah.priceChangeFilter,""),[y,v]=co(ah.mappedFilter,""),[x,w]=co(ah.sortColumn,""),[S,_]=co(ah.sortDirection,"asc"),[b,C]=k.useState(null),[T,F]=k.useState(null),[A,D]=k.useState({}),[P,L]=k.useState(""),[W,O]=k.useState([]),[U,M]=k.useState(!1),[I,H]=k.useState(null),[z,G]=k.useState(""),[te,re]=k.useState(""),[me,J]=k.useState(!1),[ne,ye]=k.useState(""),[ke,Ye]=k.useState(!1),[De,qe]=k.useState({}),[ue,Ze]=k.useState(null),ee=Rg(r,300),{data:Z}=Oe({queryKey:["suppliers"],queryFn:async()=>{const ce=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!ce.ok)throw new Error("Failed to fetch suppliers");return ce.json()}}),{data:ge}=Oe({queryKey:["search-settings"],queryFn:async()=>{const ce=await fetch("/api/search/settings",{headers:{Authorization:`Bearer ${n}`}});if(!ce.ok)throw new Error("Failed to fetch search settings");return ce.json()},staleTime:6e4}),{data:Te,isLoading:Be,error:he}=Oe({queryKey:["search-line-items",ee,o,l,c,f,y],queryFn:async()=>{const ce=new URLSearchParams;ee&&ce.set("q",ee),o&&ce.set("supplier_id",o),l&&ce.set("date_from",l),c&&ce.set("date_to",c),f&&ce.set("group_by",f),y&&ce.set("mapped",y),ce.set("limit","200");const Je=await fetch(`/api/search/line-items?${ce}`,{headers:{Authorization:`Bearer ${n}`}});if(!Je.ok)throw new Error("Search failed");return Je.json()},enabled:!!n});k.useEffect(()=>{if(!(Te!=null&&Te.items)||!n)return;const ce=new Map;for(const ct of Te.items)!ct.ingredient_id&&!ct.product_code&&ct.description&&ct.supplier_id&&(ce.has(ct.supplier_id)||ce.set(ct.supplier_id,[]),ce.get(ct.supplier_id).push({description:ct.description,price:ct.most_recent_price??void 0}));if(ce.size===0){qe({});return}const Je={},jt=Array.from(ce.entries()).map(([ct,Se])=>fetch("/api/ingredients/sources/alias-suggestions",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({supplier_id:ct,items:Se})}).then(ot=>ot.ok?ot.json():[]).then(ot=>{for(const ut of ot)Je[`${ct}:${ut.description.toLowerCase()}`]=ut}).catch(()=>{}));Promise.all(jt).then(()=>qe({...Je}))},[Te==null?void 0:Te.items,n]);const He=Ue({mutationFn:async({sourceId:ce,alias:Je})=>{const jt=await fetch(`/api/ingredients/sources/${ce}/aliases`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({alias:Je})});if(!jt.ok)throw new Error("Failed to add alias");return jt.json()},onSuccess:(ce,Je)=>{qe(jt=>{const ct={...jt};for(const Se of Object.keys(ct))Se.endsWith(`:${Je.alias.toLowerCase()}`)&&delete ct[Se];return ct}),Ze(null),e.invalidateQueries({queryKey:["search-line-items"]})}}),Ge=ce=>{ce.supplier_id&&C({isOpen:!0,productCode:ce.product_code,description:ce.description,unit:ce.unit,supplierId:ce.supplier_id,supplierName:ce.supplier_name||"Unknown"})},ae=async ce=>{F(ce),D({pack_quantity:ce.most_recent_pack_quantity?Number(ce.most_recent_pack_quantity):null,unit_size:ce.most_recent_unit_size?Number(ce.most_recent_unit_size):null,unit_size_type:ce.most_recent_unit_size_type,unit_price:ce.most_recent_price!=null?Number(ce.most_recent_price):null}),H(ce.ingredient_id||null),G(ce.ingredient_name||""),re(ce.ingredient_standard_unit||""),J(!1),L(""),O([]),ye(""),Ye(!1),ce.most_recent_unit_size&&ce.most_recent_unit_size_type&&Q(ce.ingredient_standard_unit||void 0,{pack_quantity:ce.most_recent_pack_quantity,unit_size:ce.most_recent_unit_size,unit_size_type:ce.most_recent_unit_size_type,unit_price:ce.most_recent_price}),ce.description&&!ce.ingredient_id&&K(ce.description)},K=async ce=>{if(!ce||ce.length<2){O([]);return}M(!0);try{const Je=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(ce)}`,{headers:{Authorization:`Bearer ${n}`}});Je.ok&&O(await Je.json())}catch{}M(!1)},de=ce=>{H(ce.id),G(ce.name),re(ce.standard_unit),L(""),O([]),A.unit_size_type||D(Je=>({...Je,unit_size_type:ce.standard_unit})),Q(ce.standard_unit)},Y=ce=>{e.invalidateQueries({queryKey:["search-line-items"]}),X()},Q=(ce,Je)=>{var Qt;const jt=Je?{...A,...Je}:A,ct=ce||te||jt.unit_size_type,Se=jt.pack_quantity||1,ot=jt.unit_size,ut=jt.unit_size_type,Ot=jt.unit_price;if(!ot||!ut||!ct){ye("");return}const on=(Qt={g:{g:1,kg:.001},kg:{g:1e3,kg:1},oz:{g:28.3495,kg:.0283495},ml:{ml:1,ltr:.001},cl:{ml:10,ltr:.01},ltr:{ml:1e3,ltr:1},each:{each:1}}[ut])==null?void 0:Qt[ct];if(!on){ye(ut!==ct?`Cannot convert ${ut} → ${ct}`:`${ot}${ut}`);return}const Ke=Se*ot*on,Rt=Ot?Ot/Ke:null;let Cr=`${Se>1?`${Se} × ${ot}${ut} = `:""}${Ke.toFixed(Ke%1?2:0)} ${ct}`;Rt&&(Cr+=` → £${Rt.toFixed(4)} per ${ct}`,ct==="g"?Cr+=` (£${(Rt*1e3).toFixed(2)}/kg)`:ct==="ml"&&(Cr+=` (£${(Rt*1e3).toFixed(2)}/ltr)`)),ye(Cr)},X=()=>{F(null),D({}),H(null),G(""),re(""),J(!1),L(""),O([]),ye("")},pe=async()=>{if(T){Ye(!0);try{if(T.most_recent_line_item_id&&T.most_recent_invoice_id&&await fetch(`/api/invoices/${T.most_recent_invoice_id}/line-items/${T.most_recent_line_item_id}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({pack_quantity:A.pack_quantity||null,unit_size:A.unit_size||null,unit_size_type:A.unit_size_type||null,...I?{ingredient_id:I}:{}})}),I&&T.supplier_id){const ce={supplier_id:T.supplier_id,pack_quantity:A.pack_quantity||1,unit_size:A.unit_size||null,unit_size_type:A.unit_size_type||te||null};T.product_code?ce.product_code=T.product_code:T.description&&(ce.description_pattern=T.description.substring(0,100).toLowerCase().trim()),A.unit_price&&(ce.latest_unit_price=A.unit_price),T.most_recent_invoice_id&&(ce.invoice_id=T.most_recent_invoice_id),await fetch(`/api/ingredients/${I}/sources`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(ce)})}e.invalidateQueries({queryKey:["search-line-items"]}),X()}catch(ce){console.error("Failed to save mapping:",ce)}Ye(!1)}},we=ce=>{x===ce?_(S==="asc"?"desc":"asc"):(w(ce),_("asc"))},Ne=ce=>x!==ce?null:S==="asc"?" ▲":" ▼",st=k.useMemo(()=>Te!=null&&Te.items?g?Te.items.filter(ce=>g==="no_history"?ce.price_change_status==="no_history":g==="no_change"?ce.price_change_status==="consistent"||ce.price_change_status==="acknowledged":g==="increase"?ce.price_change_percent!==null&&ce.price_change_percent>0:g==="decrease"?ce.price_change_percent!==null&&ce.price_change_percent<0:!0):Te.items:[],[Te==null?void 0:Te.items,g]),Ve=k.useMemo(()=>!st.length||!x?st:[...st].sort((Je,jt)=>{let ct,Se;switch(x){case"code":ct=Je.product_code||"",Se=jt.product_code||"";break;case"description":ct=Je.description||"",Se=jt.description||"";break;case"supplier":ct=Je.supplier_name||"",Se=jt.supplier_name||"";break;case"price":ct=Je.most_recent_price??-1/0,Se=jt.most_recent_price??-1/0;break;case"ingredient_rate":ct=Je.price_per_std_unit!=null?typeof Je.price_per_std_unit=="string"?parseFloat(Je.price_per_std_unit):Je.price_per_std_unit:-1/0,Se=jt.price_per_std_unit!=null?typeof jt.price_per_std_unit=="string"?parseFloat(jt.price_per_std_unit):jt.price_per_std_unit:-1/0;break;case"total_quantity":ct=Je.total_quantity??-1/0,Se=jt.total_quantity??-1/0;break;case"occurrence_count":ct=Je.occurrence_count??0,Se=jt.occurrence_count??0;break;case"last_invoice":ct=Je.most_recent_invoice_number||"",Se=jt.most_recent_invoice_number||"";break;case"last_date":ct=Je.most_recent_date||"",Se=jt.most_recent_date||"";break;default:return 0}return typeof ct=="string"&&typeof Se=="string"?S==="asc"?ct.localeCompare(Se):Se.localeCompare(ct):S==="asc"?ct-Se:Se-ct}),[st,x,S]),Re=ce=>{const Je=Khe(ce.price_change_status);if(!Je.icon)return null;if(ce.price_change_status==="consistent"||ce.price_change_status==="acknowledged"){const ct=Math.ceil((new Date(c).getTime()-new Date(l).getTime())/864e5)+30;return s.jsx("div",{style:{fontSize:"0.75rem",marginTop:"2px",color:Je.color,cursor:"help"},title:`Price stable over last ${ct} days -Click 📊 to see full 12-month history`,children:s.jsx("span",{style:{fontWeight:"bold"},children:Je.icon})})}if((ce.price_change_status==="amber"||ce.price_change_status==="red")&&ce.price_change_percent!==null&&ce.price_change_percent!==0){const jt=ce.price_change_percent>0,ct=jt?"▲":"▼",Se=jt?"#ef4444":"#22c55e",ot=jt?"increased":"decreased",Ot=Math.ceil((new Date(c).getTime()-new Date(l).getTime())/(1e3*60*60*24))+30;return s.jsxs("div",{style:{fontSize:"0.75rem",marginTop:"2px",color:Se,cursor:"help"},title:`Price ${ot} ${Math.abs(ce.price_change_percent).toFixed(1)}% over last ${Ot} days -Click 📊 to see full history`,children:[s.jsx("span",{style:{fontWeight:"bold"},children:ct})," ",Math.abs(ce.price_change_percent).toFixed(1),"%"]})}return ce.price_change_status==="amber"||ce.price_change_status==="red"?s.jsx("div",{style:{fontSize:"0.75rem",marginTop:"2px",color:Je.color},children:s.jsx("span",{style:{fontWeight:"bold"},children:Je.icon})}):null},Le=ce=>{if(ce.price_per_std_unit==null)return null;const Je=typeof ce.price_per_std_unit=="string"?parseFloat(ce.price_per_std_unit):ce.price_per_std_unit,jt=ce.ingredient_standard_unit||"?";if(jt==="g"&&Je<1)return`£${(Je*1e3).toFixed(2)}/kg`;if(jt==="ml"&&Je<1)return`£${(Je*1e3).toFixed(2)}/ltr`;const ct=Je>=1?2:4;return`£${Je.toFixed(ct)}/${jt}`},rt=()=>{i(""),a(""),m(""),v(""),p("");const ce=wM();d(ce.from),u(ce.to)},$e=r||o||g||y||f;return s.jsxs("div",{style:{padding:"20px",maxWidth:"1600px",margin:"0 auto"},children:[s.jsx("h1",{style:{marginBottom:"20px"},children:"Search Line Items"}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"12px",marginBottom:"20px",padding:"16px",backgroundColor:"#f8fafc",borderRadius:"8px"},children:[s.jsx("input",{type:"text",placeholder:"Search product code, description...",value:r,onChange:ce=>i(ce.target.value),style:{flex:"1 1 300px",padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"4px",fontSize:"14px"}}),s.jsxs("select",{value:o,onChange:ce=>a(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Suppliers"}),Z==null?void 0:Z.map(ce=>s.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),s.jsxs("select",{value:g,onChange:ce=>m(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Price Changes"}),s.jsx("option",{value:"no_history",children:"No History"}),s.jsx("option",{value:"no_change",children:"✓ No Change"}),s.jsx("option",{value:"increase",children:"▲ Price Increase"}),s.jsx("option",{value:"decrease",children:"▼ Price Decrease"})]}),s.jsxs("select",{value:y,onChange:ce=>v(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"All Mapping"}),s.jsx("option",{value:"yes",children:"Mapped to Ingredient"}),s.jsx("option",{value:"no",children:"Not Mapped"})]}),s.jsxs("select",{value:f,onChange:ce=>p(ce.target.value),style:{padding:"8px",border:"1px solid #d1d5db",borderRadius:"4px"},children:[s.jsx("option",{value:"",children:"No Grouping"}),s.jsx("option",{value:"supplier",children:"Group by Supplier"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("label",{style:{fontSize:"14px"},children:"From:"}),s.jsx("input",{type:"date",value:l,onChange:ce=>d(ce.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}}),s.jsx("label",{style:{fontSize:"14px"},children:"To:"}),s.jsx("input",{type:"date",value:c,onChange:ce=>u(ce.target.value),style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px"}})]}),$e&&s.jsx("button",{onClick:rt,style:{padding:"8px 16px",background:"#ef4444",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},children:"Clear Filters"})]}),s.jsxs("div",{style:{display:"flex",gap:"16px",marginBottom:"16px",fontSize:"13px",color:"#6b7280",flexWrap:"wrap"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#22c55e",fontWeight:"bold"},children:"✓"})," Price consistent"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#ef4444",fontWeight:"bold"},children:"▲"})," Price increase"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#22c55e",fontWeight:"bold"},children:"▼"})," Price decrease"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#28a745"},children:"⚖"})," Mapped to ingredient"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#ccc"},children:"⚖"})," Not mapped"]})]}),Be&&s.jsx("p",{children:"Loading..."}),he&&s.jsxs("p",{style:{color:"red"},children:["Error: ",he.message]}),Te&&s.jsxs("div",{children:[s.jsxs("p",{style:{marginBottom:"12px",color:"#6b7280"},children:["Found ",Te.total_count," unique item",Te.total_count!==1?"s":"",(g||y)&&` (showing ${Ve.length} filtered)`]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:"1000px"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{backgroundColor:"#f1f5f9"},children:[s.jsxs("th",{style:lh,onClick:()=>we("code"),children:["Code",Ne("code")]}),s.jsxs("th",{style:{...lh,minWidth:"150px"},onClick:()=>we("description"),children:["Description",Ne("description")]}),s.jsxs("th",{style:lh,onClick:()=>we("supplier"),children:["Supplier",Ne("supplier")]}),s.jsxs("th",{style:lh,onClick:()=>we("price"),children:["Price",Ne("price")]}),s.jsx("th",{style:{...NK,textAlign:"center",width:"40px"},children:"⚖"}),s.jsxs("th",{style:{...lh,textAlign:"right"},onClick:()=>we("ingredient_rate"),children:["Ingredient Rate",Ne("ingredient_rate")]}),s.jsxs("th",{style:lh,onClick:()=>we("total_quantity"),children:["Total Qty",Ne("total_quantity")]}),s.jsxs("th",{style:lh,onClick:()=>we("occurrence_count"),children:["#",Ne("occurrence_count")]}),s.jsxs("th",{style:lh,onClick:()=>we("last_invoice"),children:["Last Invoice",Ne("last_invoice")]}),s.jsxs("th",{style:lh,onClick:()=>we("last_date"),children:["Last Date",Ne("last_date")]})]})}),s.jsx("tbody",{children:Ve.map((ce,Je)=>s.jsxs("tr",{style:{borderBottom:"1px solid #e5e7eb"},children:[s.jsx("td",{style:Yc,children:ce.product_code||"-"}),s.jsxs("td",{style:Yc,children:[s.jsxs("div",{children:[ce.description||"-",ce.has_definition&&s.jsx("span",{title:`${ce.portions_per_unit||"?"} portions per unit`,style:{marginLeft:"6px",color:"#8b5cf6"},children:"📦"})]}),!ce.ingredient_id&&!ce.product_code&&ce.description&&ce.supplier_id&&(()=>{const jt=`${ce.supplier_id}:${ce.description.toLowerCase()}`,ct=De[jt];if(!ct)return null;const Se=ue===jt;return s.jsxs("div",{style:{fontSize:"0.7rem",color:"#0c5460",background:"#d1ecf1",padding:"0.2rem 0.4rem",borderRadius:"3px",marginTop:"3px",border:"1px solid #bee5eb",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.4rem"},children:[s.jsxs("span",{children:['Similar to "',ct.canonical_description,'"',ct.ingredient_name&&s.jsxs(s.Fragment,{children:[" → ",ct.ingredient_name]})," ","(",Math.round(ct.similarity*100),"%)"]}),s.jsx("button",{type:"button",onClick:ot=>{ot.stopPropagation(),Ze(jt),He.mutate({sourceId:ct.source_id,alias:ce.description})},disabled:Se,style:{padding:"0.15rem 0.4rem",background:"#17a2b8",color:"white",border:"none",borderRadius:"3px",cursor:Se?"default":"pointer",fontSize:"0.65rem",fontWeight:"500",whiteSpace:"nowrap",opacity:Se?.6:1},children:Se?"Adding...":"+ Alias"})]})})()]}),s.jsx("td",{style:Yc,children:ce.supplier_name||"-"}),s.jsx("td",{style:Yc,children:s.jsxs("div",{children:[s.jsxs("div",{children:[Td(ce.most_recent_price),s.jsx("span",{onClick:()=>Ge(ce),style:{marginLeft:"6px",cursor:"pointer"},title:"View price history",children:"📊"})]}),Re(ce)]})}),s.jsx("td",{style:{...Yc,textAlign:"center",padding:"4px"},children:s.jsx("button",{type:"button",onClick:()=>ae(ce),style:{padding:"4px 6px",background:"transparent",border:`1px solid ${ce.ingredient_id?"#28a745":"#ddd"}`,borderRadius:"4px",cursor:"pointer",color:ce.ingredient_id?"#28a745":"#999",fontSize:"16px",lineHeight:1,...ce.ingredient_id?{background:"#e8f5e9"}:{}},title:ce.ingredient_id?`Mapped to: ${ce.ingredient_name} -Click to view/edit mapping`:"Click to map to an ingredient",children:"⚖"})}),s.jsx("td",{style:{...Yc,textAlign:"right"},children:ce.ingredient_id?s.jsxs("div",{children:[s.jsx("span",{style:{color:"#16a34a",fontWeight:600},children:Le(ce)||"-"}),s.jsx("div",{style:{fontSize:"0.75rem",color:"#6b7280",marginTop:"2px"},children:ce.ingredient_name})]}):s.jsx("span",{style:{color:"#d1d5db"},children:"-"})}),s.jsx("td",{style:Yc,children:Ex(ce.total_quantity)}),s.jsx("td",{style:Yc,children:ce.occurrence_count}),s.jsx("td",{style:Yc,children:s.jsx("a",{href:`/invoice/${ce.most_recent_invoice_id}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"none"},children:ce.most_recent_invoice_number||"-"})}),s.jsx("td",{style:Yc,children:Cm(ce.most_recent_date)})]},`${ce.product_code}-${ce.description}-${ce.supplier_id}-${Je}`))})]})})]}),b&&s.jsx(FK,{isOpen:b.isOpen,onClose:()=>C(null),productCode:b.productCode,description:b.description,unit:b.unit,supplierId:b.supplierId,supplierName:b.supplierName}),T&&s.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},onClick:X,children:s.jsxs("div",{style:{background:"#fff",borderRadius:"12px",padding:"1.5rem",width:"650px",maxWidth:"95vw",maxHeight:"90vh",overflowY:"auto"},onClick:ce=>ce.stopPropagation(),children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[s.jsx("h3",{style:{margin:0},children:"Ingredient Mapping"}),s.jsx("button",{onClick:X,style:{background:"none",border:"none",fontSize:"1.5rem",cursor:"pointer",color:"#666"},children:"×"})]}),s.jsxs("div",{style:{padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",marginBottom:"1rem",fontSize:"0.9rem"},children:[s.jsx("strong",{children:T.description||T.product_code||"Unknown item"}),T.supplier_name&&s.jsxs("span",{style:{marginLeft:"0.75rem",color:"#666"},children:["(",T.supplier_name,")"]}),T.most_recent_price!=null&&s.jsxs("span",{style:{marginLeft:"0.75rem",color:"#666"},children:["£",Number(T.most_recent_price).toFixed(2)]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("label",{style:{fontWeight:600,fontSize:"0.9rem",display:"block",marginBottom:"0.5rem"},children:["Ingredient ",I&&s.jsxs("span",{style:{color:"#28a745",fontWeight:"normal"},children:["(",z,")"]})]}),I?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem 0.75rem",background:"#d4edda",borderRadius:"6px",border:"1px solid #c3e6cb"},children:[s.jsxs("span",{style:{flex:1},children:[z," ",s.jsxs("span",{style:{color:"#666",fontSize:"0.85rem"},children:["(",te,")"]})]}),s.jsx("button",{onClick:()=>{H(null),G(""),re(""),ye("")},style:{background:"none",border:"none",cursor:"pointer",color:"#666",fontSize:"1.1rem"},children:"×"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{type:"text",value:P,onChange:ce=>{L(ce.target.value),K(ce.target.value)},placeholder:"Search ingredients...",style:{padding:"8px 12px",border:"1px solid #d1d5db",borderRadius:"4px",fontSize:"14px",width:"100%",boxSizing:"border-box"}}),U&&s.jsx("span",{style:{position:"absolute",right:"10px",top:"10px",color:"#999"},children:"..."})]}),W.length>0&&s.jsx("div",{style:{border:"1px solid #ddd",borderRadius:"0 0 6px 6px",maxHeight:"200px",overflowY:"auto",background:"#fff"},children:W.map(ce=>s.jsxs("div",{onClick:()=>de(ce),style:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem",display:"flex",justifyContent:"space-between"},onMouseOver:Je=>Je.currentTarget.style.background="#f0f7ff",onMouseOut:Je=>Je.currentTarget.style.background="#fff",children:[s.jsxs("span",{children:[ce.name," ",s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:["(",ce.standard_unit,")"]})]}),s.jsxs("span",{style:{color:"#999",fontSize:"0.8rem"},children:[ce.category_name||""," ",ce.similarity?`${(ce.similarity*100).toFixed(0)}%`:""]})]},ce.id))}),s.jsx("button",{onClick:()=>J(!0),style:{marginTop:"0.5rem",padding:"0.4rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.85rem"},children:"+ Create new ingredient"})]})]}),s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("label",{style:{fontWeight:600,fontSize:"0.9rem",display:"block",marginBottom:"0.25rem"},children:I?`How much ${z} is in this line item?`:"Unit size & pricing"}),s.jsxs("div",{style:{fontSize:"0.8rem",color:"#888",marginBottom:"0.5rem"},children:[T.description,T.most_recent_price!=null?` @ £${Number(T.most_recent_price).toFixed(2)}`:""]}),s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem",alignItems:"flex-end"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",display:"block"},children:"Contains"}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",step:"0.1",value:A.unit_size||"",onChange:ce=>{const Je={...A,unit_size:parseFloat(ce.target.value)||null};D(Je),Q(void 0,Je)},onFocus:ce=>ce.target.select(),style:{padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:"4px",width:"70px",fontSize:"14px"},placeholder:"e.g., 2"}),s.jsxs("select",{value:A.unit_size_type||te||"",onChange:ce=>{const Je={...A,unit_size_type:ce.target.value||null};D(Je),Q(void 0,Je)},style:{padding:"6px",border:"1px solid #d1d5db",borderRadius:"4px",width:"60px",fontSize:"14px"},children:[s.jsx("option",{value:"",children:"--"}),s.jsx("option",{value:"each",children:"each"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"}),s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"oz",children:"oz"}),s.jsx("option",{value:"cl",children:"cl"})]}),te&&A.unit_size_type&&A.unit_size_type!==te&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#999"},children:["→ ",te]})]})]}),s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",display:"block"},children:"Pack of"}),s.jsx("input",{type:"number",value:A.pack_quantity||"",onChange:ce=>{const Je={...A,pack_quantity:parseInt(ce.target.value)||null};D(Je),Q(void 0,Je)},onFocus:ce=>ce.target.select(),style:{padding:"6px 8px",border:"1px solid #d1d5db",borderRadius:"4px",width:"50px",fontSize:"14px"},placeholder:"1"})]}),s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",display:"block"},children:"Line Price"}),s.jsx("span",{style:{fontSize:"0.9rem",fontWeight:500},children:A.unit_price?`£${Number(A.unit_price).toFixed(2)}`:"--"})]})]}),ne&&s.jsx("div",{style:{marginTop:"0.5rem",padding:"0.5rem 0.75rem",background:"#e8f5e9",borderRadius:"6px",fontSize:"0.9rem",color:"#2e7d32",fontWeight:500},children:ne})]}),s.jsxs("div",{style:{display:"flex",gap:"0.75rem",justifyContent:"flex-end"},children:[s.jsx("button",{onClick:X,style:{padding:"0.5rem 1.25rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer"},children:"Cancel"}),s.jsx("button",{onClick:pe,disabled:ke,style:{padding:"0.5rem 1.25rem",background:"#28a745",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",opacity:ke?.6:1},children:ke?"Saving...":I?"Save & Map Ingredient":"Save"})]})]})}),s.jsx(A0,{open:me,onClose:()=>J(!1),onSaved:Y,prePopulateName:P||"",preSelectLineItem:T?{product_code:T.product_code,description:T.description,supplier_id:T.supplier_id,supplier_name:T.supplier_name,unit:T.unit,most_recent_price:T.most_recent_price!=null?Number(T.most_recent_price):null,total_quantity:T.total_quantity,occurrence_count:T.occurrence_count,most_recent_invoice_id:T.most_recent_invoice_id,most_recent_line_number:T.most_recent_line_number,most_recent_pack_quantity:T.most_recent_pack_quantity,most_recent_unit_size:T.most_recent_unit_size,most_recent_unit_size_type:T.most_recent_unit_size_type,ingredient_id:T.ingredient_id,ingredient_name:T.ingredient_name}:null})]})}const NK={padding:"12px",textAlign:"left",fontWeight:600,fontSize:"14px"},lh={...NK,cursor:"pointer",userSelect:"none"},Yc={padding:"12px",fontSize:"14px"},VN={DRAFT:{bg:"#e0e0e0",color:"#555"},PENDING:{bg:"#e3f2fd",color:"#1565c0"},LINKED:{bg:"#d4edda",color:"#155724"},CLOSED:{bg:"#f5f5f5",color:"#666"},CANCELLED:{bg:"#ffebee",color:"#c62828"}};function Vfe(){var m;const{token:n}=gn(),[e,t]=k.useState("DRAFT,PENDING"),[r,i]=k.useState(""),[o,a]=k.useState(null),[l,d]=k.useState(!1),{data:c}=Oe({queryKey:["suppliers"],queryFn:async()=>{const y=await fetch("/api/suppliers/",{headers:{Authorization:`Bearer ${n}`}});if(!y.ok)throw new Error("Failed to fetch suppliers");return y.json()},enabled:!!n}),u=new URLSearchParams;e&&u.append("status",e),r&&u.append("supplier_id",r);const{data:f,refetch:p}=Oe({queryKey:["purchase-orders",e,r],queryFn:async()=>{const y=await fetch(`/api/purchase-orders/?${u}`,{headers:{Authorization:`Bearer ${n}`}});if(!y.ok)throw new Error("Failed to fetch purchase orders");return y.json()},enabled:!!n}),g=y=>new Date(y+"T00:00:00").toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"});return s.jsxs("div",{children:[s.jsxs("div",{style:ti.headerRow,children:[s.jsx("h2",{style:ti.pageTitle,children:"Purchase Orders"}),s.jsx("button",{style:ti.newBtn,onClick:()=>d(!0),children:"+ New PO"})]}),s.jsxs("div",{style:ti.filterBar,children:[s.jsx("div",{style:ti.statusTabs,children:[{label:"Open",value:"DRAFT,PENDING"},{label:"All",value:""},{label:"Draft",value:"DRAFT"},{label:"Pending",value:"PENDING"},{label:"Linked",value:"LINKED"},{label:"Closed",value:"CLOSED"}].map(y=>s.jsx("button",{style:{...ti.filterTab,...e===y.value?ti.filterTabActive:{}},onClick:()=>t(y.value),children:y.label},y.value))}),s.jsxs("select",{value:r,onChange:y=>i(y.target.value),style:ti.filterSelect,children:[s.jsx("option",{value:"",children:"All Suppliers"}),(m=c==null?void 0:c.suppliers)==null?void 0:m.map(y=>s.jsx("option",{value:y.id,children:y.name},y.id))]})]}),s.jsx("div",{style:ti.tableContainer,children:s.jsxs("table",{style:ti.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:ti.th,children:"Date"}),s.jsx("th",{style:ti.th,children:"Supplier"}),s.jsx("th",{style:ti.th,children:"Type"}),s.jsx("th",{style:ti.th,children:"Reference"}),s.jsx("th",{style:{...ti.th,textAlign:"right"},children:"Total"}),s.jsx("th",{style:ti.th,children:"Status"}),s.jsx("th",{style:ti.th,children:"Created"})]})}),s.jsx("tbody",{children:!f||f.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:7,style:ti.emptyTd,children:"No purchase orders found"})}):f.map(y=>{const v=VN[y.status]||VN.DRAFT;return s.jsxs("tr",{style:ti.row,onClick:()=>a(y.id),children:[s.jsx("td",{style:ti.td,children:g(y.order_date)}),s.jsx("td",{style:ti.td,children:y.supplier_name||"-"}),s.jsx("td",{style:ti.td,children:s.jsx("span",{style:ti.typeBadge,children:y.order_type==="itemised"?"Itemised":"Single Value"})}),s.jsx("td",{style:ti.td,children:y.order_reference||"-"}),s.jsx("td",{style:{...ti.td,textAlign:"right",fontWeight:500},children:y.total_amount!=null?`£${y.total_amount.toFixed(2)}`:"-"}),s.jsx("td",{style:ti.td,children:s.jsx("span",{style:{...ti.statusBadge,background:v.bg,color:v.color},children:y.status})}),s.jsx("td",{style:{...ti.td,fontSize:"0.8rem",color:"#888"},children:y.created_by_name||""})]},y.id)})})]})}),s.jsx(TT,{isOpen:!!o,onClose:()=>a(null),onSaved:()=>p(),poId:o}),s.jsx(TT,{isOpen:l,onClose:()=>d(!1),onSaved:()=>p()})]})}const ti={headerRow:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},pageTitle:{margin:0,color:"#1a1a2e"},newBtn:{padding:"0.6rem 1.2rem",background:"#1a1a2e",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},filterBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem",gap:"1rem",flexWrap:"wrap"},statusTabs:{display:"flex",gap:"0.25rem"},filterTab:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",background:"white",cursor:"pointer",fontSize:"0.85rem",fontWeight:500},filterTabActive:{background:"#1a1a2e",color:"white",borderColor:"#1a1a2e"},filterSelect:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.85rem"},tableContainer:{background:"white",borderRadius:"8px",boxShadow:"0 1px 4px rgba(0,0,0,0.08)",overflow:"auto"},table:{width:"100%",borderCollapse:"collapse"},th:{textAlign:"left",padding:"0.75rem 1rem",borderBottom:"2px solid #eee",fontWeight:600,color:"#666",fontSize:"0.85rem",whiteSpace:"nowrap"},td:{padding:"0.75rem 1rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},emptyTd:{padding:"2rem",textAlign:"center",color:"#999"},row:{cursor:"pointer",transition:"background 0.15s"},statusBadge:{display:"inline-block",padding:"0.2rem 0.6rem",borderRadius:"12px",fontSize:"0.75rem",fontWeight:600},typeBadge:{fontSize:"0.8rem",color:"#666"}};function T0({flags:n,size:e="small",source_ingredients:t}){const r=n.filter(a=>(a.active??a.is_active)!==!1);if(!r.length)return null;const i=e==="small"?"0.7rem":"0.8rem",o=e==="small"?"1px 5px":"2px 8px";return s.jsx("div",{style:GN.container,children:r.map((a,l)=>{const d=a.name||a.flag_name||"",c=a.code||a.flag_code||"",u=a.icon||a.flag_icon||"",f=a.propagation||a.propagation_type||"contains",p=a.excludable??a.excludable_on_request??!1,g=f==="contains"?"#dc3545":"#28a745",m=t==null?void 0:t[d];let y=d;return m&&m.length>0&&(y+=` — from: ${m.join(", ")}`),p&&(y+=" (excludable on request)"),s.jsxs("span",{title:y,style:{...GN.badge,background:g,fontSize:i,padding:o,border:p?"1.5px dashed rgba(255,255,255,0.6)":"none",opacity:p?.85:1},children:[u?`${u} `:"",c||d.substring(0,3)]},l)})})}const GN={container:{display:"flex",flexWrap:"wrap",gap:"3px",alignItems:"center"},badge:{display:"inline-block",borderRadius:"10px",color:"white",fontWeight:600,whiteSpace:"nowrap",lineHeight:1.4}};function Gfe(){const{token:n}=gn(),e=pi(),[t,r]=k.useState(""),[i,o]=k.useState(""),[a,l]=k.useState(!1),[d,c]=k.useState(!1),[u,f]=k.useState(null),[p,g]=k.useState(!1),[m,y]=k.useState(null),{data:v}=Oe({queryKey:["ingredient-categories"],queryFn:async()=>{const T=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${n}`}});if(!T.ok)throw new Error("Failed to fetch categories");return T.json()},enabled:!!n}),{data:x,isLoading:w}=Oe({queryKey:["ingredients",t,i,a,d],queryFn:async()=>{const T=new URLSearchParams;t&&T.set("search",t),i&&T.set("category_id",i),a&&T.set("unmapped","true"),d&&T.set("archived","true");const F=await fetch(`/api/ingredients?${T}`,{headers:{Authorization:`Bearer ${n}`}});if(!F.ok)throw new Error("Failed to fetch ingredients");return F.json()},enabled:!!n}),{data:S}=Oe({queryKey:["ingredient-sources",u],queryFn:async()=>{const T=await fetch(`/api/ingredients/${u}/sources`,{headers:{Authorization:`Bearer ${n}`}});if(!T.ok)throw new Error("Failed to fetch sources");return T.json()},enabled:!!n&&!!u}),_=Ue({mutationFn:async T=>{if(!(await fetch(`/api/ingredients/${T}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to archive")},onSuccess:()=>e.invalidateQueries({queryKey:["ingredients"]})}),b=Ue({mutationFn:async T=>{if(!(await fetch(`/api/ingredients/${T}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_archived:!1})})).ok)throw new Error("Failed to unarchive")},onSuccess:()=>e.invalidateQueries({queryKey:["ingredients"]})}),C=T=>{y({id:T.id,name:T.name,category_id:T.category_id,standard_unit:T.standard_unit,yield_percent:T.yield_percent,manual_price:T.manual_price,notes:T.notes,is_prepackaged:T.is_prepackaged,is_free:T.is_free,product_ingredients:T.product_ingredients,has_label_image:T.has_label_image}),g(!0)};return s.jsxs("div",{style:vn.page,children:[s.jsxs("div",{style:vn.header,children:[s.jsx("h2",{style:{margin:0},children:"Ingredient Library"}),s.jsx("button",{onClick:()=>{y(null),g(!0)},style:vn.primaryBtn,children:"+ Create Ingredient"})]}),s.jsxs("div",{style:vn.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search ingredients...",value:t,onChange:T=>r(T.target.value),style:vn.searchInput}),s.jsxs("select",{value:i,onChange:T=>o(T.target.value),style:vn.select,children:[s.jsx("option",{value:"",children:"All Categories"}),v==null?void 0:v.map(T=>s.jsxs("option",{value:T.id,children:[T.name," (",T.ingredient_count,")"]},T.id))]}),s.jsxs("label",{style:vn.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:a,onChange:T=>l(T.target.checked)}),"Unmapped only"]}),s.jsxs("label",{style:vn.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:d,onChange:T=>c(T.target.checked)}),"Show Archived"]})]}),s.jsxs("div",{style:vn.statsBar,children:[s.jsxs("span",{children:[(x==null?void 0:x.length)||0," ",d?"archived":""," ingredients"]}),s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{children:[(x==null?void 0:x.filter(T=>T.source_count===0).length)||0," unmapped"]})]}),w?s.jsx("div",{style:vn.loading,children:"Loading ingredients..."}):s.jsxs("table",{style:vn.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:vn.th,children:"Name"}),s.jsx("th",{style:vn.th,children:"Category"}),s.jsx("th",{style:vn.th,children:"Unit"}),s.jsx("th",{style:vn.th,children:"Yield %"}),s.jsx("th",{style:vn.th,children:"Sources"}),s.jsx("th",{style:vn.th,children:"Price/Unit"}),s.jsx("th",{style:vn.th,children:"Flags"}),s.jsx("th",{style:vn.th,children:"Actions"})]})}),s.jsx("tbody",{children:x==null?void 0:x.map(T=>{var F;return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{style:{...vn.tr,cursor:"pointer",...T.is_archived?{opacity:.5}:{}},onClick:()=>f(u===T.id?null:T.id),children:[s.jsxs("td",{style:vn.td,children:[s.jsx("span",{style:{fontWeight:500,...T.is_archived?{textDecoration:"line-through"}:{}},children:T.name}),T.is_archived&&s.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.7rem",color:"#999",fontStyle:"italic"},children:"archived"})]}),s.jsx("td",{style:vn.td,children:T.category_name||"-"}),s.jsx("td",{style:vn.td,children:T.standard_unit}),s.jsx("td",{style:vn.td,children:s.jsxs("span",{style:{color:T.yield_percent<100?"#e94560":"#666"},children:[T.yield_percent,"%"]})}),s.jsx("td",{style:vn.td,children:s.jsx("span",{style:{background:T.source_count>0?"#22c55e":"#f59e0b",color:"white",padding:"2px 8px",borderRadius:"10px",fontSize:"0.75rem",fontWeight:600},children:T.source_count})}),s.jsx("td",{style:vn.td,children:T.effective_price!=null?(()=>{const A=T.effective_price,D=T.standard_unit;return D==="g"&&A<1?`£${(A*1e3).toFixed(2)}/kg`:D==="ml"&&A<1?`£${(A*1e3).toFixed(2)}/ltr`:`£${A>=1?A.toFixed(2):A.toFixed(4)}/${D}`})():s.jsx("span",{style:{color:"#aaa"},children:"-"})}),s.jsx("td",{style:vn.td,children:s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"3px",alignItems:"center"},children:[s.jsx(T0,{flags:T.flags.map(A=>({name:A.flag_name,code:A.flag_code||void 0,category_name:A.category_name,propagation:A.propagation_type}))}),(F=T.none_categories)==null?void 0:F.map(A=>s.jsxs("span",{title:`${A}: None apply`,style:{display:"inline-block",borderRadius:"10px",color:"white",fontWeight:600,whiteSpace:"nowrap",lineHeight:1.4,fontSize:"0.7rem",padding:"1px 5px",background:"#999"},children:[A.substring(0,3),": None"]},A))]})}),s.jsxs("td",{style:vn.td,children:[s.jsx("button",{onClick:A=>{A.stopPropagation(),C(T)},style:vn.smallBtn,children:"Edit"}),T.is_archived?s.jsx("button",{onClick:A=>{A.stopPropagation(),b.mutate(T.id)},style:{...vn.smallBtn,color:"#22c55e"},children:"Unarchive"}):s.jsx("button",{onClick:A=>{A.stopPropagation(),_.mutate(T.id)},style:{...vn.smallBtn,color:"#e94560"},children:"Archive"})]})]},T.id),u===T.id&&s.jsx("tr",{children:s.jsx("td",{colSpan:8,style:vn.expandedTd,children:s.jsxs("div",{style:vn.sourcesSection,children:[s.jsx("h4",{style:{margin:"0 0 8px 0"},children:"Supplier Sources"}),S&&S.length>0?s.jsxs("table",{style:{...vn.table,margin:0},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:vn.thSmall,children:"Supplier"}),s.jsx("th",{style:vn.thSmall,children:"Code/Pattern"}),s.jsx("th",{style:vn.thSmall,children:"Pack"}),s.jsx("th",{style:vn.thSmall,children:"Last Price"}),s.jsxs("th",{style:vn.thSmall,children:["Price/",T.standard_unit]}),s.jsx("th",{style:vn.thSmall,children:"Last Invoice"})]})}),s.jsx("tbody",{children:S.map(A=>{var D;return s.jsxs("tr",{children:[s.jsx("td",{style:vn.tdSmall,children:A.supplier_name}),s.jsx("td",{style:vn.tdSmall,children:A.product_code&&((D=A.supplier_name)!=null&&D.toLowerCase().includes("brakes"))?s.jsx("a",{href:`https://www.brake.co.uk/p/${A.product_code}`,target:"_blank",rel:"noopener noreferrer",style:{color:"#2563eb",textDecoration:"underline"},title:"View on Brakes website",children:A.product_code}):A.product_code||A.description_pattern||"-"}),s.jsx("td",{style:vn.tdSmall,children:A.pack_quantity&&A.unit_size?`${A.pack_quantity}×${A.unit_size}${A.unit_size_type||""}`:"-"}),s.jsx("td",{style:vn.tdSmall,children:A.latest_unit_price!=null?`£${A.latest_unit_price.toFixed(2)}`:"-"}),s.jsx("td",{style:vn.tdSmall,children:A.price_per_std_unit!=null?(()=>{const P=typeof A.price_per_std_unit=="string"?parseFloat(A.price_per_std_unit):A.price_per_std_unit,L=T.standard_unit;return L==="g"&&P<1?`£${(P*1e3).toFixed(2)}/kg`:L==="ml"&&P<1?`£${(P*1e3).toFixed(2)}/ltr`:`£${P>=1?P.toFixed(2):P.toFixed(4)}/${L}`})():"-"}),s.jsx("td",{style:vn.tdSmall,children:A.latest_invoice_date||"-"})]},A.id)})})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic"},children:"No supplier sources mapped yet"})]})})},`${T.id}-expanded`)]})})})]}),s.jsx(A0,{open:p,onClose:()=>{g(!1),y(null)},editingIngredient:m})]})}const vn={page:{padding:"1.5rem",maxWidth:"1400px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},checkLabel:{display:"flex",alignItems:"center",gap:"0.35rem",fontSize:"0.9rem",color:"#555"},statsBar:{display:"flex",gap:"0.75rem",fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},thSmall:{padding:"0.4rem 0.5rem",textAlign:"left",borderBottom:"1px solid #e0e0e0",background:"#f5f5f5",fontSize:"0.75rem",fontWeight:600,color:"#666"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},tdSmall:{padding:"0.35rem 0.5rem",fontSize:"0.8rem"},expandedTd:{padding:"0.75rem 1rem",background:"#f9f9f9"},sourcesSection:{padding:"0.5rem"},smallBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem",marginRight:"0.25rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},loading:{padding:"2rem",textAlign:"center",color:"#888"}};function Kfe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(""),[o,a]=k.useState(""),[l,d]=k.useState(!1),[c,u]=k.useState(!1),[f,p]=k.useState("list"),[g,m]=k.useState(!1),[y,v]=k.useState(!1),[x,w]=k.useState(""),[S,_]=k.useState(""),[b,C]=k.useState(""),[T,F]=k.useState({}),[A,D]=k.useState(null),[P,L]=k.useState(""),[W,O]=k.useState(""),[U,M]=k.useState(""),[I,H]=k.useState("1"),[z,G]=k.useState("portions"),[te,re]=k.useState(""),[me,J]=k.useState("ml"),[ne,ye]=k.useState(""),[ke,Ye]=k.useState(""),{data:De}=Oe({queryKey:["recipe-sections"],queryFn:async()=>{const K=await fetch("/api/recipes/menu-sections?section_type=recipe",{headers:{Authorization:`Bearer ${n}`}});if(!K.ok)throw new Error("Failed to fetch sections");return K.json()},enabled:!!n}),{data:qe,isLoading:ue}=Oe({queryKey:["recipes",r,o,y],queryFn:async()=>{const K=new URLSearchParams;K.set("recipe_type","component"),r&&K.set("search",r),o&&K.set("menu_section_id",o),y&&K.set("archived","true");const de=await fetch(`/api/recipes?${K}`,{headers:{Authorization:`Bearer ${n}`}});if(!de.ok)throw new Error("Failed to fetch recipes");return de.json()},enabled:!!n}),Ze=Ue({mutationFn:async K=>{const de=await fetch("/api/recipes",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(K)});if(!de.ok)throw new Error("Failed to create recipe");return de.json()},onSuccess:K=>{t.invalidateQueries({queryKey:["recipes"]}),d(!1),e(`/recipes/${K.id}`)}}),ee=Ue({mutationFn:async K=>{const de=await fetch(`/api/recipes/${K}/duplicate`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!de.ok)throw new Error("Failed to duplicate");return de.json()},onSuccess:K=>{t.invalidateQueries({queryKey:["recipes"]}),e(`/recipes/${K.id}`)}}),Z=Ue({mutationFn:async K=>{if(!(await fetch(`/api/recipes/${K}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to archive")},onSuccess:()=>t.invalidateQueries({queryKey:["recipes"]})}),ge=Ue({mutationFn:async K=>{if(!(await fetch(`/api/recipes/${K}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_archived:!1})})).ok)throw new Error("Failed to unarchive")},onSuccess:()=>t.invalidateQueries({queryKey:["recipes"]})}),Te=Ue({mutationFn:async K=>{const de=await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:K,section_type:"recipe"})});if(!de.ok)throw new Error("Failed to create section");return de.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["recipe-sections"]}),Ye(""),u(!1)}}),Be=Ue({mutationFn:async({id:K,name:de})=>{const Y=await fetch(`/api/recipes/menu-sections/${K}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:de})});if(!Y.ok)throw new Error("Failed to update section");return Y.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["recipe-sections"]}),t.invalidateQueries({queryKey:["recipes"]}),D(null),L("")}}),he=Ue({mutationFn:async K=>{const de=await fetch(`/api/recipes/menu-sections/${K}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!de.ok)throw new Error("Failed to delete section");return de.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["recipe-sections"]}),t.invalidateQueries({queryKey:["recipes"]})}}),{data:He}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const K=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${n}`}});if(!K.ok)throw new Error("Failed to fetch flag categories");return K.json()},enabled:!!n&&g}),Ge=(()=>{let K=qe||[];if(x.trim()){const Q=x.toLowerCase();K=K.filter(X=>X.name.toLowerCase().includes(Q)||X.flag_summary.some(pe=>pe.name.toLowerCase().includes(Q)))}if(S){const Q=parseFloat(S);isNaN(Q)||(K=K.filter(X=>X.cost_per_portion!=null&&X.cost_per_portion>=Q))}if(b){const Q=parseFloat(b);isNaN(Q)||(K=K.filter(X=>X.cost_per_portion!=null&&X.cost_per_portion<=Q))}const de=Object.entries(T).filter(([,Q])=>Q==="include").map(([Q])=>Q),Y=Object.entries(T).filter(([,Q])=>Q==="exclude").map(([Q])=>Q);return de.length>0&&(K=K.filter(Q=>de.every(X=>Q.flag_summary.some(pe=>pe.name===X&&pe.active)))),Y.length>0&&(K=K.filter(Q=>!Y.some(X=>Q.flag_summary.some(pe=>pe.name===X&&pe.active)))),K})(),ae=()=>{Ze.mutate({name:W,recipe_type:"component",menu_section_id:U?parseInt(U):null,batch_portions:z==="portions"&&parseInt(I)||1,batch_output_type:z,batch_yield_qty:z==="bulk"&&parseFloat(te)||null,batch_yield_unit:z==="bulk"?me:null,description:ne||null})};return s.jsxs("div",{style:wt.page,children:[s.jsxs("div",{style:wt.header,children:[s.jsx("h2",{style:{margin:0},children:"Recipes"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>u(!0),style:wt.secondaryBtn,children:"+ Section"}),s.jsx("button",{onClick:()=>{d(!0),O(""),M(""),H("1"),G("portions"),re(""),J("ml"),ye("")},style:wt.primaryBtn,children:"+ New Recipe"})]})]}),s.jsx("div",{style:wt.statsBar,children:s.jsxs("span",{children:[Ge.length," ",y?"archived ":"","recipes"]})}),s.jsxs("div",{style:wt.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search recipes...",value:r,onChange:K=>i(K.target.value),style:wt.searchInput}),s.jsxs("select",{value:o,onChange:K=>a(K.target.value),style:wt.select,children:[s.jsx("option",{value:"",children:"All Sections"}),De==null?void 0:De.map(K=>s.jsxs("option",{value:K.id,children:[K.name," (",K.recipe_count,")"]},K.id))]}),s.jsxs("label",{style:wt.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:y,onChange:K=>v(K.target.checked)}),"Show Archived"]}),s.jsx("button",{onClick:()=>m(!g),style:{...wt.secondaryBtn,padding:"0.5rem 0.75rem",fontSize:"0.85rem"},children:g?"Hide Filters":"Show Filters"}),s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"2px"},children:[s.jsx("button",{onClick:()=>p("card"),style:{...wt.viewToggleBtn,...f==="card"?wt.viewToggleBtnActive:{},borderRadius:"4px 0 0 4px"},children:"Cards"}),s.jsx("button",{onClick:()=>p("list"),style:{...wt.viewToggleBtn,...f==="list"?wt.viewToggleBtnActive:{},borderRadius:"0 4px 4px 0"},children:"List"})]})]}),g&&s.jsx("div",{style:wt.advancedFilterPanel,children:s.jsxs("div",{style:{display:"flex",gap:"1rem",flexWrap:"wrap",alignItems:"flex-start"},children:[s.jsxs("div",{style:{minWidth:"200px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Contains ingredient"}),s.jsx("input",{type:"text",placeholder:"Search by ingredient...",value:x,onChange:K=>w(K.target.value),style:{...wt.searchInput,width:"100%"}})]}),s.jsxs("div",{style:{minWidth:"150px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Cost/portion range"}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",placeholder:"Min",value:S,onChange:K=>_(K.target.value),style:{...wt.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"}),s.jsx("span",{style:{color:"#888"},children:"-"}),s.jsx("input",{type:"number",placeholder:"Max",value:b,onChange:K=>C(K.target.value),style:{...wt.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"})]})]}),He&&He.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"250px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Food flag filters"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:He.flatMap(K=>K.flags||[]).map(K=>{const de=T[K.name]||"neutral",Y=de==="neutral"?"include":de==="include"?"exclude":"neutral";return s.jsxs("button",{onClick:()=>F(Q=>{const X={...Q};return Y==="neutral"?delete X[K.name]:X[K.name]=Y,X}),style:{padding:"2px 8px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:600,cursor:"pointer",border:"1px solid",borderColor:de==="include"?"#22c55e":de==="exclude"?"#ef4444":"#ddd",background:de==="include"?"#dcfce7":de==="exclude"?"#fef2f2":"white",color:de==="include"?"#166534":de==="exclude"?"#991b1b":"#666"},title:`${K.name}: ${de} (click to cycle)`,children:[de==="include"?"+ ":de==="exclude"?"- ":"",K.code||K.name]},K.id)})})]})]})}),ue?s.jsx("div",{style:wt.loading,children:"Loading recipes..."}):f==="card"?s.jsx("div",{style:wt.grid,children:Ge.map(K=>s.jsxs("div",{style:{...wt.card,...K.is_archived?{opacity:.6}:{}},onClick:()=>e(`/recipes/${K.id}`),children:[s.jsxs("div",{style:wt.cardHeader,children:[s.jsx("span",{style:{fontWeight:600,fontSize:"1rem",...K.is_archived?{textDecoration:"line-through"}:{}},children:K.name}),s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[K.is_archived&&s.jsx("span",{style:{background:"#999",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"ARCHIVED"}),s.jsx("span",{style:{background:"#8b5cf6",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"RECIPE"})]})]}),K.menu_section_name&&s.jsx("div",{style:wt.sectionTag,children:K.menu_section_name}),(K.batch_output_type==="bulk"||K.batch_portions>1)&&s.jsx("div",{style:{fontSize:"0.8rem",color:"#666",marginTop:"4px"},children:K.batch_output_type==="bulk"?`Yield: ${K.batch_yield_qty}${K.batch_yield_unit}`:`Batch: ${K.batch_portions} portions`}),s.jsxs("div",{style:wt.cardMeta,children:[K.cost_per_portion!=null?s.jsxs("span",{style:wt.costBadge,children:["£",K.cost_per_portion.toFixed(K.batch_output_type==="bulk"?4:2),"/",K.output_unit||"portion"]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"No costing"}),(K.prep_time_minutes||K.cook_time_minutes)&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:[K.prep_time_minutes?`${K.prep_time_minutes}m prep`:"",K.prep_time_minutes&&K.cook_time_minutes?" + ":"",K.cook_time_minutes?`${K.cook_time_minutes}m cook`:""]})]}),K.flag_summary.length>0&&s.jsx("div",{style:{marginTop:"6px"},children:s.jsx(T0,{flags:K.flag_summary})}),s.jsxs("div",{style:wt.cardActions,children:[s.jsx("button",{onClick:de=>{de.stopPropagation(),ee.mutate(K.id)},style:wt.actionBtn,children:"Duplicate"}),K.is_archived?s.jsx("button",{onClick:de=>{de.stopPropagation(),ge.mutate(K.id)},style:{...wt.actionBtn,color:"#22c55e"},children:"Restore"}):s.jsx("button",{onClick:de=>{de.stopPropagation(),Z.mutate(K.id)},style:{...wt.actionBtn,color:"#e94560"},children:"Archive"})]})]},K.id))}):s.jsxs("table",{style:wt.listTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:wt.listTh,children:"Name"}),s.jsx("th",{style:wt.listTh,children:"Type"}),s.jsx("th",{style:wt.listTh,children:"Section"}),s.jsx("th",{style:wt.listTh,children:"Output"}),s.jsx("th",{style:wt.listTh,children:"Cost/Unit"}),s.jsx("th",{style:wt.listTh,children:"Flags"}),s.jsx("th",{style:wt.listTh,children:"Actions"})]})}),s.jsx("tbody",{children:Ge.map(K=>s.jsxs("tr",{style:{...wt.listTr,cursor:"pointer",...K.is_archived?{opacity:.6}:{}},onClick:()=>e(`/recipes/${K.id}`),children:[s.jsxs("td",{style:wt.listTd,children:[s.jsx("span",{style:{fontWeight:500,...K.is_archived?{textDecoration:"line-through"}:{}},children:K.name}),K.is_archived&&s.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.7rem",color:"#999",fontStyle:"italic"},children:"archived"})]}),s.jsx("td",{style:wt.listTd,children:s.jsx("span",{style:{background:"#8b5cf6",color:"white",padding:"1px 6px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"RECIPE"})}),s.jsx("td",{style:wt.listTd,children:K.menu_section_name||"-"}),s.jsx("td",{style:wt.listTd,children:K.batch_output_type==="bulk"?`${K.batch_yield_qty}${K.batch_yield_unit}`:K.batch_portions}),s.jsx("td",{style:wt.listTd,children:K.cost_per_portion!=null?s.jsxs("span",{style:wt.costBadge,children:["£",K.cost_per_portion.toFixed(K.batch_output_type==="bulk"?4:2),"/",K.output_unit||"portion"]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"})}),s.jsx("td",{style:wt.listTd,children:K.flag_summary.length>0&&s.jsx(T0,{flags:K.flag_summary})}),s.jsxs("td",{style:wt.listTd,children:[s.jsx("button",{onClick:de=>{de.stopPropagation(),ee.mutate(K.id)},style:wt.actionBtn,children:"Duplicate"}),K.is_archived?s.jsx("button",{onClick:de=>{de.stopPropagation(),ge.mutate(K.id)},style:{...wt.actionBtn,color:"#22c55e",marginLeft:"4px"},children:"Restore"}):s.jsx("button",{onClick:de=>{de.stopPropagation(),Z.mutate(K.id)},style:{...wt.actionBtn,color:"#e94560",marginLeft:"4px"},children:"Archive"})]})]},K.id))})]}),l&&s.jsx("div",{style:wt.overlay,children:s.jsxs("div",{style:wt.modal,children:[s.jsxs("div",{style:wt.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"New Recipe"}),s.jsx("button",{onClick:()=>d(!1),style:wt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:wt.modalBody,children:[s.jsx("label",{style:wt.label,children:"Name *"}),s.jsx("input",{value:W,onChange:K=>O(K.target.value),style:wt.input,placeholder:"e.g. Hollandaise Sauce, Pastry Base"}),s.jsx("label",{style:wt.label,children:"Section"}),s.jsxs("select",{value:U,onChange:K=>M(K.target.value),style:wt.input,children:[s.jsx("option",{value:"",children:"None"}),De==null?void 0:De.map(K=>s.jsx("option",{value:K.id,children:K.name},K.id))]}),s.jsx("label",{style:wt.label,children:"Output Type"}),s.jsxs("select",{value:z,onChange:K=>G(K.target.value),style:wt.input,children:[s.jsx("option",{value:"portions",children:"Portioned"}),s.jsx("option",{value:"bulk",children:"Bulk (volume/weight)"})]}),z==="portions"?s.jsxs(s.Fragment,{children:[s.jsx("label",{style:wt.label,children:"Batch Portions"}),s.jsx("input",{type:"number",value:I,onChange:K=>H(K.target.value),style:wt.input,min:"1"})]}):s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("label",{style:wt.label,children:"Yield Quantity"}),s.jsx("input",{type:"number",value:te,onChange:K=>re(K.target.value),style:wt.input,step:"0.1",min:"0.1",placeholder:"e.g. 500"})]}),s.jsxs("div",{style:{width:"90px"},children:[s.jsx("label",{style:wt.label,children:"Unit"}),s.jsxs("select",{value:me,onChange:K=>J(K.target.value),style:wt.input,children:[s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"})]})]})]}),s.jsx("label",{style:wt.label,children:"Description"}),s.jsx("textarea",{value:ne,onChange:K=>ye(K.target.value),style:{...wt.input,minHeight:"60px"},placeholder:"Brief description..."})]}),s.jsxs("div",{style:wt.modalFooter,children:[s.jsx("button",{onClick:()=>d(!1),style:wt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:ae,disabled:!W||Ze.isPending,style:wt.primaryBtn,children:Ze.isPending?"Creating...":"Create Recipe"})]})]})}),c&&s.jsx("div",{style:wt.overlay,children:s.jsxs("div",{style:{...wt.modal,width:"450px"},children:[s.jsxs("div",{style:wt.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Manage Recipe Sections"}),s.jsx("button",{onClick:()=>{u(!1),D(null)},style:wt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:wt.modalBody,children:[De&&De.length>0&&s.jsx("div",{style:{marginBottom:"1rem"},children:De.map(K=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.4rem 0",borderBottom:"1px solid #f0f0f0"},children:A===K.id?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:P,onChange:de=>L(de.target.value),style:{...wt.input,flex:1},autoFocus:!0}),s.jsx("button",{onClick:()=>Be.mutate({id:K.id,name:P}),disabled:!P.trim(),style:{...wt.actionBtn,color:"#22c55e"},children:"Save"}),s.jsx("button",{onClick:()=>{D(null),L("")},style:wt.actionBtn,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:"0.9rem"},children:K.name}),s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:["(",K.recipe_count,")"]}),s.jsx("button",{onClick:()=>{D(K.id),L(K.name)},style:wt.actionBtn,children:"Edit"}),s.jsx("button",{onClick:()=>{confirm(`Delete section "${K.name}"? Recipes in this section will be unassigned.`)&&he.mutate(K.id)},style:{...wt.actionBtn,color:"#e94560"},children:"Delete"})]})},K.id))}),s.jsx("label",{style:wt.label,children:"Add New Section"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{value:ke,onChange:K=>Ye(K.target.value),style:{...wt.input,flex:1},placeholder:"e.g. Protein, Garnish, Pastry, Baked"}),s.jsx("button",{onClick:()=>Te.mutate(ke),disabled:!ke,style:wt.primaryBtn,children:"Add"})]})]}),s.jsx("div",{style:wt.modalFooter,children:s.jsx("button",{onClick:()=>{u(!1),D(null)},style:wt.cancelBtn,children:"Close"})})]})})]})}const wt={page:{padding:"1.5rem",maxWidth:"1400px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},statsBar:{display:"flex",gap:"0.75rem",fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},checkLabel:{display:"flex",alignItems:"center",gap:"0.35rem",fontSize:"0.85rem",color:"#555",cursor:"pointer",whiteSpace:"nowrap"},grid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:"1rem"},card:{background:"white",borderRadius:"8px",padding:"1rem",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",cursor:"pointer",transition:"box-shadow 0.2s",border:"1px solid #eee"},cardHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"0.5rem"},sectionTag:{fontSize:"0.75rem",color:"#888",marginTop:"2px"},cardMeta:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"8px"},costBadge:{background:"#f0fdf4",color:"#166534",padding:"2px 8px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},cardActions:{display:"flex",gap:"0.5rem",marginTop:"10px",borderTop:"1px solid #f0f0f0",paddingTop:"8px"},actionBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},secondaryBtn:{padding:"0.6rem 1.25rem",background:"white",color:"#333",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},viewToggleBtn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",background:"white",cursor:"pointer",fontSize:"0.8rem",color:"#666"},viewToggleBtnActive:{background:"#e94560",color:"white",borderColor:"#e94560"},advancedFilterPanel:{background:"#fafafa",border:"1px solid #eee",borderRadius:"8px",padding:"1rem",marginBottom:"1rem"},listTable:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},listTh:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},listTr:{borderBottom:"1px solid #f0f0f0"},listTd:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"}};function WK({recipeId:n,categoryId:e}){const{token:t}=gn(),r=pi(),[i,o]=k.useState(new Set),{data:a,isLoading:l}=Oe({queryKey:["recipe-flag-matrix",n],queryFn:async()=>{const S=await fetch(`/api/food-flags/recipes/${n}/flags/matrix`,{headers:{Authorization:`Bearer ${t}`}});if(!S.ok)throw new Error("Failed to fetch matrix");return S.json()},enabled:!!t&&!!n}),d=a?{flags:e?a.flags.filter(S=>S.category_id===e):a.flags,ingredients:a.ingredients}:void 0,c=Ue({mutationFn:async({ingredientId:S,flagId:_,hasFlag:b})=>{if(!(await fetch(`/api/food-flags/recipes/${n}/flags/matrix`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({updates:[{ingredient_id:S,food_flag_id:_,has_flag:b}]})})).ok)throw new Error("Failed to update flag")},onMutate:({ingredientId:S,flagId:_})=>{o(b=>new Set(b).add(`${S}-${_}`))},onSettled:(S,_,{ingredientId:b,flagId:C})=>{o(T=>{const F=new Set(T);return F.delete(`${b}-${C}`),F}),r.invalidateQueries({queryKey:["recipe-flag-matrix",n]}),r.invalidateQueries({queryKey:["recipe-flags",n]}),r.invalidateQueries({queryKey:["ingredients"]})}}),u=Ue({mutationFn:async({ingredientId:S,catId:_})=>{if(!(await fetch(`/api/food-flags/recipes/${n}/flags/matrix/none`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_id:S,category_id:_})})).ok)throw new Error("Failed to toggle none")},onSettled:()=>{r.invalidateQueries({queryKey:["recipe-flag-matrix",n]}),r.invalidateQueries({queryKey:["recipe-flags",n]}),r.invalidateQueries({queryKey:["ingredients"]})}});if(l)return s.jsx("div",{style:{padding:"1rem",color:"#888"},children:"Loading matrix..."});if(!d||!d.flags.length)return s.jsx("div",{style:{padding:"1rem",color:"#888"},children:"No flags configured for this category"});const f={};for(const S of d.flags)f[S.category_id]||(f[S.category_id]={name:S.category_name,propagation:S.propagation_type,required:S.required,flags:[]}),f[S.category_id].flags.push(S);let p="";const g=[];for(const S of d.ingredients)S.is_sub_recipe&&S.sub_recipe_name!==p?(p=S.sub_recipe_name||"",g.push({type:"header",label:`▸ ${p}`})):!S.is_sub_recipe&&p&&(p=""),g.push({type:"ingredient",label:S.is_sub_recipe?` ↳ ${S.ingredient_name}`:S.ingredient_name,ingredient:S});const m={};for(const S of d.flags)if(f[S.category_id].propagation==="contains"){const b=d.ingredients.some(C=>{var T;return(T=C.flags[S.id])==null?void 0:T.has_flag});m[S.id]={has:b,unassessed:!1}}else{const b=d.ingredients.every(T=>{var F;return(F=T.flags[S.id])==null?void 0:F.has_flag}),C=d.ingredients.some(T=>{var F;return(F=T.flags[S.id])==null?void 0:F.is_unassessed});m[S.id]={has:b&&!C,unassessed:C}}const y=(S,_)=>{var C;const b=((C=f[_])==null?void 0:C.flags)||[];return b.length>0&&b.every(T=>{var F;return(F=S.flags[T.id])==null?void 0:F.is_none})},v=(S,_,b)=>{c.mutate({ingredientId:S,flagId:_,hasFlag:!b})},x=(S,_,b,C,T)=>{const F=i.has(`${S}-${_}`),A=(b==null?void 0:b.has_flag)??!1,D=(b==null?void 0:b.is_unassessed)??!1,P=(b==null?void 0:b.is_none)??!1,L=(b==null?void 0:b.has_open_suggestion)??!1,W={...Oa.cell,cursor:"pointer",opacity:F?.5:1,transition:"background 0.15s",position:"relative"},O=L&&!A&&!D?s.jsx("span",{style:{position:"absolute",top:"2px",right:"2px",width:"6px",height:"6px",borderRadius:"50%",background:"#f59e0b"},title:"Unreviewed allergen suggestion"}):null,U=()=>{F||(D?v(S,_,!1):v(S,_,A))};return D?s.jsxs("td",{style:{...W,color:"#f59e0b"},title:"Unassessed \\u2014 click to assess",onClick:U,children:["❓",O]}):P?s.jsxs("td",{style:{...W,color:"#94a3b8",background:"#f8fafc"},title:`None apply — click to set ${T||"this flag"}`,onClick:U,children:["—",O]}):C==="contains"?s.jsxs("td",{style:{...W,color:A?"#dc3545":"#ccc",background:A?"#fef2f2":L?"#fffbeb":void 0},title:A?`Contains ${T||""} — click to remove`:L?`Unreviewed suggestion: ${T||""} — click to set`:`Click to mark as contains ${T||""}`,onClick:U,children:[A?"✓":"·",O]}):s.jsxs("td",{style:{...W,color:A?"#22c55e":"#dc3545",background:A?"#f0fdf4":void 0},title:A?`${T||"Suitable"} — click to remove`:`Click to mark as ${T||"suitable"}`,onClick:U,children:[A?"✓":"✗",O]})},w=Object.values(f).some(S=>S.required);return s.jsxs("div",{style:Oa.container,children:[s.jsx("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem"},children:s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:["Click cells to toggle flags",w?'. Use "N" column to mark "None apply".':"."]})}),s.jsx("div",{style:{overflowX:"auto",maxHeight:"70vh",overflowY:"auto"},children:s.jsxs("table",{style:Oa.table,children:[s.jsx("thead",{style:{position:"sticky",top:0,zIndex:2},children:s.jsxs("tr",{children:[s.jsx("th",{style:{...Oa.th,minWidth:"160px",position:"sticky",top:0,background:"white",zIndex:2},children:"Ingredient"}),Object.entries(f).map(([S,_])=>s.jsxs(s.Fragment,{children:[_.flags.map(b=>s.jsxs("th",{style:Oa.th,title:`${b.name} (${_.name})`,children:[Object.keys(f).length>1&&s.jsx("div",{style:{fontSize:"0.6rem",color:"#888"},children:_.name}),s.jsx("div",{children:b.code||b.name.substring(0,4)})]},b.id)),_.required&&s.jsx("th",{style:{...Oa.th,borderLeft:"2px solid #e0e0e0",fontSize:"0.6rem",minWidth:"28px"},title:`None apply for ${_.name}`,children:s.jsx("div",{children:"N"})},`none-${S}`)]}))]})}),s.jsxs("tbody",{children:[g.map((S,_)=>{if(S.type==="header"){const C=Object.values(f).filter(F=>F.required).length,T=d.flags.length+C+1;return s.jsx("tr",{children:s.jsx("td",{colSpan:T,style:Oa.subHeader,children:S.label})},`h-${_}`)}const b=S.ingredient;return s.jsxs("tr",{children:[s.jsx("td",{style:{...Oa.td,fontWeight:b.is_sub_recipe?400:500},children:S.label}),Object.entries(f).map(([C,T])=>s.jsxs(s.Fragment,{children:[T.flags.map(F=>x(b.ingredient_id,F.id,b.flags[F.id],T.propagation,F.name)),T.required&&s.jsx("td",{style:{...Oa.cell,borderLeft:"2px solid #e0e0e0",cursor:"pointer",color:y(b,Number(C))?"#3b82f6":"#ddd",background:y(b,Number(C))?"#eff6ff":void 0,fontWeight:y(b,Number(C))?600:400},title:y(b,Number(C))?"None apply — click to unset":`Click to mark "None apply" for ${T.name}`,onClick:()=>u.mutate({ingredientId:b.ingredient_id,catId:Number(C)}),children:"N"},`none-${C}-${b.ingredient_id}`)]}))]},b.ingredient_id+"-"+_)}),s.jsxs("tr",{style:{borderTop:"3px double #333"},children:[s.jsx("td",{style:{...Oa.td,fontWeight:700},children:"Recipe Total"}),Object.entries(f).map(([S,_])=>s.jsxs(s.Fragment,{children:[_.flags.map(b=>{const C=m[b.id];return C.unassessed?s.jsx("td",{style:{...Oa.cell,color:"#f59e0b"},children:"❓"},b.id):_.propagation==="contains"?s.jsx("td",{style:{...Oa.cell,color:C.has?"#dc3545":void 0,fontWeight:700},children:C.has?"✓":""},b.id):s.jsx("td",{style:{...Oa.cell,color:C.has?"#22c55e":"#dc3545",fontWeight:700},children:C.has?"✓":"✗"},b.id)}),_.required&&s.jsx("td",{style:{...Oa.cell,borderLeft:"2px solid #e0e0e0"}},`none-total-${S}`)]}))]})]})]})})]})}const Oa={container:{background:"white",padding:"1rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.8rem"},th:{padding:"0.4rem 0.35rem",textAlign:"center",borderBottom:"2px solid #ddd",fontSize:"0.7rem",fontWeight:600,minWidth:"40px",position:"sticky",top:0,background:"white",zIndex:1},td:{padding:"0.35rem 0.5rem",borderBottom:"1px solid #f0f0f0",fontSize:"0.8rem"},cell:{padding:"0.35rem",textAlign:"center",borderBottom:"1px solid #f0f0f0",fontSize:"0.9rem"},subHeader:{padding:"0.5rem",fontWeight:700,background:"#f8f9fa",fontSize:"0.8rem",color:"#555"}},Xfe={g:["g","kg"],kg:["g","kg"],ml:["ml","ltr"],ltr:["ml","ltr"],each:["each"],portion:["portion"]};function KN(n){return Xfe[n]||[n]}function Yfe(){var al;const{id:n}=G_(),e=parseInt(n||"0"),{token:t,user:r}=gn(),i=go(),o=pi(),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState("1"),[p,g]=k.useState("portions"),[m,y]=k.useState(""),[v,x]=k.useState("ml"),[w,S]=k.useState(""),[_,b]=k.useState(""),[C,T]=k.useState(""),[F,A]=k.useState(""),[D,P]=k.useState(!1),[L,W]=k.useState(!1),[O,U]=k.useState(""),[M,I]=k.useState([]),[H,z]=k.useState(null),[G,te]=k.useState(""),[re,me]=k.useState([]),[J,ne]=k.useState(""),[ye,ke]=k.useState(""),[Ye,De]=k.useState(!1),[qe,ue]=k.useState(null),[Ze,ee]=k.useState(null),[Z,ge]=k.useState(""),[Te,Be]=k.useState(""),[he,He]=k.useState("100"),[Ge,ae]=k.useState(""),[K,de]=k.useState(!1),[Y,Q]=k.useState(null),[X,pe]=k.useState(""),[we,Ne]=k.useState(""),[st,Ve]=k.useState(!1),[Re,Le]=k.useState(""),[rt,$e]=k.useState(""),[ce,Je]=k.useState(""),[jt,ct]=k.useState(null),[Se,ot]=k.useState(""),[ut,Ot]=k.useState(!1),[An,on]=k.useState(""),[Ke,Rt]=k.useState(null),[vt,Cr]=k.useState(!1),[Qt,Ci]=k.useState(null),[Lr,Gs]=k.useState(null),[Ai,Ks]=k.useState(null),[un,Fr]=k.useState(!1),[zi,aa]=k.useState(!1),[Oi,Vd]=k.useState(!1),[Gn,Dr]=k.useState(null),[xr,Ss]=k.useState(null),[rs,Xs]=k.useState(null),{data:Jt}=Oe({queryKey:["recipe",e],queryFn:async()=>{const ie=await fetch(`/api/recipes/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!ie.ok)throw new Error("Not found");return ie.json()},enabled:!!t&&!!e}),{data:Ys}=Oe({queryKey:["recipe-sections"],queryFn:async()=>(await fetch("/api/recipes/menu-sections?section_type=recipe",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:Ft}=Oe({queryKey:["recipe-cost",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:Ea}=Oe({queryKey:["recipe-cost-scaled",e,Se],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing?scale_to=${Se}`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&!!Se&&parseFloat(Se)>0}),{data:zn}=Oe({queryKey:["recipe-flags",e],queryFn:async()=>(await fetch(`/api/food-flags/recipes/${e}/flags`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:gi}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>(await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:je}=Oe({queryKey:["recipe-changelog",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/change-log`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&un}),{data:bt}=Oe({queryKey:["recipe-cost-trend",e],queryFn:async()=>{const ie=await fetch(`/api/recipes/${e}/cost-trend`,{headers:{Authorization:`Bearer ${t}`}});if(!ie.ok)throw new Error("Failed to fetch cost trend");return ie.json()},enabled:!!t&&!!e&&vt}),{data:yn}=Oe({queryKey:["ingredient-edit",qe],queryFn:async()=>{const ie=await fetch(`/api/ingredients/${qe}`,{headers:{Authorization:`Bearer ${t}`}});if(!ie.ok)throw new Error("Not found");const nt=await ie.json();return{id:nt.id,name:nt.name,category_id:nt.category_id,standard_unit:nt.standard_unit,yield_percent:Number(nt.yield_percent),manual_price:nt.manual_price!=null?Number(nt.manual_price):null,notes:nt.notes,is_prepackaged:nt.is_prepackaged||!1,is_free:nt.is_free||!1,product_ingredients:nt.product_ingredients,has_label_image:nt.has_label_image||!1}},enabled:!!t&&!!qe}),{data:tn}=Oe({queryKey:["recipes-list-for-sub"],queryFn:async()=>(await fetch("/api/recipes?recipe_type=component",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&K});k.useEffect(()=>{var ie,nt,$,ze;Jt&&(l(Jt.name),c(Jt.description||""),f(Jt.batch_portions.toString()),g(Jt.batch_output_type||"portions"),y(((ie=Jt.batch_yield_qty)==null?void 0:ie.toString())||""),x(Jt.batch_yield_unit||"ml"),S(((nt=Jt.prep_time_minutes)==null?void 0:nt.toString())||""),b((($=Jt.cook_time_minutes)==null?void 0:$.toString())||""),T(Jt.notes||""),A(((ze=Jt.menu_section_id)==null?void 0:ze.toString())||""),P(!1))},[Jt]),k.useEffect(()=>{if(!O||O.length<2||!t)return;const ie=setTimeout(async()=>{try{const nt=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(O)}`,{headers:{Authorization:`Bearer ${t}`}});if(nt.ok){const $=await nt.json();I(Array.isArray($)?$:$.suggestions||[])}else console.warn("Ingredient suggest failed:",nt.status,await nt.text().catch(()=>""))}catch(nt){console.warn("Ingredient suggest error:",nt)}},300);return()=>clearTimeout(ie)},[O,t]);const ci=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),P(!1)}}),hn=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/ingredients`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)})).ok)throw new Error("Failed to add")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]}),W(!1),U(""),z(null),te(""),me([]),ne(""),ke("")}}),Ti=Ue({mutationFn:async({riId:ie,quantity:nt,unit:$,yield_percent:ze,notes:Qe})=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${ie}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({quantity:nt,unit:$,yield_percent:ze,notes:Qe})})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),ee(null)}}),js=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to remove")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})}}),Ar=Ue({mutationFn:async ie=>{const nt=await fetch(`/api/recipes/${e}/sub-recipes`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)});if(!nt.ok){const $=await nt.json().catch(()=>({}));throw new Error($.detail||"Failed to add sub-recipe")}},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),de(!1)}}),fs=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/recipe-sub-recipes/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]})}}),Qs=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/steps`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ie)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Ve(!1),Le(""),$e(""),Je("")}}),Lo=Ue({mutationFn:async({stepId:ie,data:nt})=>{if(!(await fetch(`/api/recipes/recipe-steps/${ie}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(nt)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),ct(null),Ve(!1),Le(""),$e(""),Je("")}}),xn=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/recipe-steps/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>o.invalidateQueries({queryKey:["recipe",e]})}),Pa=Ue({mutationFn:async({file:ie,caption:nt,image_type:$})=>{const ze=new FormData;if(ze.append("file",ie),ze.append("caption",nt),ze.append("image_type",$),!(await fetch(`/api/recipes/${e}/images`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:ze})).ok)throw new Error("Failed to upload image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Ot(!1),on(""),Rt(null)}}),nn=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/images/${ie}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Zl=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/ingredients/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_ids:ie})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),qu=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/sub-recipes/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sub_recipe_ids:ie})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),$s=Ue({mutationFn:async ie=>{if(!(await fetch(`/api/recipes/${e}/steps/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({step_ids:ie})})).ok)throw new Error("Failed to reorder steps")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Gd=(ie,nt)=>{Dr(ie),Xs(nt)},mo=(ie,nt)=>{ie.preventDefault(),Ss(nt)},Bc=()=>{if(Gn===null||xr===null||!Jt||rs!=="ing"){Dr(null),Ss(null),Xs(null);return}const nt=[...[...Jt.ingredients].sort((ze,Qe)=>ze.sort_order-Qe.sort_order)],[$]=nt.splice(Gn,1);nt.splice(xr,0,$),Zl.mutate(nt.map(ze=>ze.id)),Dr(null),Ss(null),Xs(null)},Kd=()=>{if(Gn===null||xr===null||!Jt||rs!=="sub"){Dr(null),Ss(null),Xs(null);return}const ie=[...Jt.sub_recipes],[nt]=ie.splice(Gn,1);ie.splice(xr,0,nt),qu.mutate(ie.map($=>$.id)),Dr(null),Ss(null),Xs(null)},Zs=(ie,nt)=>{if(!Jt)return;const $=[...Jt.steps],ze=nt==="up"?ie-1:ie+1;if(ze<0||ze>=$.length)return;const Qe=[...$],pt=Qe[ie];Qe[ie]=Qe[ze],Qe[ze]=pt,$s.mutate(Qe.map(kt=>kt.id))},Ra=()=>{ci.mutate({name:a,description:d||null,batch_portions:p==="portions"&&parseInt(u)||1,batch_output_type:p,batch_yield_qty:p==="bulk"&&parseFloat(m)||null,batch_yield_unit:p==="bulk"?v:null,prep_time_minutes:w?parseInt(w):null,cook_time_minutes:_?parseInt(_):null,notes:C||null,menu_section_id:F?parseInt(F):null})},Xd=ie=>{window.open(`/api/recipes/${e}/print?format=${ie}&token=${t}`,"_blank")};if(!Jt)return s.jsx("div",{style:Fe.loading,children:"Loading recipe..."});const No=Ft==null?void 0:Ft.total_cost_recent,Js=Ft==null?void 0:Ft.cost_per_portion,Ba=(Jt==null?void 0:Jt.output_unit)||"portion",Ic=Ba==="portion"?"Portion Cost":`Cost per ${Ba}`;return s.jsxs("div",{style:Fe.page,children:[s.jsxs("div",{style:Fe.topBar,children:[s.jsx("button",{onClick:()=>i("/recipes"),style:Fe.backBtn,children:"← Back"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>Xd("kitchen"),style:Fe.secondaryBtn,children:"Print Kitchen Card"}),s.jsx("button",{onClick:()=>Xd("full"),style:Fe.secondaryBtn,children:"Print Full"}),D&&s.jsx("button",{onClick:Ra,disabled:ci.isPending,style:Fe.primaryBtn,children:ci.isPending?"Saving...":"Save Changes"})]})]}),s.jsxs("div",{style:Fe.metaSection,children:[s.jsxs("div",{style:Fe.metaRow,children:[s.jsx("input",{value:a,onChange:ie=>{l(ie.target.value),P(!0)},style:{...Fe.nameInput,flex:1}}),s.jsx("span",{style:{background:"#8b5cf6",color:"white",padding:"4px 12px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},children:"RECIPE"})]}),s.jsxs("div",{style:Fe.metaGrid,children:[s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Section"}),s.jsxs("select",{value:F,onChange:ie=>{A(ie.target.value),P(!0)},style:Fe.input,children:[s.jsx("option",{value:"",children:"None"}),Ys==null?void 0:Ys.map(ie=>s.jsx("option",{value:ie.id,children:ie.name},ie.id))]})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Output Type"}),s.jsxs("select",{value:p,onChange:ie=>{g(ie.target.value),P(!0)},style:Fe.input,children:[s.jsx("option",{value:"portions",children:"Portioned"}),s.jsx("option",{value:"bulk",children:"Bulk (volume/weight)"})]})]}),p==="portions"?s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Batch Portions"}),s.jsx("input",{type:"number",value:u,onChange:ie=>{f(ie.target.value),P(!0)},style:Fe.input,min:"1"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Yield Qty"}),s.jsx("input",{type:"number",value:m,onChange:ie=>{y(ie.target.value),P(!0)},style:Fe.input,step:"0.1",min:"0.1"})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Yield Unit"}),s.jsxs("select",{value:v,onChange:ie=>{x(ie.target.value),P(!0)},style:Fe.input,children:[s.jsx("option",{value:"ml",children:"ml"}),s.jsx("option",{value:"ltr",children:"ltr"}),s.jsx("option",{value:"g",children:"g"}),s.jsx("option",{value:"kg",children:"kg"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Prep (min)"}),s.jsx("input",{type:"number",value:w,onChange:ie=>{S(ie.target.value),P(!0)},style:Fe.input})]}),s.jsxs("div",{children:[s.jsx("label",{style:Fe.label,children:"Cook (min)"}),s.jsx("input",{type:"number",value:_,onChange:ie=>{b(ie.target.value),P(!0)},style:Fe.input})]})]}),s.jsx("label",{style:Fe.label,children:"Description"}),s.jsx("textarea",{value:d,onChange:ie=>{c(ie.target.value),P(!0)},style:{...Fe.input,minHeight:"50px"}})]}),zn&&zn.unassessed_ingredients.length>0&&s.jsxs("div",{style:Fe.flagWarning,children:[s.jsxs("strong",{children:[zn.unassessed_ingredients.length," ingredient",zn.unassessed_ingredients.length>1?"s are":" is"," missing allergen details"]})," — ",zn.unassessed_ingredients.map(ie=>ie.name).join(", ")]}),zn&&zn.open_suggestion_ingredients&&zn.open_suggestion_ingredients.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsxs("strong",{children:[zn.open_suggestion_ingredients.length," ingredient",zn.open_suggestion_ingredients.length>1?"s have":" has"," unreviewed allergen suggestions"]})," — ",zn.open_suggestion_ingredients.map((ie,nt)=>s.jsxs("span",{children:[nt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline",fontWeight:600},onClick:()=>ue(ie.ingredient_id),children:ie.ingredient_name})," ","(",ie.suggestion_count,")"]},ie.ingredient_id))]}),zn&&zn.recipe_text_suggestions&&zn.recipe_text_suggestions.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsx("strong",{children:"Recipe text keyword matches"}),s.jsx("div",{style:{marginTop:"0.4rem"},children:zn.recipe_text_suggestions.map(ie=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.3rem"},children:[s.jsxs("span",{children:[s.jsx("strong",{children:ie.flag_name})," — ",ie.matched_keywords.join(", ")]}),s.jsx("button",{style:{marginLeft:"auto",background:"none",border:"1px solid #b4530955",borderRadius:"4px",color:"#b45309",cursor:"pointer",padding:"0.15rem 0.5rem",fontSize:"0.8rem",whiteSpace:"nowrap"},onClick:async()=>{try{(await fetch(`/api/food-flags/recipes/${e}/text-dismissals`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_id:ie.flag_id,dismissed_by_name:(r==null?void 0:r.name)||(r==null?void 0:r.email)||"Unknown",matched_keyword:ie.matched_keywords.join(", ")})})).ok&&o.invalidateQueries({queryKey:["recipe-flags",e]})}catch{}},children:"Dismiss"})]},ie.flag_id))})]}),Jt&&(()=>{const ie=Jt.ingredients.filter(Qe=>Qe.is_manual_price),nt=Jt.ingredients.filter(Qe=>Qe.has_no_price),$=Jt.sub_recipes.filter(Qe=>Qe.has_manual_price_ingredients),ze=Jt.sub_recipes.filter(Qe=>Qe.has_no_price_ingredients);return ie.length===0&&nt.length===0&&$.length===0&&ze.length===0?null:s.jsxs("div",{style:{background:"#fef3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #ffc10755"},children:[nt.length>0&&s.jsxs("div",{children:[s.jsxs("strong",{children:[nt.length," ingredient",nt.length>1?"s have":" has"," no price"]})," — ",nt.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ue(Qe.ingredient_id),children:Qe.ingredient_name})]},Qe.ingredient_id))]}),ie.length>0&&s.jsxs("div",{style:{marginTop:nt.length>0?"0.3rem":0},children:[s.jsxs("strong",{children:[ie.length," ingredient",ie.length>1?"s use":" uses"," manual price"]})," — ",ie.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ue(Qe.ingredient_id),children:Qe.ingredient_name})]},Qe.ingredient_id))]}),ze.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[ze.length," sub-recipe",ze.length>1?"s contain":" contains"," unpriced ingredients"]})," — ",ze.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${Qe.child_recipe_id}`),children:Qe.child_recipe_name})]},Qe.child_recipe_id))]}),$.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[$.length," sub-recipe",$.length>1?"s contain":" contains"," manual-priced ingredients"]})," — ",$.map((Qe,pt)=>s.jsxs("span",{children:[pt>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${Qe.child_recipe_id}`),children:Qe.child_recipe_name})]},Qe.child_recipe_id))]})]})})(),zn&&s.jsxs("div",{style:{margin:"0.75rem 0"},children:[zn.flags.length>0&&s.jsx(T0,{flags:zn.flags,size:"medium"}),gi&&gi.length>0&&s.jsx("div",{style:{display:"flex",gap:"0.35rem",marginTop:"0.5rem",flexWrap:"wrap"},children:gi.map(ie=>s.jsx("button",{onClick:()=>Ks(Ai===ie.id?null:ie.id),style:{padding:"3px 10px",fontSize:"0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:Ai===ie.id?"#e94560":"#f5f5f5",color:Ai===ie.id?"white":"#555",cursor:"pointer"},children:ie.name},ie.id))})]}),Ai!=null&&s.jsx(WK,{recipeId:e,categoryId:Ai||void 0}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Ingredients"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Jt.ingredients.length>1&&s.jsx("button",{onClick:()=>aa(!zi),style:{...Fe.addBtn,background:zi?"#3b82f6":void 0,color:zi?"#fff":void 0},children:zi?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>W(!0),style:Fe.addBtn,children:"+ Add"})]})]}),s.jsxs("table",{style:Fe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[zi&&s.jsx("th",{style:{...Fe.th,width:"30px"}}),s.jsx("th",{style:Fe.th,children:"Ingredient"}),s.jsx("th",{style:Fe.th,children:"Quantity"}),s.jsx("th",{style:Fe.th,children:"Yield %"}),s.jsx("th",{style:Fe.th,children:"Cost"}),s.jsx("th",{style:Fe.th,children:"Notes"}),s.jsx("th",{style:Fe.th})]})}),s.jsx("tbody",{children:[...Jt.ingredients].sort((ie,nt)=>ie.sort_order-nt.sort_order).map((ie,nt)=>s.jsxs("tr",{style:{...Fe.tr,opacity:rs==="ing"&&Gn===nt?.4:1,background:rs==="ing"&&xr===nt?"#e0f2fe":void 0},draggable:zi,onDragStart:()=>Gd(nt,"ing"),onDragOver:$=>mo($,nt),onDrop:Bc,onDragEnd:()=>{Dr(null),Ss(null),Xs(null)},children:[zi&&s.jsx("td",{style:{...Fe.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6",textDecoration:"none"},onClick:()=>ue(ie.ingredient_id),title:"Edit ingredient",children:ie.ingredient_name})}),Ze===ie.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:Fe.td,children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"2px"},children:[s.jsx("input",{type:"number",value:Z,onChange:$=>ge($.target.value),style:{...Fe.input,width:"80px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.1",autoFocus:!0}),ie.compatible_units&&ie.compatible_units.length>1?s.jsx("select",{value:Te,onChange:$=>Be($.target.value),style:{...Fe.input,width:"55px",padding:"0.25rem 0.2rem",fontSize:"0.75rem"},children:ie.compatible_units.map($=>s.jsx("option",{value:$,children:$},$))}):s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ie.unit})]})}),s.jsx("td",{style:Fe.td,children:s.jsx("input",{type:"number",value:he,onChange:$=>He($.target.value),style:{...Fe.input,width:"60px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.5",min:"1",max:"100"})}),s.jsx("td",{style:Fe.td,children:ie.cost!=null?`£${ie.cost.toFixed(2)}`:"-"}),s.jsx("td",{style:Fe.td,children:s.jsx("input",{value:Ge,onChange:$=>ae($.target.value),style:{...Fe.input,width:"120px",padding:"0.25rem 0.4rem",fontSize:"0.8rem"},placeholder:"notes..."})}),s.jsx("td",{style:Fe.td,children:s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[s.jsx("button",{onClick:()=>Ti.mutate({riId:ie.id,quantity:parseFloat(Z),unit:Te,yield_percent:parseFloat(he),notes:Ge||void 0}),disabled:!Z||Ti.isPending,style:{...Fe.addBtn,fontSize:"0.7rem",padding:"2px 6px",color:"#16a34a"},children:"Save"}),s.jsx("button",{onClick:()=>ee(null),style:{...Fe.removeBtn,color:"#888"},children:"Cancel"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("td",{style:{...Fe.td,cursor:"pointer"},onClick:()=>{ee(ie.id),ge(ie.quantity.toString()),Be(ie.unit),He(ie.yield_percent.toString()),ae(ie.notes||"")},children:[ie.quantity,ie.unit]}),s.jsx("td",{style:{...Fe.td,cursor:"pointer"},onClick:()=>{ee(ie.id),ge(ie.quantity.toString()),Be(ie.unit),He(ie.yield_percent.toString()),ae(ie.notes||"")},children:ie.yield_percent<100?s.jsxs("span",{style:{color:"#e94560"},children:[ie.yield_percent,"%"]}):"100%"}),s.jsx("td",{style:Fe.td,children:ie.cost!=null?s.jsxs("span",{style:ie.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:ie.is_manual_price?"Manual price":void 0,children:["£",ie.cost.toFixed(2)]}):"-"}),s.jsx("td",{style:{...Fe.td,cursor:"pointer"},onClick:()=>{ee(ie.id),ge(ie.quantity.toString()),Be(ie.unit),He(ie.yield_percent.toString()),ae(ie.notes||"")},children:s.jsx("span",{style:{color:"#888",fontSize:"0.8rem"},children:ie.notes||"-"})}),s.jsx("td",{style:Fe.td,children:s.jsx("button",{onClick:()=>js.mutate(ie.id),style:Fe.removeBtn,children:"✕"})})]})]},ie.id))})]})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Sub-Recipes"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Jt.sub_recipes.length>1&&s.jsx("button",{onClick:()=>Vd(!Oi),style:{...Fe.addBtn,background:Oi?"#3b82f6":void 0,color:Oi?"#fff":void 0},children:Oi?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>de(!0),style:Fe.addBtn,children:"+ Add"})]})]}),Jt.sub_recipes.length>0?s.jsxs("table",{style:Fe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[Oi&&s.jsx("th",{style:{...Fe.th,width:"30px"}}),s.jsx("th",{style:Fe.th,children:"Recipe"}),s.jsx("th",{style:Fe.th,children:"Batch Output"}),s.jsx("th",{style:Fe.th,children:"Amount Used"}),s.jsx("th",{style:Fe.th,children:"Cost"}),s.jsx("th",{style:Fe.th})]})}),s.jsx("tbody",{children:Jt.sub_recipes.map((ie,nt)=>s.jsxs("tr",{style:{...Fe.tr,opacity:rs==="sub"&&Gn===nt?.4:1,background:rs==="sub"&&xr===nt?"#e0f2fe":void 0},draggable:Oi,onDragStart:()=>Gd(nt,"sub"),onDragOver:$=>mo($,nt),onDrop:Kd,onDragEnd:()=>{Dr(null),Ss(null),Xs(null)},children:[Oi&&s.jsx("td",{style:{...Fe.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${ie.child_recipe_id}`),children:ie.child_recipe_name})}),s.jsx("td",{style:Fe.td,children:ie.batch_output_type==="bulk"?`${ie.output_qty}${ie.output_unit}`:`${ie.batch_portions} portions`}),s.jsxs("td",{style:Fe.td,children:[ie.portions_needed,ie.batch_output_type==="bulk"?ie.portions_needed_unit:" portions",ie.batch_output_type==="bulk"&&ie.portions_needed_unit!==ie.output_unit&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#888",marginLeft:"4px"},children:["(",ie.output_unit,")"]})]}),s.jsx("td",{style:Fe.td,children:ie.cost_contribution!=null?s.jsxs("span",{style:ie.has_manual_price_ingredients||ie.has_no_price_ingredients?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:ie.has_manual_price_ingredients?"Includes manual-priced ingredients":ie.has_no_price_ingredients?"Includes unpriced ingredients":void 0,children:["£",ie.cost_contribution.toFixed(2)]}):"-"}),s.jsx("td",{style:Fe.td,children:s.jsx("button",{onClick:()=>fs.mutate(ie.id),style:Fe.removeBtn,children:"✕"})})]},ie.id))})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No sub-recipes added"})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Method"}),s.jsx("button",{onClick:()=>{ct(null),Le(""),$e(""),Je(""),Ve(!0)},style:Fe.addBtn,children:"+ Add Step"})]}),Jt.steps.length>0?s.jsx("div",{style:{margin:0},children:Jt.steps.map((ie,nt)=>s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px",padding:"8px 0",borderBottom:"1px solid #f0f0f0"},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",flexShrink:0,marginTop:"2px"},children:[s.jsx("button",{onClick:()=>Zs(nt,"up"),disabled:nt===0||$s.isPending,style:{...Fe.reorderBtn,opacity:nt===0?.3:1},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>Zs(nt,"down"),disabled:nt===Jt.steps.length-1||$s.isPending,style:{...Fe.reorderBtn,opacity:nt===Jt.steps.length-1?.3:1},title:"Move down",children:"▼"})]}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem",color:"#e94560",minWidth:"24px",marginTop:"1px"},children:nt+1}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:"6px"},children:[ie.title&&s.jsx("span",{style:{fontWeight:600,fontSize:"0.95rem"},children:ie.title}),ie.duration_minutes&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#888"},children:["(",ie.duration_minutes," min)"]})]}),s.jsx("div",{style:{fontSize:"0.85rem",color:"#555",marginTop:ie.title?"2px":0,whiteSpace:"pre-wrap"},children:ie.instruction})]}),s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{onClick:()=>{ct(ie.id),Le(ie.title||""),$e(ie.instruction),Je(ie.duration_minutes?String(ie.duration_minutes):""),Ve(!0)},style:{...Fe.reorderBtn,fontSize:"0.75rem"},title:"Edit step",children:"✎"}),s.jsx("button",{onClick:()=>xn.mutate(ie.id),style:{...Fe.removeBtn,flexShrink:0},children:"✕"})]})]},ie.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No steps added yet"})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Images"}),s.jsx("button",{onClick:()=>Ot(!ut),style:Fe.addBtn,children:ut?"Cancel":"+ Upload"})]}),ut&&s.jsxs("div",{style:{marginBottom:"1rem",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsx("label",{style:Fe.label,children:"Image File"}),s.jsx("input",{type:"file",accept:"image/*",onChange:ie=>{var nt;return Rt(((nt=ie.target.files)==null?void 0:nt[0])||null)},style:{...Fe.input,padding:"0.35rem"}}),s.jsx("label",{style:Fe.label,children:"Caption (optional)"}),s.jsx("input",{value:An,onChange:ie=>on(ie.target.value),style:Fe.input,placeholder:"Describe this image..."}),s.jsx("div",{style:{marginTop:"0.75rem",display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{onClick:()=>{Ke&&Pa.mutate({file:Ke,caption:An,image_type:"general"})},disabled:!Ke||Pa.isPending,style:Fe.primaryBtn,children:Pa.isPending?"Uploading...":"Upload Image"})}),Pa.error&&s.jsx("div",{style:Fe.errorMsg,children:Pa.error.message})]}),Jt.images.length>0?s.jsx("div",{style:Fe.imageGrid,children:Jt.images.map(ie=>s.jsxs("div",{style:Fe.imageCard,children:[s.jsx("img",{src:`/api/recipes/${e}/images/${ie.id}?token=${t}`,alt:ie.caption||"Recipe image",style:{...Fe.imageThumb,cursor:"pointer"},onClick:()=>Gs(`/api/recipes/${e}/images/${ie.id}?token=${t}`)}),s.jsxs("div",{style:{padding:"0.4rem"},children:[ie.caption&&s.jsx("div",{style:{fontSize:"0.8rem",color:"#333",marginTop:"2px"},children:ie.caption}),s.jsx("button",{onClick:()=>{confirm("Delete this image?")&&nn.mutate(ie.id)},style:{...Fe.removeBtn,marginTop:"4px",fontSize:"0.7rem"},children:"Delete"})]})]},ie.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No images uploaded"})]}),s.jsxs("div",{style:Fe.costPanel,children:[s.jsx("div",{style:Fe.costHeader,children:s.jsx("h3",{style:{margin:0},children:"Cost Summary"})}),s.jsxs("div",{style:Fe.costGrid,children:[s.jsxs("div",{style:Fe.costBox,children:[s.jsx("div",{style:Fe.costLabel,children:"Recipe Total"}),s.jsx("div",{style:Fe.costValue,children:No!=null?`£${No.toFixed(2)}`:"-"})]}),s.jsxs("div",{style:Fe.costBox,children:[s.jsx("div",{style:Fe.costLabel,children:Ic}),s.jsx("div",{style:Fe.costValue,children:Js!=null?`£${Js.toFixed(4)}`:"-"})]}),(Ft==null?void 0:Ft.total_cost_min)!=null&&s.jsxs("div",{style:Fe.costBox,children:[s.jsx("div",{style:Fe.costLabel,children:"Min / Max"}),s.jsxs("div",{style:{fontSize:"0.85rem"},children:["£",Ft.total_cost_min.toFixed(2)," – £",(al=Ft.total_cost_max)==null?void 0:al.toFixed(2)]})]})]}),s.jsx("div",{style:{marginTop:"0.5rem"},children:s.jsxs("button",{onClick:()=>Cr(!vt),style:Fe.linkBtn,children:[vt?"Hide":"Show"," cost trend"]})}),vt&&(bt==null?void 0:bt.snapshots)&&bt.snapshots.length>1&&(()=>{const ie=bt.snapshots,nt=ie.map(It=>It.cost_per_portion),$=Math.min(...nt),ze=Math.max(...nt),Qe=ze-$||1,pt=500,kt=120,Ht=40,Gt=20,Er=pt-Ht*2,ar=kt-Gt*2,Kn=ie.map((It,Tn)=>{const Dt=Ht+Tn/(ie.length-1)*Er,Ln=Gt+ar-(It.cost_per_portion-$)/Qe*ar;return{x:Dt,y:Ln,...It}}),is=Kn.map(It=>`${It.x},${It.y}`).join(" "),On=[$,$+Qe/2,ze],sn=[0,Math.floor(ie.length/2),ie.length-1],ps=ie.filter((It,Tn)=>Tn>0&&It.cost_per_portion!==ie[Tn-1].cost_per_portion);return s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"1rem",alignItems:"flex-start"},children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("svg",{width:pt,height:kt,style:{background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[On.map((It,Tn)=>{const Dt=Gt+ar-(It-$)/Qe*ar;return s.jsxs("g",{children:[s.jsx("line",{x1:Ht,y1:Dt,x2:pt-Ht,y2:Dt,stroke:"#f0f0f0",strokeWidth:"1"}),s.jsxs("text",{x:Ht-4,y:Dt+3,textAnchor:"end",fontSize:"9",fill:"#888",children:["£",It.toFixed(2)]})]},Tn)}),sn.filter((It,Tn,Dt)=>Dt.indexOf(It)===Tn).map(It=>{const Tn=Kn[It],Dt=new Date(Tn.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"});return s.jsx("text",{x:Tn.x,y:kt-2,textAnchor:"middle",fontSize:"9",fill:"#888",children:Dt},It)}),s.jsx("polyline",{points:is,fill:"none",stroke:"#e94560",strokeWidth:"2"}),Kn.map((It,Tn)=>s.jsx("circle",{cx:It.x,cy:It.y,r:4,fill:"#e94560",stroke:"white",strokeWidth:"2",style:{cursor:"pointer"},onMouseEnter:Dt=>{var Fi;const Ln=(Fi=Dt.target.closest("svg"))==null?void 0:Fi.getBoundingClientRect();Ci({x:Ln?It.x+Ln.left-((Ln==null?void 0:Ln.left)||0):It.x,y:It.y-10,date:new Date(It.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),cost:`£${It.cost_per_portion.toFixed(4)}`,trigger:It.trigger})},onMouseLeave:()=>Ci(null)},Tn))]}),Qt&&s.jsxs("div",{style:{position:"absolute",left:Qt.x,top:Qt.y-50,transform:"translateX(-50%)",background:"#333",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"0.75rem",whiteSpace:"nowrap",pointerEvents:"none",zIndex:20},children:[s.jsx("div",{children:Qt.date}),s.jsx("div",{children:Qt.cost}),s.jsx("div",{style:{color:"#ccc",fontSize:"0.7rem"},children:Qt.trigger})]})]}),ps.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"220px",maxHeight:"300px",overflow:"auto",fontSize:"0.75rem",background:"#fafafa",borderRadius:"6px",padding:"6px 8px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{fontWeight:600,fontSize:"0.7rem",color:"#888",marginBottom:"4px"},children:["Change Log (",ps.length," snapshots)"]}),ps.slice().reverse().map((It,Tn)=>{const Dt=ie[ie.indexOf(It)-1],Ln=It.cost_per_portion-Dt.cost_per_portion,Fi=Ln>0?"#dc2626":"#16a34a";return s.jsxs("div",{style:{padding:"3px 0",borderBottom:"1px solid #eee"},children:[s.jsxs("div",{style:{color:"#888"},children:[new Date(It.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),s.jsxs("span",{style:{color:Fi,fontWeight:600,marginLeft:"4px"},children:[Ln>0?"+":"","£",Ln.toFixed(4)]})]}),It.changes.length>0&&s.jsx("div",{style:{color:"#666",marginTop:"1px"},children:It.changes.map((Zr,ll)=>s.jsx("div",{style:{fontSize:"0.7rem",lineHeight:1.3},children:Zr},ll))})]},Tn)})]})]})})(),vt&&(bt==null?void 0:bt.snapshots)&&bt.snapshots.length<=1&&s.jsx("div",{style:{marginTop:"0.5rem",color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"Not enough data points to display a trend chart"})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("div",{style:Fe.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Scale Recipe"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("input",{type:"number",value:Se,onChange:ie=>ot(ie.target.value),style:{...Fe.input,width:"80px"},placeholder:Jt.output_qty.toString(),min:"0.1",step:Jt.batch_output_type==="bulk"?"0.1":"1"}),s.jsxs("span",{style:{fontSize:"0.8rem",color:"#888"},children:[Ba,Ba==="portion"?"s":""]})]})]}),(()=>{var Qe;const ie=Ea||Ft;if(!(ie!=null&&ie.ingredients))return null;const nt=ie.ingredients.reduce((pt,kt)=>pt+(kt.cost_recent??0),0)+(((Qe=ie.sub_recipes)==null?void 0:Qe.reduce((pt,kt)=>pt+(kt.cost_contribution??0),0))??0),$=ie.ingredients.reduce((pt,kt)=>pt+(kt.cost_min??0),0),ze=ie.ingredients.reduce((pt,kt)=>pt+(kt.cost_max??0),0);return s.jsxs("table",{style:Fe.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Fe.th,children:"Ingredient"}),s.jsx("th",{style:Fe.th,children:"Qty"}),s.jsx("th",{style:Fe.th,children:"Recent"}),s.jsx("th",{style:Fe.th,children:"Min"}),s.jsx("th",{style:Fe.th,children:"Max"})]})}),s.jsxs("tbody",{children:[ie.ingredients.map(pt=>{const kt=pt.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;return s.jsxs("tr",{children:[s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ue(pt.ingredient_id),title:"Edit ingredient",children:pt.ingredient_name})}),s.jsxs("td",{style:Fe.td,children:[pt.quantity,pt.unit]}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:kt,title:pt.is_manual_price?"Manual price":void 0,children:pt.cost_recent!=null?`£${pt.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:kt,title:pt.is_manual_price?"Manual price":void 0,children:pt.cost_min!=null?`£${pt.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:Fe.td,children:s.jsx("span",{style:kt,title:pt.is_manual_price?"Manual price":void 0,children:pt.cost_max!=null?`£${pt.cost_max.toFixed(2)}`:"-"})})]},pt.ingredient_id)}),(()=>{const pt=(kt,Ht)=>{var Er,ar;const Gt=[];for(const Kn of kt){const is=Ht*1.5,On=Kn.child_ingredients&&Kn.child_ingredients.length>0||Kn.child_sub_recipes&&Kn.child_sub_recipes.length>0,sn=((Er=Kn.child_ingredients)==null?void 0:Er.some(It=>It.is_manual_price))||!1,ps=sn?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;if(Gt.push(s.jsx("tr",{children:s.jsxs("td",{colSpan:5,style:{...Fe.td,background:Ht===0?"#f0f0f0":"#f5f5f5",fontWeight:600,fontSize:"0.8rem",color:"#555",paddingLeft:`${.5+is}rem`},children:[Ht>0&&"→ ",s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${Kn.child_recipe_id}`),children:Kn.child_recipe_name})," (",Kn.portions_needed,Kn.output_unit==="portion"?" portions":Kn.output_unit,") — ",s.jsxs("span",{style:ps,title:sn?"Includes manual-priced ingredients":void 0,children:["£",((ar=Kn.cost_contribution)==null?void 0:ar.toFixed(2))??"-"]})]})},`sub-header-${Ht}-${Kn.child_recipe_id}`)),On){for(const It of Kn.child_ingredients||[]){const Tn=It.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;Gt.push(s.jsxs("tr",{style:{background:"#fafafa"},children:[s.jsx("td",{style:{...Fe.td,paddingLeft:`${1.5+is}rem`,color:"#666"},children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ue(It.ingredient_id),title:"Edit ingredient",children:It.ingredient_name})}),s.jsxs("td",{style:{...Fe.td,color:"#666"},children:[It.quantity,It.unit]}),s.jsx("td",{style:{...Fe.td,color:"#666"},children:s.jsx("span",{style:Tn,title:It.is_manual_price?"Manual price":void 0,children:It.cost_recent!=null?`£${It.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Fe.td,color:"#666"},children:s.jsx("span",{style:Tn,title:It.is_manual_price?"Manual price":void 0,children:It.cost_min!=null?`£${It.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Fe.td,color:"#666"},children:s.jsx("span",{style:Tn,title:It.is_manual_price?"Manual price":void 0,children:It.cost_max!=null?`£${It.cost_max.toFixed(2)}`:"-"})})]},`sub-${Ht}-${Kn.child_recipe_id}-ing-${It.ingredient_id}`))}Kn.child_sub_recipes&&Kn.child_sub_recipes.length>0&&Gt.push(...pt(Kn.child_sub_recipes,Ht+1))}}return Gt};return pt(ie.sub_recipes||[],0)})(),s.jsxs("tr",{style:{borderTop:"2px solid #333"},children:[s.jsx("td",{style:{...Fe.td,fontWeight:700},children:"Total"}),s.jsx("td",{style:Fe.td}),s.jsx("td",{style:{...Fe.td,fontWeight:700},children:nt>0?`£${nt.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Fe.td,fontWeight:700},children:$>0?`£${$.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Fe.td,fontWeight:700},children:ze>0?`£${ze.toFixed(2)}`:"-"})]})]})]})})()]}),s.jsxs("div",{style:Fe.section,children:[s.jsx("label",{style:Fe.label,children:"Notes"}),s.jsx("textarea",{value:C,onChange:ie=>{T(ie.target.value),P(!0)},style:{...Fe.input,minHeight:"60px"}})]}),s.jsxs("div",{style:Fe.section,children:[s.jsxs("button",{onClick:()=>Fr(!un),style:Fe.linkBtn,children:[un?"Hide":"Show"," change history"]}),un&&je&&s.jsx("div",{style:{marginTop:"0.5rem"},children:je.map(ie=>s.jsxs("div",{style:Fe.logEntry,children:[s.jsx("span",{style:{color:"#888",fontSize:"0.75rem"},children:ie.created_at}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#555"},children:ie.username}),s.jsx("span",{style:{fontSize:"0.85rem"},children:ie.change_summary})]},ie.id))})]}),L&&s.jsx("div",{style:Fe.overlay,children:s.jsxs("div",{style:Fe.modal,children:[s.jsxs("div",{style:Fe.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Ingredient"}),s.jsx("button",{onClick:()=>W(!1),style:Fe.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Fe.modalBody,children:[s.jsx("label",{style:Fe.label,children:"Search Ingredient"}),s.jsx("input",{value:O,onChange:ie=>{U(ie.target.value),z(null)},style:Fe.input,placeholder:"Type to search..."}),O.length>=2&&!H&&s.jsxs("div",{style:Fe.suggestions,children:[M.map(ie=>s.jsxs("div",{style:Fe.suggestionItem,onClick:()=>{const nt=KN(ie.standard_unit);z(ie.id),te(ie.standard_unit),me(nt),U(ie.name)},children:[ie.name," ",s.jsxs("span",{style:{color:"#888",fontSize:"0.75rem"},children:["(",Math.round(ie.similarity*100),"%)"]})]},ie.id)),s.jsxs("div",{style:{...Fe.suggestionItem,color:"#16a34a",fontWeight:600,borderBottom:"none"},onClick:()=>De(!0),children:['+ Create "',O,'"']})]}),H&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Fe.label,children:"Quantity"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:J,onChange:ie=>ne(ie.target.value),style:{...Fe.input,flex:1},step:"0.1"}),re.length>1?s.jsx("select",{value:G,onChange:ie=>te(ie.target.value),style:{...Fe.input,width:"70px"},children:re.map(ie=>s.jsx("option",{value:ie,children:ie},ie))}):s.jsx("span",{style:{alignSelf:"center",fontSize:"0.85rem",color:"#666",minWidth:"30px"},children:G})]}),s.jsx("label",{style:Fe.label,children:"Notes (optional)"}),s.jsx("input",{value:ye,onChange:ie=>ke(ie.target.value),style:Fe.input,placeholder:"e.g. finely diced"})]})]}),s.jsxs("div",{style:Fe.modalFooter,children:[s.jsx("button",{onClick:()=>W(!1),style:Fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>hn.mutate({ingredient_id:H,quantity:parseFloat(J),unit:G||void 0,notes:ye||void 0}),disabled:!H||!J||hn.isPending,style:Fe.primaryBtn,children:hn.isPending?"Adding...":"Add"})]}),Ar.error&&s.jsx("div",{style:Fe.errorMsg,children:Ar.error.message})]})}),s.jsx(A0,{open:Ye,onClose:()=>De(!1),onSaved:ie=>{const nt=KN(ie.standard_unit);z(ie.id),te(ie.standard_unit),me(nt),U(ie.name)},prePopulateName:O}),s.jsx(A0,{open:!!qe&&!!yn,onClose:()=>ue(null),onSaved:()=>{ue(null),o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})},editingIngredient:yn||void 0}),K&&s.jsx("div",{style:Fe.overlay,children:s.jsxs("div",{style:Fe.modal,children:[s.jsxs("div",{style:Fe.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Sub-Recipe"}),s.jsx("button",{onClick:()=>de(!1),style:Fe.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Fe.modalBody,children:[s.jsx("label",{style:Fe.label,children:"Select Component Recipe"}),s.jsxs("select",{value:(Y==null?void 0:Y.toString())||"",onChange:ie=>{const nt=parseInt(ie.target.value);Q(nt);const $=tn==null?void 0:tn.find(ze=>ze.id===nt);Ne(($==null?void 0:$.batch_output_type)==="bulk"&&($==null?void 0:$.batch_yield_unit)||"")},style:Fe.input,children:[s.jsx("option",{value:"",children:"Select..."}),tn==null?void 0:tn.filter(ie=>ie.id!==e).map(ie=>s.jsxs("option",{value:ie.id,children:[ie.name," (",ie.batch_output_type==="bulk"?`yield: ${ie.batch_yield_qty}${ie.batch_yield_unit}`:`batch: ${ie.batch_portions}`,")"]},ie.id))]}),(()=>{const ie=tn==null?void 0:tn.find(Qe=>Qe.id===Y),nt=(ie==null?void 0:ie.batch_output_type)==="bulk",$=(ie==null?void 0:ie.batch_yield_unit)||"",ze=nt?$==="ml"||$==="ltr"?["ml","ltr"]:$==="g"||$==="kg"?["g","kg"]:[$]:[];return s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Fe.label,children:nt?"Amount":"Portions Needed"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:X,onChange:Qe=>pe(Qe.target.value),style:{...Fe.input,flex:1},step:nt?"0.1":"0.5",min:"0.1"}),nt&&ze.length>1?s.jsx("select",{value:we,onChange:Qe=>Ne(Qe.target.value),style:{...Fe.input,width:"80px",flex:"none"},children:ze.map(Qe=>s.jsx("option",{value:Qe,children:Qe},Qe))}):nt?s.jsx("span",{style:{padding:"0.5rem 0",fontSize:"0.85rem",color:"#555"},children:$}):null]})]})})()]}),s.jsxs("div",{style:Fe.modalFooter,children:[s.jsx("button",{onClick:()=>de(!1),style:Fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>Ar.mutate({child_recipe_id:Y,portions_needed:parseFloat(X),portions_needed_unit:we||void 0}),disabled:!Y||!X||Ar.isPending,style:Fe.primaryBtn,children:Ar.isPending?"Adding...":"Add"})]}),Ar.error&&s.jsx("div",{style:Fe.errorMsg,children:Ar.error.message})]})}),st&&s.jsx("div",{style:Fe.overlay,children:s.jsxs("div",{style:Fe.modal,children:[s.jsxs("div",{style:Fe.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:jt?"Edit Step":"Add Step"}),s.jsx("button",{onClick:()=>{Ve(!1),ct(null)},style:Fe.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Fe.modalBody,children:[s.jsx("label",{style:Fe.label,children:"Title (optional)"}),s.jsx("input",{value:Re,onChange:ie=>Le(ie.target.value),style:Fe.input,placeholder:"e.g. Prepare the base, Sear the protein"}),s.jsx("label",{style:Fe.label,children:"Instructions"}),s.jsx("textarea",{value:rt,onChange:ie=>$e(ie.target.value),style:{...Fe.input,minHeight:"80px"}}),s.jsx("label",{style:Fe.label,children:"Duration (minutes, optional)"}),s.jsx("input",{type:"number",value:ce,onChange:ie=>Je(ie.target.value),style:Fe.input})]}),s.jsxs("div",{style:Fe.modalFooter,children:[s.jsx("button",{onClick:()=>{Ve(!1),ct(null)},style:Fe.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>{jt?Lo.mutate({stepId:jt,data:{title:Re||"",instruction:rt,duration_minutes:ce?parseInt(ce):void 0}}):Qs.mutate({title:Re||void 0,instruction:rt,step_number:((Jt==null?void 0:Jt.steps.length)||0)+1,duration_minutes:ce?parseInt(ce):void 0})},disabled:!rt||Qs.isPending||Lo.isPending,style:Fe.primaryBtn,children:jt?Lo.isPending?"Saving...":"Save":Qs.isPending?"Adding...":"Add Step"})]})]})}),Lr&&s.jsxs("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.85)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,cursor:"pointer"},onClick:()=>Gs(null),children:[s.jsx("img",{src:Lr,alt:"Recipe image",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"},onClick:ie=>ie.stopPropagation()}),s.jsx("button",{onClick:()=>Gs(null),style:{position:"absolute",top:"20px",right:"20px",background:"rgba(255,255,255,0.2)",border:"none",color:"white",fontSize:"1.5rem",cursor:"pointer",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center"},children:"✕"})]})]})}const Fe={page:{padding:"1.5rem",maxWidth:"1000px",margin:"0 auto"},topBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},backBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},metaSection:{background:"white",padding:"1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},metaRow:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"0.75rem"},metaGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:"0.75rem",marginBottom:"0.75rem"},nameInput:{fontSize:"1.3rem",fontWeight:600,padding:"0.4rem",border:"1px solid #e0e0e0",borderRadius:"6px"},section:{background:"white",padding:"1rem 1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.5rem",fontSize:"0.85rem"},addBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},removeBtn:{padding:"2px 6px",background:"none",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.7rem",color:"#e94560"},costPanel:{background:"#f8f9fa",padding:"1.25rem",borderRadius:"8px",border:"2px solid #e0e0e0",marginBottom:"1rem"},costHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},costGrid:{display:"flex",gap:"1.5rem",flexWrap:"wrap"},costBox:{minWidth:"120px"},costLabel:{fontSize:"0.75rem",color:"#666",fontWeight:600},costValue:{fontSize:"1.3rem",fontWeight:700,color:"#333"},flagWarning:{background:"#fff3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem"},logEntry:{display:"flex",gap:"0.5rem",padding:"0.35rem 0",borderBottom:"1px solid #f0f0f0",alignItems:"center"},linkBtn:{background:"none",border:"none",color:"#3b82f6",cursor:"pointer",fontSize:"0.8rem",padding:0},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},secondaryBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.5rem",marginBottom:"0.2rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},suggestions:{background:"white",border:"1px solid #ddd",borderRadius:"6px",maxHeight:"150px",overflow:"auto",marginTop:"4px"},suggestionItem:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.85rem"},errorMsg:{padding:"0.75rem 1.25rem",color:"#dc3545",fontSize:"0.85rem"},reorderBtn:{padding:"0",width:"18px",height:"16px",background:"none",border:"1px solid #ddd",borderRadius:"3px",cursor:"pointer",fontSize:"0.55rem",color:"#666",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1},imageGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))",gap:"0.75rem"},imageCard:{background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0",overflow:"hidden"},imageThumb:{width:"100%",height:"120px",objectFit:"cover",display:"block"}};function Qfe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(!1),[o,a]=k.useState(""),[l,d]=k.useState(""),[c,u]=k.useState(""),{data:f,isLoading:p}=Oe({queryKey:["event-orders"],queryFn:async()=>{const v=await fetch("/api/event-orders",{headers:{Authorization:`Bearer ${n}`}});if(!v.ok)throw new Error("Failed");return v.json()},enabled:!!n}),g=Ue({mutationFn:async v=>{const x=await fetch("/api/event-orders",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(v)});if(!x.ok)throw new Error("Failed to create");return x.json()},onSuccess:v=>{t.invalidateQueries({queryKey:["event-orders"]}),i(!1),e(`/event-orders/${v.id}`)}}),m=Ue({mutationFn:async v=>{if(!(await fetch(`/api/event-orders/${v}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed")},onSuccess:()=>t.invalidateQueries({queryKey:["event-orders"]})}),y={DRAFT:"#f59e0b",FINALISED:"#3b82f6",ORDERED:"#22c55e"};return s.jsxs("div",{style:Pr.page,children:[s.jsxs("div",{style:Pr.header,children:[s.jsx("h2",{style:{margin:0},children:"Event Orders"}),s.jsx("button",{onClick:()=>{i(!0),a(""),d(""),u("")},style:Pr.primaryBtn,children:"+ New Event Order"})]}),p?s.jsx("div",{style:Pr.loading,children:"Loading..."}):f&&f.length>0?s.jsxs("table",{style:Pr.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Pr.th,children:"Name"}),s.jsx("th",{style:Pr.th,children:"Date"}),s.jsx("th",{style:Pr.th,children:"Status"}),s.jsx("th",{style:Pr.th,children:"Recipes"}),s.jsx("th",{style:Pr.th,children:"Actions"})]})}),s.jsx("tbody",{children:f.map(v=>s.jsxs("tr",{style:Pr.tr,onClick:()=>e(`/event-orders/${v.id}`),children:[s.jsx("td",{style:{...Pr.td,fontWeight:500,cursor:"pointer"},children:v.name}),s.jsx("td",{style:Pr.td,children:v.event_date||"-"}),s.jsx("td",{style:Pr.td,children:s.jsx("span",{style:{background:y[v.status]||"#ccc",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.75rem",fontWeight:600},children:v.status})}),s.jsx("td",{style:Pr.td,children:v.item_count}),s.jsx("td",{style:Pr.td,children:v.status==="DRAFT"&&s.jsx("button",{onClick:x=>{x.stopPropagation(),m.mutate(v.id)},style:{...Pr.smallBtn,color:"#e94560"},children:"Delete"})})]},v.id))})]}):s.jsx("div",{style:{textAlign:"center",padding:"3rem",color:"#888"},children:"No event orders yet. Create one to start planning."}),r&&s.jsx("div",{style:Pr.overlay,children:s.jsxs("div",{style:Pr.modal,children:[s.jsxs("div",{style:Pr.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"New Event Order"}),s.jsx("button",{onClick:()=>i(!1),style:Pr.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Pr.modalBody,children:[s.jsx("label",{style:Pr.label,children:"Event Name *"}),s.jsx("input",{value:o,onChange:v=>a(v.target.value),style:Pr.input,placeholder:"e.g. Wedding Reception 15th March"}),s.jsx("label",{style:Pr.label,children:"Event Date"}),s.jsx("input",{type:"date",value:l,onChange:v=>d(v.target.value),style:Pr.input}),s.jsx("label",{style:Pr.label,children:"Notes"}),s.jsx("textarea",{value:c,onChange:v=>u(v.target.value),style:{...Pr.input,minHeight:"60px"}})]}),s.jsxs("div",{style:Pr.modalFooter,children:[s.jsx("button",{onClick:()=>i(!1),style:Pr.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>g.mutate({name:o,event_date:l||void 0,notes:c||void 0}),disabled:!o||g.isPending,style:Pr.primaryBtn,children:"Create"})]})]})})]})}const Pr={page:{padding:"1.5rem",maxWidth:"1000px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},tr:{borderBottom:"1px solid #f0f0f0",cursor:"pointer"},td:{padding:"0.6rem 0.75rem",fontSize:"0.85rem"},smallBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"}};function $fe(){const{id:n}=G_(),e=parseInt(n||"0"),{token:t}=gn(),r=go(),i=pi(),[o,a]=k.useState(null),[l,d]=k.useState(""),[c,u]=k.useState(null),[f,p]=k.useState("1"),[g,m]=k.useState(null),[y,v]=k.useState([]),[x,w]=k.useState("1"),[S,_]=k.useState(!1),[b,C]=k.useState(!1),{data:T}=Oe({queryKey:["event-order",e],queryFn:async()=>{const ue=await fetch(`/api/event-orders/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Not found");return ue.json()},enabled:!!t&&!!e}),F=o==="recipe"?"component":o==="dish"?"dish":null,{data:A}=Oe({queryKey:["recipes-for-event",F],queryFn:async()=>{const ue=await fetch(`/api/recipes?recipe_type=${F}`,{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Failed");return ue.json()},enabled:!!t&&(o==="recipe"||o==="dish")}),{data:D}=Oe({queryKey:["menus-for-event"],queryFn:async()=>{const ue=await fetch("/api/menus",{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Failed");return ue.json()},enabled:!!t&&o==="menu"&&!g}),{data:P}=Oe({queryKey:["menu-detail-for-event",g],queryFn:async()=>{const ue=await fetch(`/api/menus/${g}`,{headers:{Authorization:`Bearer ${t}`}});if(!ue.ok)throw new Error("Failed");return ue.json()},enabled:!!t&&!!g}),{data:L}=Oe({queryKey:["event-shopping-list",e,b],queryFn:async()=>(await fetch(`/api/event-orders/${e}/shopping-list${b?"?group_by_supplier=true":""}`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&S}),W=Ue({mutationFn:async ue=>{if(!(await fetch(`/api/event-orders/${e}/items`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ue)})).ok)throw new Error("Failed")},onSuccess:()=>{i.invalidateQueries({queryKey:["event-order",e]}),i.invalidateQueries({queryKey:["event-shopping-list",e]}),I()}}),O=Ue({mutationFn:async ue=>{const Ze=await fetch(`/api/event-orders/${e}/items/bulk`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({items:ue})});if(!Ze.ok)throw new Error("Failed");return Ze.json()},onSuccess:()=>{i.invalidateQueries({queryKey:["event-order",e]}),i.invalidateQueries({queryKey:["event-shopping-list",e]}),I()}}),U=Ue({mutationFn:async ue=>{if(!(await fetch(`/api/event-orders/items/${ue}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>{i.invalidateQueries({queryKey:["event-order",e]}),i.invalidateQueries({queryKey:["event-shopping-list",e]})}}),M=Ue({mutationFn:async ue=>{if(!(await fetch(`/api/event-orders/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({status:ue})})).ok)throw new Error("Failed")},onSuccess:()=>i.invalidateQueries({queryKey:["event-order",e]})});function I(){a(null),d(""),u(null),p("1"),m(null),v([]),w("1")}function H(ue){m(ue),d("")}const z=ue=>{const Ze=new Set(((T==null?void 0:T.items)||[]).map(Z=>Z.recipe_id)),ee=[];for(const Z of ue.divisions)for(const ge of Z.items)ge.recipe_id&&!ge.is_archived&&ee.push({recipe_id:ge.recipe_id,display_name:ge.display_name,division_name:Z.name,checked:!Ze.has(ge.recipe_id),quantity:parseInt(x)||1});v(ee)};P&&y.length===0&&g&&z(P);function G(ue){w(ue);const Ze=parseInt(ue)||1;v(ee=>ee.map(Z=>({...Z,quantity:Ze})))}function te(ue,Ze){v(ee=>ee.map((Z,ge)=>ge===ue?{...Z,quantity:parseInt(Ze)||0}:Z))}function re(ue){v(Ze=>Ze.map((ee,Z)=>Z===ue?{...ee,checked:!ee.checked}:ee))}function me(){const ue=y.filter(Ze=>Ze.checked&&Ze.quantity>0).map(Ze=>({recipe_id:Ze.recipe_id,quantity:Ze.quantity,notes:`From menu: ${(P==null?void 0:P.name)||""}`}));ue.length>0&&O.mutate(ue)}if(!T)return s.jsx("div",{style:gt.loading,children:"Loading event order..."});const J=T.items.reduce((ue,Ze)=>ue+(Ze.subtotal||0),0),ne=T.items.reduce((ue,Ze)=>Ze.recipe_type==="dish"?ue+Ze.quantity:ue+Ze.quantity*Ze.batch_portions,0),ye=(A||[]).filter(ue=>!l||ue.name.toLowerCase().includes(l.toLowerCase())),Ye=(D||[]).filter(ue=>ue.is_active).filter(ue=>!l||ue.name.toLowerCase().includes(l.toLowerCase())),De=(L==null?void 0:L.by_supplier)||{},qe=Object.keys(De).sort();return s.jsxs("div",{style:gt.page,children:[s.jsxs("div",{style:gt.topBar,children:[s.jsx("button",{onClick:()=>r("/event-orders"),style:gt.backBtn,children:"← Back"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[T.status==="DRAFT"&&s.jsx("button",{onClick:()=>M.mutate("FINALISED"),style:gt.secondaryBtn,children:"Finalise"}),T.status==="FINALISED"&&s.jsx("button",{onClick:()=>M.mutate("ORDERED"),style:gt.primaryBtn,children:"Mark Ordered"})]})]}),s.jsxs("div",{style:gt.headerCard,children:[s.jsxs("div",{children:[s.jsx("h2",{style:{margin:0},children:T.name}),T.event_date&&s.jsx("div",{style:{color:"#888",marginTop:"4px"},children:T.event_date}),T.notes&&s.jsx("div",{style:{color:"#666",marginTop:"4px",fontSize:"0.85rem"},children:T.notes})]}),s.jsx("span",{style:{background:T.status==="DRAFT"?"#f59e0b":T.status==="FINALISED"?"#3b82f6":"#22c55e",color:"white",padding:"4px 12px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},children:T.status})]}),s.jsxs("div",{style:gt.section,children:[s.jsxs("div",{style:gt.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Items"}),s.jsxs("div",{style:{display:"flex",gap:"0.35rem"},children:[s.jsx("button",{onClick:()=>a("recipe"),style:gt.addBtn,children:"+ Recipe"}),s.jsx("button",{onClick:()=>a("dish"),style:gt.addBtn,children:"+ Dish"}),s.jsx("button",{onClick:()=>a("menu"),style:{...gt.addBtn,background:"#eff6ff",borderColor:"#93c5fd"},children:"+ Menu"})]})]}),T.items.length>0?s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Recipe"}),s.jsx("th",{style:gt.th,children:"Type"}),s.jsx("th",{style:gt.th,children:"Quantity"}),s.jsx("th",{style:gt.th,children:"Cost/Portion"}),s.jsx("th",{style:gt.th,children:"Subtotal"}),s.jsx("th",{style:gt.th})]})}),s.jsx("tbody",{children:T.items.map(ue=>s.jsxs("tr",{children:[s.jsxs("td",{style:gt.td,children:[s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>r(`/recipes/${ue.recipe_id}`),children:ue.recipe_name}),ue.notes&&s.jsx("span",{style:{fontSize:"0.7rem",color:"#999",marginLeft:"0.5rem"},children:ue.notes})]}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.recipe_type==="component"?`Component (${ue.batch_portions} per batch)`:"Dish"})}),s.jsx("td",{style:gt.td,children:ue.quantity}),s.jsx("td",{style:gt.td,children:ue.cost_per_portion!=null?`£${ue.cost_per_portion.toFixed(2)}`:"-"}),s.jsx("td",{style:gt.td,children:ue.subtotal!=null?`£${ue.subtotal.toFixed(2)}`:"-"}),s.jsx("td",{style:gt.td,children:s.jsx("button",{onClick:()=>U.mutate(ue.id),style:gt.removeBtn,children:"✕"})})]},ue.id))}),s.jsx("tfoot",{children:s.jsxs("tr",{style:{borderTop:"2px solid #ddd"},children:[s.jsx("td",{colSpan:4,style:{...gt.td,fontWeight:600,textAlign:"right"},children:"Total:"}),s.jsxs("td",{style:{...gt.td,fontWeight:600},children:["£",J.toFixed(2)]}),s.jsx("td",{})]})})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",padding:"1rem 0"},children:"No items added yet"}),T.items.length>0&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666",marginTop:"0.5rem"},children:["~",ne," total servings | £",ne>0?(J/ne).toFixed(2):"0.00","/head"]})]}),T.items.length>0&&s.jsxs("div",{style:gt.section,children:[s.jsxs("div",{style:gt.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Shopping List"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsxs("label",{style:{fontSize:"0.8rem"},children:[s.jsx("input",{type:"checkbox",checked:b,onChange:ue=>C(ue.target.checked)})," ","Group by supplier"]}),s.jsxs("button",{onClick:()=>_(!S),style:gt.addBtn,children:[S?"Hide":"Show"," Shopping List"]})]})]}),S&&L&&!b&&s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Ingredient"}),s.jsx("th",{style:gt.th,children:"Category"}),s.jsx("th",{style:gt.th,children:"Quantity"}),s.jsx("th",{style:gt.th,children:"Source"}),s.jsx("th",{style:gt.th,children:"Packs"}),s.jsx("th",{style:gt.th,children:"Est. Cost"})]})}),s.jsx("tbody",{children:L.items.map(ue=>s.jsxs("tr",{children:[s.jsx("td",{style:gt.td,children:ue.ingredient_name}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.category})}),s.jsxs("td",{style:gt.td,children:[ue.adjusted_quantity,ue.unit]}),s.jsx("td",{style:gt.td,children:ue.sources.length>0?ue.sources[0].supplier_name:s.jsx("span",{style:{color:"#f59e0b",fontSize:"0.8rem"},children:"No source"})}),s.jsx("td",{style:gt.td,children:ue.sources.length>0&&ue.sources[0].suggested_packs?`${ue.sources[0].suggested_packs} × ${ue.sources[0].pack_description||"pack"}`:"-"}),s.jsx("td",{style:gt.td,children:ue.sources.length>0&&ue.sources[0].subtotal!=null?`£${ue.sources[0].subtotal.toFixed(2)}`:"-"})]},ue.ingredient_id))})]}),S&&L&&b&&s.jsxs("div",{children:[qe.length===0&&s.jsx("p",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No supplier data available"}),qe.map(ue=>{const Ze=De[ue],ee=Ze.reduce((Z,ge)=>Z+(ge.subtotal||0),0);return s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0.4rem 0.5rem",background:"#f8f9fa",borderRadius:"4px",marginBottom:"0.25rem"},children:[s.jsx("strong",{style:{fontSize:"0.85rem"},children:ue}),ee>0&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#666"},children:["£",ee.toFixed(2)]})]}),s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Ingredient"}),s.jsx("th",{style:gt.th,children:"Quantity"}),s.jsx("th",{style:gt.th,children:"Packs"}),s.jsx("th",{style:gt.th,children:"Est. Cost"})]})}),s.jsx("tbody",{children:Ze.map((Z,ge)=>s.jsxs("tr",{children:[s.jsx("td",{style:gt.td,children:Z.ingredient_name}),s.jsxs("td",{style:gt.td,children:[Z.quantity_needed,Z.unit]}),s.jsx("td",{style:gt.td,children:Z.suggested_packs?`${Z.suggested_packs} × ${Z.pack_description||"pack"}`:"-"}),s.jsx("td",{style:gt.td,children:Z.subtotal!=null?`£${Z.subtotal.toFixed(2)}`:"-"})]},ge))})]})]},ue)}),L.items.filter(ue=>ue.sources.length===0).length>0&&s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("div",{style:{padding:"0.4rem 0.5rem",background:"#fef3c7",borderRadius:"4px",marginBottom:"0.25rem"},children:s.jsx("strong",{style:{fontSize:"0.85rem",color:"#92400e"},children:"No Supplier"})}),s.jsxs("table",{style:gt.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gt.th,children:"Ingredient"}),s.jsx("th",{style:gt.th,children:"Category"}),s.jsx("th",{style:gt.th,children:"Quantity"})]})}),s.jsx("tbody",{children:L.items.filter(ue=>ue.sources.length===0).map(ue=>s.jsxs("tr",{children:[s.jsx("td",{style:gt.td,children:ue.ingredient_name}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.category})}),s.jsxs("td",{style:gt.td,children:[ue.adjusted_quantity,ue.unit]})]},ue.ingredient_id))})]})]})]})]}),(o==="recipe"||o==="dish")&&s.jsx("div",{style:gt.overlay,onClick:I,children:s.jsxs("div",{style:gt.modal,onClick:ue=>ue.stopPropagation(),children:[s.jsxs("div",{style:gt.modalHeader,children:[s.jsxs("h3",{style:{margin:0},children:["Add ",o==="recipe"?"Recipe":"Dish"]}),s.jsx("button",{onClick:I,style:gt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:gt.modalBody,children:[s.jsx("input",{type:"text",value:l,onChange:ue=>d(ue.target.value),placeholder:`Search ${o==="recipe"?"recipes":"dishes"}...`,style:gt.input,autoFocus:!0}),s.jsxs("div",{style:{maxHeight:"250px",overflow:"auto",border:"1px solid #eee",borderRadius:"6px",marginTop:"0.5rem"},children:[ye.map(ue=>s.jsxs("div",{onClick:()=>u(ue.id),style:{padding:"0.5rem 0.75rem",cursor:"pointer",background:c===ue.id?"#eff6ff":"#fff",borderBottom:"1px solid #f3f4f6",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontWeight:c===ue.id?600:400,fontSize:"0.9rem"},children:ue.name}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:o==="recipe"?`batch: ${ue.batch_portions}`:ue.cost_per_portion!=null?`£${ue.cost_per_portion.toFixed(2)}/portion`:""})]},ue.id)),ye.length===0&&s.jsxs("p",{style:{padding:"0.75rem",color:"#999",textAlign:"center",margin:0,fontSize:"0.85rem"},children:["No ",o==="recipe"?"recipes":"dishes"," found"]})]}),c&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{style:gt.label,children:["Quantity (",o==="recipe"?"batches":"servings",")"]}),s.jsx("input",{type:"number",value:f,onChange:ue=>p(ue.target.value),style:gt.input,min:"1"})]})]}),s.jsxs("div",{style:gt.modalFooter,children:[s.jsx("button",{onClick:I,style:gt.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>c&&W.mutate({recipe_id:c,quantity:parseInt(f)||1}),disabled:!c||!f||W.isPending,style:gt.primaryBtn,children:W.isPending?"Adding...":"Add"})]})]})}),o==="menu"&&s.jsx("div",{style:gt.overlay,onClick:I,children:s.jsxs("div",{style:{...gt.modal,width:"600px"},onClick:ue=>ue.stopPropagation(),children:[s.jsxs("div",{style:gt.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:g?`Add from: ${(P==null?void 0:P.name)||"Loading..."}`:"Add Menu"}),s.jsx("button",{onClick:I,style:gt.closeBtn,children:"✕"})]}),s.jsxs("div",{style:gt.modalBody,children:[!g&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:l,onChange:ue=>d(ue.target.value),placeholder:"Search menus...",style:gt.input,autoFocus:!0}),s.jsxs("div",{style:{maxHeight:"300px",overflow:"auto",border:"1px solid #eee",borderRadius:"6px",marginTop:"0.5rem"},children:[Ye.map(ue=>s.jsxs("div",{onClick:()=>H(ue.id),style:{padding:"0.6rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f3f4f6",display:"flex",justifyContent:"space-between",alignItems:"center"},onMouseEnter:Ze=>Ze.currentTarget.style.background="#f9fafb",onMouseLeave:Ze=>Ze.currentTarget.style.background="#fff",children:[s.jsxs("div",{children:[s.jsx("span",{style:{fontWeight:500,fontSize:"0.9rem"},children:ue.name}),ue.description&&s.jsx("div",{style:{fontSize:"0.75rem",color:"#888"},children:ue.description})]}),s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:[ue.item_count," dish",ue.item_count!==1?"es":""]})]},ue.id)),Ye.length===0&&s.jsx("p",{style:{padding:"0.75rem",color:"#999",textAlign:"center",margin:0,fontSize:"0.85rem"},children:"No active menus found"})]})]}),g&&y.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"0.75rem"},children:[s.jsx("label",{style:{fontSize:"0.8rem",fontWeight:600,color:"#555",whiteSpace:"nowrap"},children:"Covers:"}),s.jsx("input",{type:"number",value:x,onChange:ue=>G(ue.target.value),style:{...gt.input,width:"80px"},min:"1"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:"Sets quantity for all dishes"})]}),s.jsx("div",{style:{maxHeight:"350px",overflow:"auto",border:"1px solid #eee",borderRadius:"6px"},children:s.jsxs("table",{style:{...gt.table,fontSize:"0.85rem"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...gt.th,width:"30px"}}),s.jsx("th",{style:gt.th,children:"Dish"}),s.jsx("th",{style:gt.th,children:"Section"}),s.jsx("th",{style:{...gt.th,width:"80px"},children:"Qty"})]})}),s.jsx("tbody",{children:y.map((ue,Ze)=>{const ee=((T==null?void 0:T.items)||[]).some(Z=>Z.recipe_id===ue.recipe_id);return s.jsxs("tr",{style:{opacity:ee?.5:1},children:[s.jsx("td",{style:gt.td,children:s.jsx("input",{type:"checkbox",checked:ue.checked,onChange:()=>re(Ze),disabled:ee})}),s.jsxs("td",{style:gt.td,children:[ue.display_name,ee&&s.jsx("span",{style:{fontSize:"0.7rem",color:"#f59e0b",marginLeft:"0.5rem"},children:"already added"})]}),s.jsx("td",{style:gt.td,children:s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:ue.division_name})}),s.jsx("td",{style:gt.td,children:s.jsx("input",{type:"number",value:ue.quantity,onChange:Z=>te(Ze,Z.target.value),style:{width:"60px",padding:"0.25rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.85rem",textAlign:"center"},min:"0",disabled:!ue.checked||ee})})]},Ze)})})]})})]}),g&&y.length===0&&P&&s.jsx("p",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No dishes on this menu"})]}),s.jsxs("div",{style:gt.modalFooter,children:[g&&s.jsx("button",{onClick:()=>{m(null),v([]),d("")},style:gt.cancelBtn,children:"← Back"}),s.jsx("button",{onClick:I,style:gt.cancelBtn,children:"Cancel"}),g&&s.jsx("button",{onClick:me,disabled:y.filter(ue=>ue.checked&&ue.quantity>0).length===0||O.isPending,style:gt.primaryBtn,children:O.isPending?"Adding...":`Add ${y.filter(ue=>ue.checked&&ue.quantity>0).length} Dishes`})]})]})})]})}const gt={page:{padding:"1.5rem",maxWidth:"1100px",margin:"0 auto"},topBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},backBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},headerCard:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",background:"white",padding:"1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},section:{background:"white",padding:"1rem 1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666"},td:{padding:"0.4rem 0.5rem",fontSize:"0.85rem",borderBottom:"1px solid #f0f0f0"},addBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},removeBtn:{padding:"2px 6px",background:"none",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.7rem",color:"#e94560"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},secondaryBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"}};function $P(n,e){return e==="g"&&n<1?`£${(n*1e3).toFixed(2)}/kg`:e==="ml"&&n<1?`£${(n*1e3).toFixed(2)}/ltr`:`£${n.toFixed(4)}/${e||"?"}`}function Zfe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(""),[o,a]=k.useState(""),[l,d]=k.useState(!1),[c,u]=k.useState(!1),[f,p]=k.useState("list"),[g,m]=k.useState(!1),[y,v]=k.useState(!1),[x,w]=k.useState(30),[S,_]=k.useState(null),[b,C]=k.useState(null),[T,F]=k.useState(""),[A,D]=k.useState(""),[P,L]=k.useState(""),[W,O]=k.useState({}),[U,M]=k.useState(null),[I,H]=k.useState(""),[z,G]=k.useState(""),[te,re]=k.useState(""),[me,J]=k.useState(""),[ne,ye]=k.useState(""),{data:ke}=Oe({queryKey:["dish-courses"],queryFn:async()=>{const Y=await fetch("/api/recipes/menu-sections?section_type=dish",{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch sections");return Y.json()},enabled:!!n}),{data:Ye,isLoading:De}=Oe({queryKey:["dishes",r,o,y],queryFn:async()=>{const Y=new URLSearchParams;r&&Y.set("search",r),Y.set("recipe_type","dish"),o&&Y.set("menu_section_id",o),y&&Y.set("archived","true");const Q=await fetch(`/api/recipes?${Y}`,{headers:{Authorization:`Bearer ${n}`}});if(!Q.ok)throw new Error("Failed to fetch dishes");return Q.json()},enabled:!!n}),{data:qe}=Oe({queryKey:["price-impact-dishes",x],queryFn:async()=>{const Y=await fetch(`/api/recipes/price-impact?days=${x}`,{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch price impact");return Y.json()},enabled:!!n}),ue=new Map;qe==null||qe.recipes.filter(Y=>Y.recipe_type==="dish").forEach(Y=>ue.set(Y.recipe_id,Y));const{data:Ze}=Oe({queryKey:["cost-trend",S],queryFn:async()=>{const Y=await fetch(`/api/recipes/${S}/cost-trend`,{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch cost trend");return Y.json()},enabled:!!n&&!!S}),ee=Ue({mutationFn:async Y=>{const Q=await fetch("/api/recipes",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(Y)});if(!Q.ok)throw new Error("Failed to create dish");return Q.json()},onSuccess:Y=>{t.invalidateQueries({queryKey:["dishes"]}),d(!1),e(`/dishes/${Y.id}`)}}),Z=Ue({mutationFn:async Y=>{const Q=await fetch(`/api/recipes/${Y}/duplicate`,{method:"POST",headers:{Authorization:`Bearer ${n}`}});if(!Q.ok)throw new Error("Failed to duplicate");return Q.json()},onSuccess:Y=>{t.invalidateQueries({queryKey:["dishes"]}),e(`/dishes/${Y.id}`)}}),ge=Ue({mutationFn:async Y=>{if(!(await fetch(`/api/recipes/${Y}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to archive")},onSuccess:()=>t.invalidateQueries({queryKey:["dishes"]})}),Te=Ue({mutationFn:async Y=>{if(!(await fetch(`/api/recipes/${Y}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_archived:!1})})).ok)throw new Error("Failed to unarchive")},onSuccess:()=>t.invalidateQueries({queryKey:["dishes"]})}),Be=Ue({mutationFn:async Y=>{const Q=await fetch("/api/recipes/menu-sections",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Y,section_type:"dish"})});if(!Q.ok)throw new Error("Failed to create course");return Q.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["dish-courses"]}),ye(""),u(!1)}}),he=Ue({mutationFn:async({id:Y,name:Q})=>{const X=await fetch(`/api/recipes/menu-sections/${Y}`,{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:Q})});if(!X.ok)throw new Error("Failed to update course");return X.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["dish-courses"]}),t.invalidateQueries({queryKey:["dishes"]}),M(null),H("")}}),He=Ue({mutationFn:async Y=>{const Q=await fetch(`/api/recipes/menu-sections/${Y}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}});if(!Q.ok)throw new Error("Failed to delete course");return Q.json()},onSuccess:()=>{t.invalidateQueries({queryKey:["dish-courses"]}),t.invalidateQueries({queryKey:["dishes"]})}}),{data:Ge}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>{const Y=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${n}`}});if(!Y.ok)throw new Error("Failed to fetch flag categories");return Y.json()},enabled:!!n&&g}),ae=(()=>{let Y=Ye||[];if(T.trim()){const pe=T.toLowerCase();Y=Y.filter(we=>we.name.toLowerCase().includes(pe)||we.flag_summary.some(Ne=>Ne.name.toLowerCase().includes(pe)))}if(A){const pe=parseFloat(A);isNaN(pe)||(Y=Y.filter(we=>we.cost_per_portion!=null&&we.cost_per_portion>=pe))}if(P){const pe=parseFloat(P);isNaN(pe)||(Y=Y.filter(we=>we.cost_per_portion!=null&&we.cost_per_portion<=pe))}const Q=Object.entries(W).filter(([,pe])=>pe==="include").map(([pe])=>pe),X=Object.entries(W).filter(([,pe])=>pe==="exclude").map(([pe])=>pe);return Q.length>0&&(Y=Y.filter(pe=>Q.every(we=>pe.flag_summary.some(Ne=>Ne.name===we&&Ne.active)))),X.length>0&&(Y=Y.filter(pe=>!X.some(we=>pe.flag_summary.some(Ne=>Ne.name===we&&Ne.active)))),Y})(),K=Y=>{const Q=ue.get(Y),X=S===Y?Ze==null?void 0:Ze.snapshots:void 0;return s.jsxs("div",{children:[X&&X.length>1&&(()=>{const pe=X.map(ot=>ot.cost_per_portion),we=Math.min(...pe),Ne=Math.max(...pe),st=Ne-we||1,Ve=460,Re=110,Le=40,rt=18,$e=Ve-Le*2,ce=Re-rt*2,Je=X.map((ot,ut)=>{const Ot=Le+ut/(X.length-1)*$e,An=rt+ce-(ot.cost_per_portion-we)/st*ce;return{x:Ot,y:An,...ot}}),jt=Je.map(ot=>`${ot.x},${ot.y}`).join(" "),ct=[we,we+st/2,Ne],Se=[0,Math.floor(X.length/2),X.length-1];return s.jsx("div",{children:s.jsxs("div",{style:{position:"relative"},children:[s.jsx("div",{style:{fontSize:"0.7rem",fontWeight:600,color:"#888",marginBottom:"4px"},children:"Cost Trend"}),s.jsxs("svg",{width:Ve,height:Re,style:{background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[ct.map((ot,ut)=>{const Ot=rt+ce-(ot-we)/st*ce;return s.jsxs("g",{children:[s.jsx("line",{x1:Le,y1:Ot,x2:Ve-Le,y2:Ot,stroke:"#f0f0f0",strokeWidth:"1"}),s.jsxs("text",{x:Le-4,y:Ot+3,textAnchor:"end",fontSize:"9",fill:"#888",children:["£",ot.toFixed(2)]})]},ut)}),Se.filter((ot,ut,Ot)=>Ot.indexOf(ot)===ut).map(ot=>{const ut=Je[ot],Ot=new Date(ut.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"});return s.jsx("text",{x:ut.x,y:Re-2,textAnchor:"middle",fontSize:"9",fill:"#888",children:Ot},ot)}),s.jsx("polyline",{points:jt,fill:"none",stroke:"#e94560",strokeWidth:"2"}),Je.map((ot,ut)=>s.jsx("circle",{cx:ot.x,cy:ot.y,r:3.5,fill:"#e94560",stroke:"white",strokeWidth:"1.5",style:{cursor:"pointer"},onMouseEnter:()=>{C({x:ot.x,y:ot.y-10,date:new Date(ot.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),cost:`£${ot.cost_per_portion.toFixed(2)}`,trigger:ot.trigger})},onMouseLeave:()=>C(null)},ut))]}),b&&s.jsxs("div",{style:{position:"absolute",left:b.x,top:b.y-50,transform:"translateX(-50%)",background:"#333",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"0.75rem",whiteSpace:"nowrap",pointerEvents:"none",zIndex:20},children:[s.jsx("div",{children:b.date}),s.jsx("div",{children:b.cost}),b.trigger&&s.jsx("div",{style:{color:"#ccc",fontSize:"0.7rem"},children:b.trigger})]})]})})})(),X&&X.length<=1&&s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.8rem",marginBottom:"6px"},children:"Not enough data for trend chart"}),!X&&s.jsx("div",{style:{color:"#888",fontSize:"0.8rem"},children:"Loading cost trend..."}),Q&&Q.ingredient_changes.length>0&&s.jsxs("div",{style:{marginTop:"8px"},children:[s.jsxs("div",{style:{fontWeight:600,fontSize:"0.7rem",color:"#888",marginBottom:"4px"},children:["Ingredient Price Changes (",Q.ingredient_changes.length,") — last ",x," days"]}),s.jsx("div",{style:{fontSize:"0.8rem",color:"#555"},children:Q.ingredient_changes.map((pe,we)=>s.jsxs("div",{style:{padding:"3px 0",borderBottom:wee(`/invoice/${pe.source_invoice_id}`),children:pe.source_invoice_number||`#${pe.source_invoice_id}`}),pe.ingredient_name&&pe.old_price!=null&&pe.new_price!=null?s.jsxs(s.Fragment,{children:[pe.ingredient_name,": ",$P(pe.old_price,pe.unit)," ","→"," ",$P(pe.new_price,pe.unit)]}):pe.ingredient_name&&pe.new_price!=null&&pe.old_price==null?s.jsxs(s.Fragment,{children:[pe.ingredient_name," price set: ",$P(pe.new_price,pe.unit)]}):pe.summary]}),pe.cost_impact!=null&&s.jsxs("span",{style:{fontFamily:"monospace",fontWeight:600,fontSize:"0.75rem",color:pe.cost_impact>0?"#dc2626":pe.cost_impact<0?"#16a34a":"#888",marginLeft:"1rem",whiteSpace:"nowrap"},children:[pe.cost_impact>0?"+":"","£",pe.cost_impact.toFixed(4),"/",Q.output_unit]})]},we))})]})]})},de=()=>{ee.mutate({name:z,recipe_type:"dish",menu_section_id:te?parseInt(te):null,batch_portions:1,description:me||null})};return s.jsxs("div",{style:_t.page,children:[s.jsxs("div",{style:_t.header,children:[s.jsx("h2",{style:{margin:0},children:"Dishes"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>u(!0),style:_t.secondaryBtn,children:"+ Course"}),s.jsx("button",{onClick:()=>{d(!0),G(""),re(""),J("")},style:_t.primaryBtn,children:"+ New Dish"})]})]}),s.jsxs("div",{style:_t.statsBar,children:[s.jsxs("span",{children:[ae.length," ",y?"archived ":"","dishes"]}),ue.size>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{style:{color:"#dc2626",fontWeight:600},children:[ue.size," with cost changes"]})]})]}),s.jsxs("div",{style:_t.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search dishes...",value:r,onChange:Y=>i(Y.target.value),style:_t.searchInput}),s.jsxs("select",{value:o,onChange:Y=>a(Y.target.value),style:_t.select,children:[s.jsx("option",{value:"",children:"All Courses"}),ke==null?void 0:ke.map(Y=>s.jsxs("option",{value:Y.id,children:[Y.name," (",Y.recipe_count,")"]},Y.id))]}),s.jsxs("label",{style:_t.checkLabel,children:[s.jsx("input",{type:"checkbox",checked:y,onChange:Y=>v(Y.target.checked)}),"Show Archived"]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.35rem"},children:[s.jsx("label",{style:{fontSize:"0.8rem",color:"#666",whiteSpace:"nowrap"},children:"Cost changes:"}),s.jsxs("select",{value:x,onChange:Y=>w(Number(Y.target.value)),style:{..._t.select,padding:"0.35rem 0.4rem",fontSize:"0.8rem"},children:[s.jsx("option",{value:7,children:"7d"}),s.jsx("option",{value:14,children:"14d"}),s.jsx("option",{value:30,children:"30d"}),s.jsx("option",{value:60,children:"60d"}),s.jsx("option",{value:90,children:"90d"})]})]}),s.jsx("button",{onClick:()=>m(!g),style:{..._t.secondaryBtn,padding:"0.5rem 0.75rem",fontSize:"0.85rem"},children:g?"Hide Filters":"Show Filters"}),s.jsxs("div",{style:{marginLeft:"auto",display:"flex",gap:"2px"},children:[s.jsx("button",{onClick:()=>p("card"),style:{..._t.viewToggleBtn,...f==="card"?_t.viewToggleBtnActive:{},borderRadius:"4px 0 0 4px"},children:"Cards"}),s.jsx("button",{onClick:()=>p("list"),style:{..._t.viewToggleBtn,...f==="list"?_t.viewToggleBtnActive:{},borderRadius:"0 4px 4px 0"},children:"List"})]})]}),g&&s.jsx("div",{style:_t.advancedFilterPanel,children:s.jsxs("div",{style:{display:"flex",gap:"1rem",flexWrap:"wrap",alignItems:"flex-start"},children:[s.jsxs("div",{style:{minWidth:"200px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Contains ingredient"}),s.jsx("input",{type:"text",placeholder:"Search by ingredient...",value:T,onChange:Y=>F(Y.target.value),style:{..._t.searchInput,width:"100%"}})]}),s.jsxs("div",{style:{minWidth:"150px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Cost/portion range"}),s.jsxs("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[s.jsx("input",{type:"number",placeholder:"Min",value:A,onChange:Y=>D(Y.target.value),style:{..._t.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"}),s.jsx("span",{style:{color:"#888"},children:"-"}),s.jsx("input",{type:"number",placeholder:"Max",value:P,onChange:Y=>L(Y.target.value),style:{..._t.searchInput,width:"80px",padding:"0.4rem"},step:"0.01"})]})]}),Ge&&Ge.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"250px"},children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"4px"},children:"Food flag filters"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Ge.flatMap(Y=>Y.flags||[]).map(Y=>{const Q=W[Y.name]||"neutral",X=Q==="neutral"?"include":Q==="include"?"exclude":"neutral";return s.jsxs("button",{onClick:()=>O(pe=>{const we={...pe};return X==="neutral"?delete we[Y.name]:we[Y.name]=X,we}),style:{padding:"2px 8px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:600,cursor:"pointer",border:"1px solid",borderColor:Q==="include"?"#22c55e":Q==="exclude"?"#ef4444":"#ddd",background:Q==="include"?"#dcfce7":Q==="exclude"?"#fef2f2":"white",color:Q==="include"?"#166534":Q==="exclude"?"#991b1b":"#666"},title:`${Y.name}: ${Q} (click to cycle)`,children:[Q==="include"?"+ ":Q==="exclude"?"- ":"",Y.code||Y.name]},Y.id)})})]})]})}),De?s.jsx("div",{style:_t.loading,children:"Loading dishes..."}):f==="card"?s.jsx("div",{style:_t.grid,children:ae.map(Y=>s.jsxs("div",{style:{..._t.card,...Y.is_archived?{opacity:.6}:{}},onClick:()=>e(`/dishes/${Y.id}`),children:[s.jsxs("div",{style:_t.cardHeader,children:[s.jsx("span",{style:{fontWeight:600,fontSize:"1rem",...Y.is_archived?{textDecoration:"line-through"}:{}},children:Y.name}),s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[Y.is_archived&&s.jsx("span",{style:{background:"#999",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:"ARCHIVED"}),s.jsx("span",{style:{background:"#3b82f6",color:"white",padding:"2px 8px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600,textTransform:"uppercase"},children:"DISH"})]})]}),Y.menu_section_name&&s.jsx("div",{style:_t.sectionTag,children:Y.menu_section_name}),Y.kds_menu_item_name&&s.jsxs("div",{style:{fontSize:"0.7rem",color:"#999",marginTop:"0.15rem"},children:["SambaPOS: ",Y.kds_menu_item_name,Y.sambapos_portion_name&&Y.sambapos_portion_name!=="Normal"&&` (${Y.sambapos_portion_name})`]}),s.jsxs("div",{style:_t.cardMeta,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Y.cost_per_portion!=null?s.jsxs("span",{style:_t.costBadge,children:["£",Y.cost_per_portion.toFixed(2),"/portion"]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"No costing"}),ue.has(Y.id)&&(()=>{const Q=ue.get(Y.id),X=(Q.cost_change??0)>0;return s.jsxs("span",{onClick:pe=>{pe.stopPropagation(),_(S===Y.id?null:Y.id),C(null)},style:{background:X?"#fef2f2":"#f0fdf4",color:X?"#dc2626":"#16a34a",border:`1px solid ${X?"#fca5a5":"#86efac"}`,padding:"1px 6px",borderRadius:"10px",fontSize:"0.65rem",fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},title:`${Q.ingredient_changes.length} ingredient price change(s) in last ${x}d`,children:[X?"▲":"▼"," ",Q.cost_change_pct!=null?`${Q.cost_change_pct>0?"+":""}${Q.cost_change_pct}%`:""]})})()]}),Y.gross_sell_price!=null&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#555"},children:["Sell: ","£",Y.gross_sell_price.toFixed(2)]}),Y.gross_sell_price!=null&&Y.cost_per_portion!=null&&(()=>{const Q=Y.gross_sell_price/1.2,X=(Q-Y.cost_per_portion)/Q*100;return s.jsxs("span",{style:{fontSize:"0.8rem",fontWeight:600,color:X>=70?"#16a34a":X>=60?"#ca8a04":"#dc2626"},children:[X.toFixed(1),"% GP"]})})()]}),S===Y.id&&s.jsx("div",{onClick:Q=>Q.stopPropagation(),style:{marginTop:"8px",borderTop:"1px solid #eee",paddingTop:"8px"},children:K(Y.id)}),Y.flag_summary.length>0&&s.jsx("div",{style:{marginTop:"6px"},children:s.jsx(T0,{flags:Y.flag_summary})}),s.jsxs("div",{style:_t.cardActions,children:[s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Z.mutate(Y.id)},style:_t.actionBtn,children:"Duplicate"}),Y.is_archived?s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Te.mutate(Y.id)},style:{..._t.actionBtn,color:"#22c55e"},children:"Restore"}):s.jsx("button",{onClick:Q=>{Q.stopPropagation(),ge.mutate(Y.id)},style:{..._t.actionBtn,color:"#e94560"},children:"Archive"})]})]},Y.id))}):s.jsxs("table",{style:_t.listTable,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:_t.listTh,children:"Name"}),s.jsx("th",{style:_t.listTh,children:"Type"}),s.jsx("th",{style:_t.listTh,children:"Course"}),s.jsx("th",{style:_t.listTh,children:"Cost/Portion"}),s.jsx("th",{style:_t.listTh,children:"Sell Price"}),s.jsx("th",{style:_t.listTh,children:"GP%"}),s.jsx("th",{style:_t.listTh,children:"Flags"}),s.jsx("th",{style:_t.listTh,children:"Actions"})]})}),s.jsx("tbody",{children:ae.map(Y=>s.jsxs(s.Fragment,{children:[s.jsxs("tr",{style:{..._t.listTr,cursor:"pointer",...Y.is_archived?{opacity:.6}:{}},onClick:()=>e(`/dishes/${Y.id}`),children:[s.jsxs("td",{style:_t.listTd,children:[s.jsx("span",{style:{fontWeight:500,...Y.is_archived?{textDecoration:"line-through"}:{}},children:Y.name}),Y.is_archived&&s.jsx("span",{style:{marginLeft:"0.5rem",fontSize:"0.7rem",color:"#999",fontStyle:"italic"},children:"archived"})]}),s.jsx("td",{style:_t.listTd,children:s.jsx("span",{style:{background:"#3b82f6",color:"white",padding:"1px 6px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600,textTransform:"uppercase"},children:"DISH"})}),s.jsx("td",{style:_t.listTd,children:Y.menu_section_name||"-"}),s.jsx("td",{style:_t.listTd,children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Y.cost_per_portion!=null?s.jsxs("span",{style:_t.costBadge,children:["£",Y.cost_per_portion.toFixed(2)]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"}),ue.has(Y.id)&&(()=>{const Q=ue.get(Y.id),X=(Q.cost_change??0)>0;return s.jsxs("span",{onClick:pe=>{pe.stopPropagation(),_(S===Y.id?null:Y.id),C(null)},style:{background:X?"#fef2f2":"#f0fdf4",color:X?"#dc2626":"#16a34a",border:`1px solid ${X?"#fca5a5":"#86efac"}`,padding:"1px 6px",borderRadius:"10px",fontSize:"0.65rem",fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},title:`${Q.ingredient_changes.length} ingredient price change(s) in last ${x}d — click to expand`,children:[X?"▲":"▼"," ",Q.cost_change_pct!=null?`${Q.cost_change_pct>0?"+":""}${Q.cost_change_pct}%`:""]})})()]})}),s.jsx("td",{style:_t.listTd,children:Y.gross_sell_price!=null?s.jsxs("span",{children:["£",Y.gross_sell_price.toFixed(2)]}):s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"})}),s.jsx("td",{style:_t.listTd,children:Y.gross_sell_price!=null&&Y.cost_per_portion!=null?(()=>{const Q=Y.gross_sell_price/1.2,X=(Q-Y.cost_per_portion)/Q*100;return s.jsxs("span",{style:{fontWeight:600,color:X>=70?"#16a34a":X>=60?"#ca8a04":"#dc2626"},children:[X.toFixed(1),"%"]})})():s.jsx("span",{style:{color:"#aaa",fontSize:"0.8rem"},children:"-"})}),s.jsx("td",{style:_t.listTd,children:Y.flag_summary.length>0&&s.jsx(T0,{flags:Y.flag_summary})}),s.jsxs("td",{style:_t.listTd,children:[s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Z.mutate(Y.id)},style:_t.actionBtn,children:"Duplicate"}),Y.is_archived?s.jsx("button",{onClick:Q=>{Q.stopPropagation(),Te.mutate(Y.id)},style:{..._t.actionBtn,color:"#22c55e",marginLeft:"4px"},children:"Restore"}):s.jsx("button",{onClick:Q=>{Q.stopPropagation(),ge.mutate(Y.id)},style:{..._t.actionBtn,color:"#e94560",marginLeft:"4px"},children:"Archive"})]})]},Y.id),S===Y.id&&s.jsx("tr",{children:s.jsx("td",{colSpan:8,style:{padding:"0.5rem 0.75rem 0.75rem 2rem",background:"#fafafa",borderBottom:"1px solid #e0e0e0"},children:K(Y.id)})},`${Y.id}-cost-detail`)]}))})]}),l&&s.jsx("div",{style:_t.overlay,children:s.jsxs("div",{style:_t.modal,children:[s.jsxs("div",{style:_t.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"New Dish"}),s.jsx("button",{onClick:()=>d(!1),style:_t.closeBtn,children:"✕"})]}),s.jsxs("div",{style:_t.modalBody,children:[s.jsx("label",{style:_t.label,children:"Name *"}),s.jsx("input",{value:z,onChange:Y=>G(Y.target.value),style:_t.input,placeholder:"e.g. Beef Burger, Caesar Salad"}),s.jsx("label",{style:_t.label,children:"Course"}),s.jsxs("select",{value:te,onChange:Y=>re(Y.target.value),style:_t.input,children:[s.jsx("option",{value:"",children:"None"}),ke==null?void 0:ke.map(Y=>s.jsx("option",{value:Y.id,children:Y.name},Y.id))]}),s.jsx("label",{style:_t.label,children:"Description"}),s.jsx("textarea",{value:me,onChange:Y=>J(Y.target.value),style:{..._t.input,minHeight:"60px"},placeholder:"Brief description..."})]}),s.jsxs("div",{style:_t.modalFooter,children:[s.jsx("button",{onClick:()=>d(!1),style:_t.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:de,disabled:!z||ee.isPending,style:_t.primaryBtn,children:ee.isPending?"Creating...":"Create Dish"})]})]})}),c&&s.jsx("div",{style:_t.overlay,children:s.jsxs("div",{style:{..._t.modal,width:"450px"},children:[s.jsxs("div",{style:_t.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Manage Courses"}),s.jsx("button",{onClick:()=>{u(!1),M(null)},style:_t.closeBtn,children:"✕"})]}),s.jsxs("div",{style:_t.modalBody,children:[ke&&ke.length>0&&s.jsx("div",{style:{marginBottom:"1rem"},children:ke.map(Y=>s.jsx("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.4rem 0",borderBottom:"1px solid #f0f0f0"},children:U===Y.id?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:I,onChange:Q=>H(Q.target.value),style:{..._t.input,flex:1},autoFocus:!0}),s.jsx("button",{onClick:()=>he.mutate({id:Y.id,name:I}),disabled:!I.trim(),style:{..._t.actionBtn,color:"#22c55e"},children:"Save"}),s.jsx("button",{onClick:()=>{M(null),H("")},style:_t.actionBtn,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1,fontSize:"0.9rem"},children:Y.name}),s.jsxs("span",{style:{fontSize:"0.75rem",color:"#888"},children:["(",Y.recipe_count,")"]}),s.jsx("button",{onClick:()=>{M(Y.id),H(Y.name)},style:_t.actionBtn,children:"Edit"}),s.jsx("button",{onClick:()=>{confirm(`Delete course "${Y.name}"? Dishes in this course will be unassigned.`)&&He.mutate(Y.id)},style:{..._t.actionBtn,color:"#e94560"},children:"Delete"})]})},Y.id))}),s.jsx("label",{style:_t.label,children:"Add New Course"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{value:ne,onChange:Y=>ye(Y.target.value),style:{..._t.input,flex:1},placeholder:"e.g. Starters, Mains, Desserts, Sides"}),s.jsx("button",{onClick:()=>Be.mutate(ne),disabled:!ne,style:_t.primaryBtn,children:"Add"})]})]}),s.jsx("div",{style:_t.modalFooter,children:s.jsx("button",{onClick:()=>{u(!1),M(null)},style:_t.cancelBtn,children:"Close"})})]})})]})}const _t={page:{padding:"1.5rem",maxWidth:"1400px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},statsBar:{display:"flex",gap:"0.75rem",fontSize:"0.85rem",color:"#666",marginBottom:"0.75rem"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},checkLabel:{display:"flex",alignItems:"center",gap:"0.35rem",fontSize:"0.85rem",color:"#555",cursor:"pointer",whiteSpace:"nowrap"},grid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:"1rem"},card:{background:"white",borderRadius:"8px",padding:"1rem",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",cursor:"pointer",transition:"box-shadow 0.2s",border:"1px solid #eee"},cardHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"0.5rem"},sectionTag:{fontSize:"0.75rem",color:"#888",marginTop:"2px"},cardMeta:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"8px"},costBadge:{background:"#f0fdf4",color:"#166534",padding:"2px 8px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},cardActions:{display:"flex",gap:"0.5rem",marginTop:"10px",borderTop:"1px solid #f0f0f0",paddingTop:"8px"},actionBtn:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"white",cursor:"pointer",fontSize:"0.75rem"},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600,fontSize:"0.9rem"},secondaryBtn:{padding:"0.6rem 1.25rem",background:"white",color:"#333",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.9rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.75rem",marginBottom:"0.25rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},viewToggleBtn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",background:"white",cursor:"pointer",fontSize:"0.8rem",color:"#666"},viewToggleBtnActive:{background:"#e94560",color:"white",borderColor:"#e94560"},advancedFilterPanel:{background:"#fafafa",border:"1px solid #eee",borderRadius:"8px",padding:"1rem",marginBottom:"1rem"},listTable:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},listTh:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},listTr:{borderBottom:"1px solid #f0f0f0"},listTd:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"}};function UK({menuId:n,divisions:e,preSelectedDivisionId:t,recipeId:r,recipeName:i,recipeDesc:o,recipePrice:a,onClose:l,onPublished:d}){const{token:c,user:u}=gn(),[f,p]=k.useState("select"),[g,m]=k.useState(r||null),[y,v]=k.useState(n||null),[x,w]=k.useState(t||null),[S,_]=k.useState(i||""),[b,C]=k.useState(o||""),[T,F]=k.useState(a?String(a):""),[A,D]=k.useState((u==null?void 0:u.name)||""),[P,L]=k.useState(""),[W,O]=k.useState(!1),{data:U}=Oe({queryKey:["settings"],queryFn:async()=>{const De=await fetch("/api/settings/",{headers:{Authorization:`Bearer ${c}`}});return De.ok?De.json():{llm_enabled:!1,anthropic_api_key_set:!1}},staleTime:6e4}),M=async()=>{const De=g||r;if(De){O(!0);try{const qe=await fetch("/api/menus/generate-description",{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({recipe_id:De,recipe_name:S||i||"",ingredients:[],allergen_flags:[]})});if(qe.ok){const ue=await qe.json();ue.description&&C(ue.description)}}catch{}O(!1)}},{data:I}=Oe({queryKey:["dishes-for-menu"],queryFn:async()=>{const De=await fetch("/api/recipes?recipe_type=dish",{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed to fetch dishes");return De.json()},enabled:!!c&&!r}),{data:H}=Oe({queryKey:["menus-for-publish"],queryFn:async()=>{const De=await fetch("/api/menus",{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed to fetch menus");return De.json()},enabled:!!c&&!n}),{data:z}=Oe({queryKey:["menu-divisions",y],queryFn:async()=>{const De=await fetch(`/api/menus/${y}`,{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed");return De.json()},enabled:!!c&&!!y&&!n}),{data:G,isLoading:te}=Oe({queryKey:["recipe-flags-for-publish",g],queryFn:async()=>{const De=await fetch(`/api/food-flags/recipes/${g}/flags`,{headers:{Authorization:`Bearer ${c}`}});if(!De.ok)throw new Error("Failed");return De.json()},enabled:!!c&&!!g}),re=e||(z==null?void 0:z.divisions)||[],me=(H||[]).filter(De=>De.is_active),J=(G==null?void 0:G.unassessed_ingredients)||[],ne=((G==null?void 0:G.flags)||[]).filter(De=>De.is_active),ye=J.length>0;k.useEffect(()=>{if(g&&I){const De=I.find(qe=>qe.id===g);De&&(_(De.name),C(De.description||""),F(De.gross_sell_price?String(De.gross_sell_price):""))}},[g,I]);const ke=Ue({mutationFn:async()=>{var qe;const De=await fetch(`/api/menus/${y}/items`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({recipe_id:g,division_id:x,display_name:S.trim(),description:b.trim()||null,price:T?parseFloat(T):null,confirmed_by_name:A.trim()})});if(!De.ok){const ue=await De.json().catch(()=>({}));throw new Error(typeof ue.detail=="string"?ue.detail:((qe=ue.detail)==null?void 0:qe.message)||"Failed to publish")}return De.json()},onSuccess:()=>d()}),Ye=(I||[]).filter(De=>!P||De.name.toLowerCase().includes(P.toLowerCase()));return s.jsx("div",{style:Ei.overlay,onClick:l,children:s.jsxs("div",{style:{...Ei.modal,maxWidth:"550px"},onClick:De=>De.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:f==="select"?"Publish Dish to Menu":"Confirm Allergens & Publish"}),f==="select"&&s.jsxs(s.Fragment,{children:[!r&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ei.label,children:"Select Dish *"}),s.jsx("input",{type:"text",value:P,onChange:De=>L(De.target.value),style:Ei.input,placeholder:"Search dishes..."}),s.jsxs("div",{style:{maxHeight:"200px",overflow:"auto",border:"1px solid #eee",borderRadius:"4px",marginTop:"0.25rem"},children:[Ye.map(De=>s.jsx("div",{onClick:()=>m(De.id),style:{padding:"0.5rem",cursor:"pointer",background:g===De.id?"#eff6ff":"#fff",borderBottom:"1px solid #f3f4f6"},children:s.jsx("span",{style:{fontWeight:g===De.id?600:400},children:De.name})},De.id)),Ye.length===0&&s.jsx("p",{style:{padding:"0.5rem",color:"#999"},children:"No dishes found"})]})]}),!n&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ei.label,children:"Menu *"}),s.jsxs("select",{value:y||"",onChange:De=>{v(parseInt(De.target.value)),w(null)},style:Ei.input,children:[s.jsx("option",{value:"",children:"Select a menu..."}),me.map(De=>s.jsx("option",{value:De.id,children:De.name},De.id))]})]}),re.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ei.label,children:"Section *"}),s.jsxs("select",{value:x||"",onChange:De=>w(parseInt(De.target.value)),style:Ei.input,children:[s.jsx("option",{value:"",children:"Select section..."}),re.map(De=>s.jsx("option",{value:De.id,children:De.name},De.id))]})]}),s.jsxs("div",{style:Ei.modalActions,children:[s.jsx("button",{onClick:l,style:Ei.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>p("confirm"),style:Ei.btnPrimary,disabled:!g||!y||!x,children:"Next: Review Allergens"})]})]}),f==="confirm"&&s.jsxs(s.Fragment,{children:[te&&s.jsx("p",{children:"Loading allergen data..."}),!te&&ye&&s.jsxs("div",{style:{background:"#fee2e2",padding:"0.75rem",borderRadius:"6px",marginBottom:"1rem"},children:[s.jsx("strong",{style:{color:"#dc2626"},children:"Cannot publish: unassessed ingredients"}),s.jsx("ul",{style:{margin:"0.5rem 0 0",paddingLeft:"1.25rem"},children:J.map((De,qe)=>s.jsxs("li",{style:{fontSize:"0.875rem"},children:[De.name," — ",De.category]},qe))})]}),!te&&!ye&&s.jsxs(s.Fragment,{children:[ne.length>0&&s.jsxs("div",{style:{marginBottom:"1rem"},children:[s.jsx("label",{style:Ei.label,children:"Confirmed Allergens"}),s.jsx("div",{style:{display:"flex",gap:"0.25rem",flexWrap:"wrap"},children:ne.map(De=>s.jsxs("span",{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"0.8rem",background:De.propagation_type==="contains"?"#fee2e2":"#dcfce7",color:De.propagation_type==="contains"?"#991b1b":"#166534"},children:[De.flag_code||De.flag_name,De.excludable_on_request&&" *"]},De.food_flag_id))})]}),s.jsx("label",{style:Ei.label,children:"Display Name *"}),s.jsx("input",{value:S,onChange:De=>_(De.target.value),style:Ei.input}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("label",{style:Ei.label,children:"Description"}),(U==null?void 0:U.llm_enabled)&&(U==null?void 0:U.anthropic_api_key_set)&&s.jsx("button",{onClick:M,disabled:W,style:{padding:"0.2rem 0.6rem",background:"#7952b3",color:"white",border:"none",borderRadius:"4px",cursor:W?"wait":"pointer",fontSize:"0.75rem",opacity:W?.7:1},children:W?"Generating...":"✨ Generate"})]}),s.jsx("textarea",{value:b,onChange:De=>C(De.target.value),style:{...Ei.input,minHeight:"60px",resize:"vertical"}}),s.jsx("label",{style:Ei.label,children:"Price"}),s.jsx("input",{type:"number",step:"0.01",value:T,onChange:De=>F(De.target.value),style:{...Ei.input,width:"120px"}}),s.jsx("label",{style:Ei.label,children:"Confirmed by *"}),s.jsx("input",{value:A,onChange:De=>D(De.target.value),style:Ei.input})]}),s.jsxs("div",{style:Ei.modalActions,children:[s.jsx("button",{onClick:()=>p("select"),style:Ei.btn,children:"Back"}),s.jsx("button",{onClick:l,style:Ei.btn,children:"Cancel"}),!ye&&s.jsx("button",{onClick:()=>ke.mutate(),style:Ei.btnPrimary,disabled:!S.trim()||!A.trim()||ke.isPending,children:ke.isPending?"Publishing...":"Publish to Menu"})]}),ke.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:ke.error.message})]})]})})}const Ei={overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"90%",maxHeight:"90vh",overflow:"auto"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.75rem"},input:{width:"100%",padding:"0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",boxSizing:"border-box"},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"}},Jfe={g:["g","kg"],kg:["g","kg"],ml:["ml","ltr"],ltr:["ml","ltr"],each:["each"],portion:["portion"]};function XN(n){return Jfe[n]||[n]}function epe(){var nt;const{id:n}=G_(),e=parseInt(n||"0"),{token:t,user:r}=gn(),i=go(),o=pi(),[a,l]=k.useState(""),[d,c]=k.useState(""),[u,f]=k.useState(""),[p,g]=k.useState(""),[m,y]=k.useState(""),[v,x]=k.useState(""),[w,S]=k.useState(""),[_,b]=k.useState(!1),[C,T]=k.useState(!1),[F,A]=k.useState(""),[D,P]=k.useState([]),[L,W]=k.useState(null),[O,U]=k.useState(""),[M,I]=k.useState([]),[H,z]=k.useState(""),[G,te]=k.useState(""),[re,me]=k.useState(!1),[J,ne]=k.useState(null),[ye,ke]=k.useState(null),[Ye,De]=k.useState(""),[qe,ue]=k.useState(""),[Ze,ee]=k.useState("100"),[Z,ge]=k.useState(""),[Te,Be]=k.useState(!1),[he,He]=k.useState(!1),[Ge,ae]=k.useState(null),[K,de]=k.useState(null),[Y,Q]=k.useState(null),[X,pe]=k.useState(!1),[we,Ne]=k.useState(null),[st,Ve]=k.useState(""),[Re,Le]=k.useState(""),[rt,$e]=k.useState(!1),[ce,Je]=k.useState(""),[jt,ct]=k.useState(""),[Se,ot]=k.useState(""),[ut,Ot]=k.useState(null),[An,on]=k.useState(""),[Ke,Rt]=k.useState(!1),[vt,Cr]=k.useState(""),[Qt,Ci]=k.useState(null),[Lr,Gs]=k.useState(""),[Ai,Ks]=k.useState(!1),[un,Fr]=k.useState(""),[zi,aa]=k.useState(!1),[Oi,Vd]=k.useState(!1),[Gn,Dr]=k.useState(null),[xr,Ss]=k.useState(null),[rs,Xs]=k.useState(null),[Jt,Ys]=k.useState(!1),{data:Ft}=Oe({queryKey:["recipe",e],queryFn:async()=>{const $=await fetch(`/api/recipes/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!$.ok)throw new Error("Not found");return $.json()},enabled:!!t&&!!e}),{data:Ea}=Oe({queryKey:["dish-courses"],queryFn:async()=>(await fetch("/api/recipes/menu-sections?section_type=dish",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:zn}=Oe({queryKey:["recipe-cost",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:gi}=Oe({queryKey:["recipe-cost-scaled",e,An],queryFn:async()=>(await fetch(`/api/recipes/${e}/costing?scale_to=${An}`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&!!An&&parseInt(An)>0}),{data:je}=Oe({queryKey:["recipe-flags",e],queryFn:async()=>(await fetch(`/api/food-flags/recipes/${e}/flags`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e}),{data:bt}=Oe({queryKey:["food-flag-categories"],queryFn:async()=>(await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t}),{data:yn}=Oe({queryKey:["recipe-changelog",e],queryFn:async()=>(await fetch(`/api/recipes/${e}/change-log`,{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&!!e&&Jt}),{data:tn}=Oe({queryKey:["recipe-cost-trend",e],queryFn:async()=>{const $=await fetch(`/api/recipes/${e}/cost-trend`,{headers:{Authorization:`Bearer ${t}`}});if(!$.ok)throw new Error("Failed to fetch cost trend");return $.json()},enabled:!!t&&!!e&&Oi}),{data:ci}=Oe({queryKey:["dish-menus",e],queryFn:async()=>{const $=await fetch(`/api/menus/dish/${e}/menus`,{headers:{Authorization:`Bearer ${t}`}});return $.ok?$.json():[]},enabled:!!t&&!!e}),{data:hn}=Oe({queryKey:["ingredient-edit",J],queryFn:async()=>{const $=await fetch(`/api/ingredients/${J}`,{headers:{Authorization:`Bearer ${t}`}});if(!$.ok)throw new Error("Not found");const ze=await $.json();return{id:ze.id,name:ze.name,category_id:ze.category_id,standard_unit:ze.standard_unit,yield_percent:Number(ze.yield_percent),manual_price:ze.manual_price!=null?Number(ze.manual_price):null,notes:ze.notes,is_prepackaged:ze.is_prepackaged||!1,is_free:ze.is_free||!1,product_ingredients:ze.product_ingredients,has_label_image:ze.has_label_image||!1}},enabled:!!t&&!!J}),{data:Ti}=Oe({queryKey:["recipes-list-for-sub"],queryFn:async()=>(await fetch("/api/recipes?recipe_type=component",{headers:{Authorization:`Bearer ${t}`}})).json(),enabled:!!t&&X}),{data:js}=Oe({queryKey:["sambapos-menu-items-portions"],queryFn:async()=>{const $=await fetch("/api/sambapos/menu-items-with-portions",{headers:{Authorization:`Bearer ${t}`}});return $.ok?$.json():[]},enabled:!!t&&Ai});k.useEffect(()=>{var $,ze,Qe,pt;Ft&&(l(Ft.name),c(Ft.description||""),f((($=Ft.prep_time_minutes)==null?void 0:$.toString())||""),g(((ze=Ft.cook_time_minutes)==null?void 0:ze.toString())||""),y(Ft.notes||""),x(((Qe=Ft.menu_section_id)==null?void 0:Qe.toString())||""),S(Ft.kds_menu_item_name||""),Gs(((pt=Ft.gross_sell_price)==null?void 0:pt.toString())||""),b(!1))},[Ft]),k.useEffect(()=>{if(!F||F.length<2||!t)return;const $=setTimeout(async()=>{try{const ze=await fetch(`/api/ingredients/suggest?description=${encodeURIComponent(F)}`,{headers:{Authorization:`Bearer ${t}`}});if(ze.ok){const Qe=await ze.json();P(Array.isArray(Qe)?Qe:Qe.suggestions||[])}else console.warn("Ingredient suggest failed:",ze.status,await ze.text().catch(()=>""))}catch(ze){console.warn("Ingredient suggest error:",ze)}},300);return()=>clearTimeout($)},[F,t]);const Ar=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),b(!1)}}),fs=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/ingredients`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)})).ok)throw new Error("Failed to add")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]}),T(!1),A(""),W(null),U(""),I([]),z(""),te("")}}),Qs=Ue({mutationFn:async({riId:$,quantity:ze,unit:Qe,yield_percent:pt,notes:kt})=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${$}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({quantity:ze,unit:Qe,yield_percent:pt,notes:kt})})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),ke(null)}}),Lo=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/recipe-ingredients/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to remove")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})}}),xn=Ue({mutationFn:async $=>{const ze=await fetch(`/api/recipes/${e}/sub-recipes`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)});if(!ze.ok){const Qe=await ze.json().catch(()=>({}));throw new Error(Qe.detail||"Failed to add sub-recipe")}},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]}),pe(!1)}}),Pa=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/recipe-sub-recipes/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-cost-trend",e]}),o.invalidateQueries({queryKey:["recipe-changelog",e]})}}),nn=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/steps`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify($)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),$e(!1),Je(""),ct(""),ot("")}}),Zl=Ue({mutationFn:async({stepId:$,data:ze})=>{if(!(await fetch(`/api/recipes/recipe-steps/${$}`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(ze)})).ok)throw new Error("Failed")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Ot(null),$e(!1),Je(""),ct(""),ot("")}}),qu=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/recipe-steps/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed")},onSuccess:()=>o.invalidateQueries({queryKey:["recipe",e]})}),$s=Ue({mutationFn:async({file:$,caption:ze,image_type:Qe})=>{const pt=new FormData;if(pt.append("file",$),pt.append("caption",ze),pt.append("image_type",Qe),!(await fetch(`/api/recipes/${e}/images`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:pt})).ok)throw new Error("Failed to upload image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]}),Rt(!1),Cr(""),Ci(null)}}),Gd=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/images/${$}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete image")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),mo=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/ingredients/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ingredient_ids:$})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Bc=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/sub-recipes/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({sub_recipe_ids:$})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Kd=Ue({mutationFn:async $=>{if(!(await fetch(`/api/recipes/${e}/steps/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({step_ids:$})})).ok)throw new Error("Failed to reorder steps")},onSuccess:()=>{o.invalidateQueries({queryKey:["recipe",e]})}}),Zs=($,ze)=>{ae($),Q(ze)},Ra=($,ze)=>{$.preventDefault(),de(ze)},Xd=()=>{if(Ge===null||K===null||!Ft||Y!=="ing"){ae(null),de(null),Q(null);return}const ze=[...[...Ft.ingredients].sort((pt,kt)=>pt.sort_order-kt.sort_order)],[Qe]=ze.splice(Ge,1);ze.splice(K,0,Qe),mo.mutate(ze.map(pt=>pt.id)),ae(null),de(null),Q(null)},No=()=>{if(Ge===null||K===null||!Ft||Y!=="sub"){ae(null),de(null),Q(null);return}const $=[...Ft.sub_recipes],[ze]=$.splice(Ge,1);$.splice(K,0,ze),Bc.mutate($.map(Qe=>Qe.id)),ae(null),de(null),Q(null)},Js=($,ze)=>{if(!Ft)return;const Qe=[...Ft.steps],pt=ze==="up"?$-1:$+1;if(pt<0||pt>=Qe.length)return;const kt=[...Qe],Ht=kt[$];kt[$]=kt[pt],kt[pt]=Ht,Kd.mutate(kt.map(Gt=>Gt.id))},Ba=()=>{Ar.mutate({name:a,description:d||null,batch_portions:1,prep_time_minutes:u?parseInt(u):null,cook_time_minutes:p?parseInt(p):null,notes:m||null,menu_section_id:v?parseInt(v):null,kds_menu_item_name:w||null,sambapos_portion_name:(Ft==null?void 0:Ft.sambapos_portion_name)||null,gross_sell_price:Lr&&parseFloat(Lr)>0?parseFloat(Lr):null})},Ic=$=>{window.open(`/api/recipes/${e}/print?format=${$}&token=${t}`,"_blank")};if(!Ft)return s.jsx("div",{style:Ce.loading,children:"Loading dish..."});const al=zn==null?void 0:zn.total_cost_recent,ie=zn==null?void 0:zn.cost_per_portion;return s.jsxs("div",{style:Ce.page,children:[s.jsxs("div",{style:Ce.topBar,children:[s.jsx("button",{onClick:()=>i("/dishes"),style:Ce.backBtn,children:"← Back"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("button",{onClick:()=>aa(!0),style:{...Ce.secondaryBtn,background:"#eff6ff",color:"#2563eb"},children:"Publish to Menu"}),s.jsx("button",{onClick:()=>Ic("kitchen"),style:Ce.secondaryBtn,children:"Print Kitchen Card"}),s.jsx("button",{onClick:()=>Ic("full"),style:Ce.secondaryBtn,children:"Print Full"}),_&&s.jsx("button",{onClick:Ba,disabled:Ar.isPending,style:Ce.primaryBtn,children:Ar.isPending?"Saving...":"Save Changes"})]})]}),s.jsxs("div",{style:Ce.metaSection,children:[s.jsxs("div",{style:Ce.metaRow,children:[s.jsx("input",{value:a,onChange:$=>{l($.target.value),b(!0)},style:{...Ce.nameInput,flex:1}}),s.jsx("span",{style:{background:"#3b82f6",color:"white",padding:"4px 12px",borderRadius:"4px",fontSize:"0.8rem",fontWeight:600},children:"DISH"})]}),ci&&ci.length>0&&s.jsxs("div",{style:{fontSize:"0.8rem",color:"#666",marginTop:"0.25rem"},children:["Published on: ",ci.map(($,ze)=>s.jsxs("span",{children:[ze>0&&", ",s.jsx("span",{style:{color:$.is_active?"#2563eb":"#999"},children:$.menu_name})]},$.menu_id))]}),s.jsxs("div",{style:Ce.metaGrid,children:[s.jsxs("div",{children:[s.jsx("label",{style:Ce.label,children:"Course"}),s.jsxs("select",{value:v,onChange:$=>{x($.target.value),b(!0)},style:Ce.input,children:[s.jsx("option",{value:"",children:"None"}),Ea==null?void 0:Ea.map($=>s.jsx("option",{value:$.id,children:$.name},$.id))]})]}),s.jsxs("div",{children:[s.jsx("label",{style:Ce.label,children:"Prep (min)"}),s.jsx("input",{type:"number",value:u,onChange:$=>{f($.target.value),b(!0)},style:Ce.input})]}),s.jsxs("div",{children:[s.jsx("label",{style:Ce.label,children:"Cook (min)"}),s.jsx("input",{type:"number",value:p,onChange:$=>{g($.target.value),b(!0)},style:Ce.input})]})]}),s.jsx("label",{style:Ce.label,children:"Description"}),s.jsx("textarea",{value:d,onChange:$=>{c($.target.value),b(!0)},style:{...Ce.input,minHeight:"50px"}}),s.jsx("label",{style:Ce.label,children:"SambaPOS Menu Item"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsxs("div",{onClick:()=>Ks(!0),style:{...Ce.input,cursor:"pointer",flex:1,display:"flex",alignItems:"center",justifyContent:"space-between",minHeight:"36px",background:"#fafafa"},children:[w?s.jsxs("span",{children:[s.jsx("strong",{children:w}),(Ft==null?void 0:Ft.sambapos_portion_name)&&Ft.sambapos_portion_name!=="Normal"&&s.jsxs("span",{style:{color:"#666",marginLeft:"0.5rem"},children:["(",Ft.sambapos_portion_name,")"]})]}):s.jsx("span",{style:{color:"#999"},children:"Click to select SambaPOS item..."}),s.jsx("span",{style:{color:"#999",fontSize:"0.8rem"},children:"▼"})]}),w&&s.jsx("button",{onClick:()=>{S(""),Ar.mutate({kds_menu_item_name:"",sambapos_portion_name:""})},style:{background:"none",border:"1px solid #ddd",borderRadius:"4px",padding:"6px 10px",cursor:"pointer",color:"#999",fontSize:"0.85rem"},title:"Clear SambaPOS link",children:"✕"})]})]}),je&&je.unassessed_ingredients.length>0&&s.jsxs("div",{style:Ce.flagWarning,children:[s.jsxs("strong",{children:[je.unassessed_ingredients.length," ingredient",je.unassessed_ingredients.length>1?"s are":" is"," missing allergen details"]})," — ",je.unassessed_ingredients.map($=>$.name).join(", ")]}),je&&je.open_suggestion_ingredients&&je.open_suggestion_ingredients.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsxs("strong",{children:[je.open_suggestion_ingredients.length," ingredient",je.open_suggestion_ingredients.length>1?"s have":" has"," unreviewed allergen suggestions"]})," — ",je.open_suggestion_ingredients.map(($,ze)=>s.jsxs("span",{children:[ze>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline",fontWeight:600},onClick:()=>ne($.ingredient_id),children:$.ingredient_name})," ","(",$.suggestion_count,")"]},$.ingredient_id))]}),je&&je.recipe_text_suggestions&&je.recipe_text_suggestions.length>0&&s.jsxs("div",{style:{background:"#fffbeb",color:"#b45309",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #f59e0b55"},children:[s.jsx("strong",{children:"Recipe text keyword matches"}),s.jsx("div",{style:{marginTop:"0.4rem"},children:je.recipe_text_suggestions.map($=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.3rem"},children:[s.jsxs("span",{children:[s.jsx("strong",{children:$.flag_name})," — ",$.matched_keywords.join(", ")]}),s.jsx("button",{style:{marginLeft:"auto",background:"none",border:"1px solid #b4530955",borderRadius:"4px",color:"#b45309",cursor:"pointer",padding:"0.15rem 0.5rem",fontSize:"0.8rem",whiteSpace:"nowrap"},onClick:async()=>{try{(await fetch(`/api/food-flags/recipes/${e}/text-dismissals`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_id:$.flag_id,dismissed_by_name:(r==null?void 0:r.name)||(r==null?void 0:r.email)||"Unknown",matched_keyword:$.matched_keywords.join(", ")})})).ok&&o.invalidateQueries({queryKey:["recipe-flags",e]})}catch{}},children:"Dismiss"})]},$.flag_id))})]}),Ft&&(()=>{const $=Ft.ingredients.filter(kt=>kt.is_manual_price),ze=Ft.ingredients.filter(kt=>kt.has_no_price),Qe=Ft.sub_recipes.filter(kt=>kt.has_manual_price_ingredients),pt=Ft.sub_recipes.filter(kt=>kt.has_no_price_ingredients);return $.length===0&&ze.length===0&&Qe.length===0&&pt.length===0?null:s.jsxs("div",{style:{background:"#fef3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem",border:"1px solid #ffc10755"},children:[ze.length>0&&s.jsxs("div",{children:[s.jsxs("strong",{children:[ze.length," ingredient",ze.length>1?"s have":" has"," no price"]})," — ",ze.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ne(kt.ingredient_id),children:kt.ingredient_name})]},kt.ingredient_id))]}),$.length>0&&s.jsxs("div",{style:{marginTop:ze.length>0?"0.3rem":0},children:[s.jsxs("strong",{children:[$.length," ingredient",$.length>1?"s use":" uses"," manual price"]})," — ",$.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>ne(kt.ingredient_id),children:kt.ingredient_name})]},kt.ingredient_id))]}),pt.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[pt.length," sub-recipe",pt.length>1?"s contain":" contains"," unpriced ingredients"]})," — ",pt.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${kt.child_recipe_id}`),children:kt.child_recipe_name})]},kt.child_recipe_id))]}),Qe.length>0&&s.jsxs("div",{style:{marginTop:"0.3rem"},children:[s.jsxs("strong",{children:[Qe.length," sub-recipe",Qe.length>1?"s contain":" contains"," manual-priced ingredients"]})," — ",Qe.map((kt,Ht)=>s.jsxs("span",{children:[Ht>0&&", ",s.jsx("span",{style:{cursor:"pointer",textDecoration:"underline"},onClick:()=>i(`/recipes/${kt.child_recipe_id}`),children:kt.child_recipe_name})]},kt.child_recipe_id))]})]})})(),je&&s.jsxs("div",{style:{margin:"0.75rem 0"},children:[je.flags.length>0&&s.jsx(T0,{flags:je.flags,size:"medium"}),bt&&bt.length>0&&s.jsx("div",{style:{display:"flex",gap:"0.35rem",marginTop:"0.5rem",flexWrap:"wrap"},children:bt.map($=>s.jsx("button",{onClick:()=>Xs(rs===$.id?null:$.id),style:{padding:"3px 10px",fontSize:"0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:rs===$.id?"#e94560":"#f5f5f5",color:rs===$.id?"white":"#555",cursor:"pointer"},children:$.name},$.id))})]}),rs!=null&&s.jsx(WK,{recipeId:e,categoryId:rs||void 0}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Ingredients"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Ft.ingredients.length>1&&s.jsx("button",{onClick:()=>Be(!Te),style:{...Ce.addBtn,background:Te?"#3b82f6":void 0,color:Te?"#fff":void 0},children:Te?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>T(!0),style:Ce.addBtn,children:"+ Add"})]})]}),s.jsxs("table",{style:Ce.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[Te&&s.jsx("th",{style:{...Ce.th,width:"30px"}}),s.jsx("th",{style:Ce.th,children:"Ingredient"}),s.jsx("th",{style:Ce.th,children:"Quantity"}),s.jsx("th",{style:Ce.th,children:"Yield %"}),s.jsx("th",{style:Ce.th,children:"Cost"}),s.jsx("th",{style:Ce.th,children:"Notes"}),s.jsx("th",{style:Ce.th})]})}),s.jsx("tbody",{children:[...Ft.ingredients].sort(($,ze)=>$.sort_order-ze.sort_order).map(($,ze)=>s.jsxs("tr",{style:{...Ce.tr,opacity:Y==="ing"&&Ge===ze?.4:1,background:Y==="ing"&&K===ze?"#e0f2fe":void 0},draggable:Te,onDragStart:()=>Zs(ze,"ing"),onDragOver:Qe=>Ra(Qe,ze),onDrop:Xd,onDragEnd:()=>{ae(null),de(null),Q(null)},children:[Te&&s.jsx("td",{style:{...Ce.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6",textDecoration:"none"},onClick:()=>ne($.ingredient_id),title:"Edit ingredient",children:$.ingredient_name})}),ye===$.id?s.jsxs(s.Fragment,{children:[s.jsx("td",{style:Ce.td,children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"2px"},children:[s.jsx("input",{type:"number",value:Ye,onChange:Qe=>De(Qe.target.value),style:{...Ce.input,width:"80px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.1",autoFocus:!0}),$.compatible_units&&$.compatible_units.length>1?s.jsx("select",{value:qe,onChange:Qe=>ue(Qe.target.value),style:{...Ce.input,width:"55px",padding:"0.25rem 0.2rem",fontSize:"0.75rem"},children:$.compatible_units.map(Qe=>s.jsx("option",{value:Qe,children:Qe},Qe))}):s.jsx("span",{style:{fontSize:"0.75rem",color:"#888"},children:$.unit})]})}),s.jsx("td",{style:Ce.td,children:s.jsx("input",{type:"number",value:Ze,onChange:Qe=>ee(Qe.target.value),style:{...Ce.input,width:"60px",padding:"0.25rem 0.4rem",fontSize:"0.85rem"},step:"0.5",min:"1",max:"100"})}),s.jsx("td",{style:Ce.td,children:$.cost!=null?`£${$.cost.toFixed(2)}`:"-"}),s.jsx("td",{style:Ce.td,children:s.jsx("input",{value:Z,onChange:Qe=>ge(Qe.target.value),style:{...Ce.input,width:"120px",padding:"0.25rem 0.4rem",fontSize:"0.8rem"},placeholder:"notes..."})}),s.jsx("td",{style:Ce.td,children:s.jsxs("div",{style:{display:"flex",gap:"4px"},children:[s.jsx("button",{onClick:()=>Qs.mutate({riId:$.id,quantity:parseFloat(Ye),unit:qe,yield_percent:parseFloat(Ze),notes:Z||void 0}),disabled:!Ye||Qs.isPending,style:{...Ce.addBtn,fontSize:"0.7rem",padding:"2px 6px",color:"#16a34a"},children:"Save"}),s.jsx("button",{onClick:()=>ke(null),style:{...Ce.removeBtn,color:"#888"},children:"Cancel"})]})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("td",{style:{...Ce.td,cursor:"pointer"},onClick:()=>{ke($.id),De($.quantity.toString()),ue($.unit),ee($.yield_percent.toString()),ge($.notes||"")},children:[$.quantity,$.unit]}),s.jsx("td",{style:{...Ce.td,cursor:"pointer"},onClick:()=>{ke($.id),De($.quantity.toString()),ue($.unit),ee($.yield_percent.toString()),ge($.notes||"")},children:$.yield_percent<100?s.jsxs("span",{style:{color:"#e94560"},children:[$.yield_percent,"%"]}):"100%"}),s.jsx("td",{style:Ce.td,children:$.cost!=null?s.jsxs("span",{style:$.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:$.is_manual_price?"Manual price":void 0,children:["£",$.cost.toFixed(2)]}):"-"}),s.jsx("td",{style:{...Ce.td,cursor:"pointer"},onClick:()=>{ke($.id),De($.quantity.toString()),ue($.unit),ee($.yield_percent.toString()),ge($.notes||"")},children:s.jsx("span",{style:{color:"#888",fontSize:"0.8rem"},children:$.notes||"-"})}),s.jsx("td",{style:Ce.td,children:s.jsx("button",{onClick:()=>Lo.mutate($.id),style:Ce.removeBtn,children:"✕"})})]})]},$.id))})]})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Sub-Recipes"}),s.jsxs("div",{style:{display:"flex",gap:"6px"},children:[Ft.sub_recipes.length>1&&s.jsx("button",{onClick:()=>He(!he),style:{...Ce.addBtn,background:he?"#3b82f6":void 0,color:he?"#fff":void 0},children:he?"✓ Done":"↕ Sort"}),s.jsx("button",{onClick:()=>pe(!0),style:Ce.addBtn,children:"+ Add"})]})]}),Ft.sub_recipes.length>0?s.jsxs("table",{style:Ce.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[he&&s.jsx("th",{style:{...Ce.th,width:"30px"}}),s.jsx("th",{style:Ce.th,children:"Recipe"}),s.jsx("th",{style:Ce.th,children:"Batch Output"}),s.jsx("th",{style:Ce.th,children:"Amount Used"}),s.jsx("th",{style:Ce.th,children:"Cost"}),s.jsx("th",{style:Ce.th})]})}),s.jsx("tbody",{children:Ft.sub_recipes.map(($,ze)=>s.jsxs("tr",{style:{...Ce.tr,opacity:Y==="sub"&&Ge===ze?.4:1,background:Y==="sub"&&K===ze?"#e0f2fe":void 0},draggable:he,onDragStart:()=>Zs(ze,"sub"),onDragOver:Qe=>Ra(Qe,ze),onDrop:No,onDragEnd:()=>{ae(null),de(null),Q(null)},children:[he&&s.jsx("td",{style:{...Ce.td,cursor:"grab",textAlign:"center",fontSize:"1rem",color:"#999"},children:"☰"}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${$.child_recipe_id}`),children:$.child_recipe_name})}),s.jsx("td",{style:Ce.td,children:$.batch_output_type==="bulk"?`${$.output_qty}${$.output_unit}`:`${$.batch_portions} portions`}),s.jsxs("td",{style:Ce.td,children:[$.portions_needed,$.batch_output_type==="bulk"?$.portions_needed_unit:" portions",$.batch_output_type==="bulk"&&$.portions_needed_unit!==$.output_unit&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#888",marginLeft:"4px"},children:["(",$.output_unit,")"]})]}),s.jsx("td",{style:Ce.td,children:$.cost_contribution!=null?s.jsxs("span",{style:$.has_manual_price_ingredients||$.has_no_price_ingredients?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0,title:$.has_manual_price_ingredients?"Includes manual-priced ingredients":$.has_no_price_ingredients?"Includes unpriced ingredients":void 0,children:["£",$.cost_contribution.toFixed(2)]}):"-"}),s.jsx("td",{style:Ce.td,children:s.jsx("button",{onClick:()=>Pa.mutate($.id),style:Ce.removeBtn,children:"✕"})})]},$.id))})]}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No sub-recipes added"})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Method"}),s.jsx("button",{onClick:()=>{Ot(null),Je(""),ct(""),ot(""),$e(!0)},style:Ce.addBtn,children:"+ Add Step"})]}),Ft.steps.length>0?s.jsx("div",{style:{margin:0},children:Ft.steps.map(($,ze)=>s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px",padding:"8px 0",borderBottom:"1px solid #f0f0f0"},children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"2px",flexShrink:0,marginTop:"2px"},children:[s.jsx("button",{onClick:()=>Js(ze,"up"),disabled:ze===0||Kd.isPending,style:{...Ce.reorderBtn,opacity:ze===0?.3:1},title:"Move up",children:"▲"}),s.jsx("button",{onClick:()=>Js(ze,"down"),disabled:ze===Ft.steps.length-1||Kd.isPending,style:{...Ce.reorderBtn,opacity:ze===Ft.steps.length-1?.3:1},title:"Move down",children:"▼"})]}),s.jsx("span",{style:{fontWeight:600,fontSize:"0.9rem",color:"#e94560",minWidth:"24px",marginTop:"1px"},children:ze+1}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:"6px"},children:[$.title&&s.jsx("span",{style:{fontWeight:600,fontSize:"0.95rem"},children:$.title}),$.duration_minutes&&s.jsxs("span",{style:{fontSize:"0.8rem",color:"#888"},children:["(",$.duration_minutes," min)"]})]}),s.jsx("div",{style:{fontSize:"0.85rem",color:"#555",marginTop:$.title?"2px":0,whiteSpace:"pre-wrap"},children:$.instruction})]}),s.jsxs("div",{style:{display:"flex",gap:"4px",flexShrink:0},children:[s.jsx("button",{onClick:()=>{Ot($.id),Je($.title||""),ct($.instruction),ot($.duration_minutes?String($.duration_minutes):""),$e(!0)},style:{...Ce.reorderBtn,fontSize:"0.75rem"},title:"Edit step",children:"✎"}),s.jsx("button",{onClick:()=>qu.mutate($.id),style:{...Ce.removeBtn,flexShrink:0},children:"✕"})]})]},$.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No steps added yet"})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Images"}),s.jsx("button",{onClick:()=>Rt(!Ke),style:Ce.addBtn,children:Ke?"Cancel":"+ Upload"})]}),Ke&&s.jsxs("div",{style:{marginBottom:"1rem",padding:"0.75rem",background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[s.jsx("label",{style:Ce.label,children:"Image File"}),s.jsx("input",{type:"file",accept:"image/*",onChange:$=>{var ze;return Ci(((ze=$.target.files)==null?void 0:ze[0])||null)},style:{...Ce.input,padding:"0.35rem"}}),s.jsx("label",{style:Ce.label,children:"Caption (optional)"}),s.jsx("input",{value:vt,onChange:$=>Cr($.target.value),style:Ce.input,placeholder:"Describe this image..."}),s.jsx("div",{style:{marginTop:"0.75rem",display:"flex",justifyContent:"flex-end"},children:s.jsx("button",{onClick:()=>{Qt&&$s.mutate({file:Qt,caption:vt,image_type:"general"})},disabled:!Qt||$s.isPending,style:Ce.primaryBtn,children:$s.isPending?"Uploading...":"Upload Image"})}),$s.error&&s.jsx("div",{style:Ce.errorMsg,children:$s.error.message})]}),Ft.images.length>0?s.jsx("div",{style:Ce.imageGrid,children:Ft.images.map($=>s.jsxs("div",{style:Ce.imageCard,children:[s.jsx("img",{src:`/api/recipes/${e}/images/${$.id}?token=${t}`,alt:$.caption||"Dish image",style:{...Ce.imageThumb,cursor:"pointer"},onClick:()=>Ss(`/api/recipes/${e}/images/${$.id}?token=${t}`)}),s.jsxs("div",{style:{padding:"0.4rem"},children:[$.caption&&s.jsx("div",{style:{fontSize:"0.8rem",color:"#333",marginTop:"2px"},children:$.caption}),s.jsx("button",{onClick:()=>{confirm("Delete this image?")&&Gd.mutate($.id)},style:{...Ce.removeBtn,marginTop:"4px",fontSize:"0.7rem"},children:"Delete"})]})]},$.id))}):s.jsx("div",{style:{color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"No images uploaded"})]}),s.jsxs("div",{style:Ce.costPanel,children:[s.jsx("div",{style:Ce.costHeader,children:s.jsx("h3",{style:{margin:0},children:"Cost Summary"})}),s.jsxs("div",{style:Ce.costGrid,children:[s.jsxs("div",{style:Ce.costBox,children:[s.jsx("div",{style:Ce.costLabel,children:"Dish Total"}),s.jsx("div",{style:Ce.costValue,children:al!=null?`£${al.toFixed(2)}`:"-"})]}),s.jsxs("div",{style:Ce.costBox,children:[s.jsx("div",{style:Ce.costLabel,children:"Portion Cost"}),s.jsx("div",{style:Ce.costValue,children:ie!=null?`£${ie.toFixed(2)}`:"-"})]}),(zn==null?void 0:zn.total_cost_min)!=null&&s.jsxs("div",{style:Ce.costBox,children:[s.jsx("div",{style:Ce.costLabel,children:"Min / Max"}),s.jsxs("div",{style:{fontSize:"0.85rem"},children:["£",zn.total_cost_min.toFixed(2)," – £",(nt=zn.total_cost_max)==null?void 0:nt.toFixed(2)]})]})]}),(zn==null?void 0:zn.gp_comparison)&&s.jsxs("div",{style:{marginTop:"0.75rem"},children:[s.jsx("strong",{style:{fontSize:"0.85rem"},children:"Suggested Sell Price (incl. VAT):"}),s.jsx("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.35rem",flexWrap:"wrap"},children:zn.gp_comparison.map($=>s.jsxs("div",{style:Ce.gpBadge,children:[$.gp_target,"% GP → ",s.jsxs("strong",{children:["£",$.suggested_price.toFixed(2)]})]},$.gp_target))})]}),ie!=null&&s.jsxs("div",{style:{marginTop:"0.75rem",display:"flex",gap:"0.75rem",alignItems:"flex-end",flexWrap:"wrap"},children:[s.jsxs("div",{children:[s.jsx("label",{style:{fontSize:"0.75rem",fontWeight:600,color:"#555",display:"block",marginBottom:"2px"},children:"Gross Sell Price"}),s.jsx("input",{type:"number",value:Lr,onChange:$=>{Gs($.target.value),b(!0)},style:{...Ce.input,width:"100px"},step:"0.5",min:"0",placeholder:"£"})]}),Lr&&parseFloat(Lr)>0&&(()=>{const ze=parseFloat(Lr)/1.2,Qe=(ze-ie)/ze*100,pt=Qe>=70?"#16a34a":Qe>=60?"#ca8a04":"#dc2626";return s.jsxs("div",{style:{...Ce.gpBadge,borderColor:pt,background:`${pt}10`},children:[s.jsxs("span",{style:{color:pt,fontWeight:700,fontSize:"1rem"},children:[Qe.toFixed(1),"% GP"]}),s.jsxs("span",{style:{color:"#888",fontSize:"0.75rem",marginLeft:"0.5rem"},children:["(net £",ze.toFixed(2),")"]})]})})()]}),s.jsx("div",{style:{marginTop:"0.5rem"},children:s.jsxs("button",{onClick:()=>Vd(!Oi),style:Ce.linkBtn,children:[Oi?"Hide":"Show"," cost trend"]})}),Oi&&(tn==null?void 0:tn.snapshots)&&tn.snapshots.length>1&&(()=>{const $=tn.snapshots,ze=$.map(Dt=>Dt.cost_per_portion),Qe=Math.min(...ze),pt=Math.max(...ze),kt=pt-Qe||1,Ht=500,Gt=120,Er=40,ar=20,Kn=Ht-Er*2,is=Gt-ar*2,On=$.map((Dt,Ln)=>{const Fi=Er+Ln/($.length-1)*Kn,Zr=ar+is-(Dt.cost_per_portion-Qe)/kt*is;return{x:Fi,y:Zr,...Dt}}),sn=On.map(Dt=>`${Dt.x},${Dt.y}`).join(" "),ps=[Qe,Qe+kt/2,pt],It=[0,Math.floor($.length/2),$.length-1],Tn=$.filter((Dt,Ln)=>Ln>0&&Dt.cost_per_portion!==$[Ln-1].cost_per_portion);return s.jsxs("div",{style:{marginTop:"0.5rem",display:"flex",gap:"1rem",alignItems:"flex-start"},children:[s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("svg",{width:Ht,height:Gt,style:{background:"white",borderRadius:"6px",border:"1px solid #e0e0e0"},children:[ps.map((Dt,Ln)=>{const Fi=ar+is-(Dt-Qe)/kt*is;return s.jsxs("g",{children:[s.jsx("line",{x1:Er,y1:Fi,x2:Ht-Er,y2:Fi,stroke:"#f0f0f0",strokeWidth:"1"}),s.jsxs("text",{x:Er-4,y:Fi+3,textAnchor:"end",fontSize:"9",fill:"#888",children:["£",Dt.toFixed(2)]})]},Ln)}),It.filter((Dt,Ln,Fi)=>Fi.indexOf(Dt)===Ln).map(Dt=>{const Ln=On[Dt],Fi=new Date(Ln.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"});return s.jsx("text",{x:Ln.x,y:Gt-2,textAnchor:"middle",fontSize:"9",fill:"#888",children:Fi},Dt)}),s.jsx("polyline",{points:sn,fill:"none",stroke:"#e94560",strokeWidth:"2"}),On.map((Dt,Ln)=>s.jsx("circle",{cx:Dt.x,cy:Dt.y,r:4,fill:"#e94560",stroke:"white",strokeWidth:"2",style:{cursor:"pointer"},onMouseEnter:Fi=>{var ll;const Zr=(ll=Fi.target.closest("svg"))==null?void 0:ll.getBoundingClientRect();Dr({x:Zr?Dt.x+Zr.left-((Zr==null?void 0:Zr.left)||0):Dt.x,y:Dt.y-10,date:new Date(Dt.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),cost:`£${Dt.cost_per_portion.toFixed(2)}`,trigger:Dt.trigger})},onMouseLeave:()=>Dr(null)},Ln))]}),Gn&&s.jsxs("div",{style:{position:"absolute",left:Gn.x,top:Gn.y-50,transform:"translateX(-50%)",background:"#333",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"0.75rem",whiteSpace:"nowrap",pointerEvents:"none",zIndex:20},children:[s.jsx("div",{children:Gn.date}),s.jsx("div",{children:Gn.cost}),s.jsx("div",{style:{color:"#ccc",fontSize:"0.7rem"},children:Gn.trigger})]})]}),Tn.length>0&&s.jsxs("div",{style:{flex:1,minWidth:"220px",maxHeight:"300px",overflow:"auto",fontSize:"0.75rem",background:"#fafafa",borderRadius:"6px",padding:"6px 8px",border:"1px solid #e0e0e0"},children:[s.jsxs("div",{style:{fontWeight:600,fontSize:"0.7rem",color:"#888",marginBottom:"4px"},children:["Change Log (",Tn.length," snapshots)"]}),Tn.slice().reverse().map((Dt,Ln)=>{const Fi=$[$.indexOf(Dt)-1],Zr=Dt.cost_per_portion-Fi.cost_per_portion,ll=Zr>0?"#dc2626":"#16a34a";return s.jsxs("div",{style:{padding:"3px 0",borderBottom:"1px solid #eee"},children:[s.jsxs("div",{style:{color:"#888"},children:[new Date(Dt.created_at).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}),s.jsxs("span",{style:{color:ll,fontWeight:600,marginLeft:"4px"},children:[Zr>0?"+":"","£",Zr.toFixed(4)]})]}),Dt.changes.length>0&&s.jsx("div",{style:{color:"#666",marginTop:"1px"},children:Dt.changes.map((Wo,Mc)=>s.jsx("div",{style:{fontSize:"0.7rem",lineHeight:1.3},children:Wo},Mc))})]},Ln)})]})]})})(),Oi&&(tn==null?void 0:tn.snapshots)&&tn.snapshots.length<=1&&s.jsx("div",{style:{marginTop:"0.5rem",color:"#888",fontStyle:"italic",fontSize:"0.85rem"},children:"Not enough data points to display a trend chart"})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("div",{style:Ce.sectionHeader,children:[s.jsx("h3",{style:{margin:0},children:"Scale Dish"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("input",{type:"number",value:An,onChange:$=>on($.target.value),style:{...Ce.input,width:"80px"},placeholder:Ft.batch_portions.toString(),min:"1"}),s.jsx("span",{style:{fontSize:"0.8rem",color:"#888"},children:"portions"})]})]}),(()=>{var kt;const $=gi||zn;if(!($!=null&&$.ingredients))return null;const ze=$.ingredients.reduce((Ht,Gt)=>Ht+(Gt.cost_recent??0),0)+(((kt=$.sub_recipes)==null?void 0:kt.reduce((Ht,Gt)=>Ht+(Gt.cost_contribution??0),0))??0),Qe=$.ingredients.reduce((Ht,Gt)=>Ht+(Gt.cost_min??0),0),pt=$.ingredients.reduce((Ht,Gt)=>Ht+(Gt.cost_max??0),0);return s.jsxs("table",{style:Ce.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:Ce.th,children:"Ingredient"}),s.jsx("th",{style:Ce.th,children:"Qty"}),s.jsx("th",{style:Ce.th,children:"Recent"}),s.jsx("th",{style:Ce.th,children:"Min"}),s.jsx("th",{style:Ce.th,children:"Max"})]})}),s.jsxs("tbody",{children:[$.ingredients.map(Ht=>{const Gt=Ht.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;return s.jsxs("tr",{children:[s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ne(Ht.ingredient_id),title:"Edit ingredient",children:Ht.ingredient_name})}),s.jsxs("td",{style:Ce.td,children:[Ht.quantity,Ht.unit]}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:Gt,title:Ht.is_manual_price?"Manual price":void 0,children:Ht.cost_recent!=null?`£${Ht.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:Gt,title:Ht.is_manual_price?"Manual price":void 0,children:Ht.cost_min!=null?`£${Ht.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:Ce.td,children:s.jsx("span",{style:Gt,title:Ht.is_manual_price?"Manual price":void 0,children:Ht.cost_max!=null?`£${Ht.cost_max.toFixed(2)}`:"-"})})]},Ht.ingredient_id)}),(()=>{const Ht=(Gt,Er)=>{var Kn,is;const ar=[];for(const On of Gt){const sn=Er*1.5,ps=On.child_ingredients&&On.child_ingredients.length>0||On.child_sub_recipes&&On.child_sub_recipes.length>0,It=((Kn=On.child_ingredients)==null?void 0:Kn.some(Dt=>Dt.is_manual_price))||!1,Tn=It?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;if(ar.push(s.jsx("tr",{children:s.jsxs("td",{colSpan:5,style:{...Ce.td,background:Er===0?"#f0f0f0":"#f5f5f5",fontWeight:600,fontSize:"0.8rem",color:"#555",paddingLeft:`${.5+sn}rem`},children:[Er>0&&"→ ",s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>i(`/recipes/${On.child_recipe_id}`),children:On.child_recipe_name})," (",On.portions_needed,On.output_unit==="portion"?" portions":On.output_unit,") — ",s.jsxs("span",{style:Tn,title:It?"Includes manual-priced ingredients":void 0,children:["£",((is=On.cost_contribution)==null?void 0:is.toFixed(2))??"-"]})]})},`sub-header-${Er}-${On.child_recipe_id}`)),ps){for(const Dt of On.child_ingredients||[]){const Ln=Dt.is_manual_price?{textDecoration:"underline dashed #b45309",textUnderlineOffset:"2px"}:void 0;ar.push(s.jsxs("tr",{style:{background:"#fafafa"},children:[s.jsx("td",{style:{...Ce.td,paddingLeft:`${1.5+sn}rem`,color:"#666"},children:s.jsx("span",{style:{cursor:"pointer",color:"#3b82f6"},onClick:()=>ne(Dt.ingredient_id),title:"Edit ingredient",children:Dt.ingredient_name})}),s.jsxs("td",{style:{...Ce.td,color:"#666"},children:[Dt.quantity,Dt.unit]}),s.jsx("td",{style:{...Ce.td,color:"#666"},children:s.jsx("span",{style:Ln,title:Dt.is_manual_price?"Manual price":void 0,children:Dt.cost_recent!=null?`£${Dt.cost_recent.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Ce.td,color:"#666"},children:s.jsx("span",{style:Ln,title:Dt.is_manual_price?"Manual price":void 0,children:Dt.cost_min!=null?`£${Dt.cost_min.toFixed(2)}`:"-"})}),s.jsx("td",{style:{...Ce.td,color:"#666"},children:s.jsx("span",{style:Ln,title:Dt.is_manual_price?"Manual price":void 0,children:Dt.cost_max!=null?`£${Dt.cost_max.toFixed(2)}`:"-"})})]},`sub-${Er}-${On.child_recipe_id}-ing-${Dt.ingredient_id}`))}On.child_sub_recipes&&On.child_sub_recipes.length>0&&ar.push(...Ht(On.child_sub_recipes,Er+1))}}return ar};return Ht($.sub_recipes||[],0)})(),s.jsxs("tr",{style:{borderTop:"2px solid #333"},children:[s.jsx("td",{style:{...Ce.td,fontWeight:700},children:"Total"}),s.jsx("td",{style:Ce.td}),s.jsx("td",{style:{...Ce.td,fontWeight:700},children:ze>0?`£${ze.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Ce.td,fontWeight:700},children:Qe>0?`£${Qe.toFixed(2)}`:"-"}),s.jsx("td",{style:{...Ce.td,fontWeight:700},children:pt>0?`£${pt.toFixed(2)}`:"-"})]})]})]})})()]}),s.jsxs("div",{style:Ce.section,children:[s.jsx("label",{style:Ce.label,children:"Notes"}),s.jsx("textarea",{value:m,onChange:$=>{y($.target.value),b(!0)},style:{...Ce.input,minHeight:"60px"}})]}),s.jsxs("div",{style:Ce.section,children:[s.jsxs("button",{onClick:()=>Ys(!Jt),style:Ce.linkBtn,children:[Jt?"Hide":"Show"," change history"]}),Jt&&yn&&s.jsx("div",{style:{marginTop:"0.5rem"},children:yn.map($=>s.jsxs("div",{style:Ce.logEntry,children:[s.jsx("span",{style:{color:"#888",fontSize:"0.75rem"},children:$.created_at}),s.jsx("span",{style:{fontSize:"0.75rem",color:"#555"},children:$.username}),s.jsx("span",{style:{fontSize:"0.85rem"},children:$.change_summary})]},$.id))})]}),C&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:Ce.modal,children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Ingredient"}),s.jsx("button",{onClick:()=>T(!1),style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("label",{style:Ce.label,children:"Search Ingredient"}),s.jsx("input",{value:F,onChange:$=>{A($.target.value),W(null)},style:Ce.input,placeholder:"Type to search..."}),F.length>=2&&!L&&s.jsxs("div",{style:Ce.suggestions,children:[D.map($=>s.jsxs("div",{style:Ce.suggestionItem,onClick:()=>{const ze=XN($.standard_unit);W($.id),U($.standard_unit),I(ze),A($.name)},children:[$.name," ",s.jsxs("span",{style:{color:"#888",fontSize:"0.75rem"},children:["(",Math.round($.similarity*100),"%)"]})]},$.id)),s.jsxs("div",{style:{...Ce.suggestionItem,color:"#16a34a",fontWeight:600,borderBottom:"none"},onClick:()=>me(!0),children:['+ Create "',F,'"']})]}),L&&s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ce.label,children:"Quantity"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:H,onChange:$=>z($.target.value),style:{...Ce.input,flex:1},step:"0.1"}),M.length>1?s.jsx("select",{value:O,onChange:$=>U($.target.value),style:{...Ce.input,width:"70px"},children:M.map($=>s.jsx("option",{value:$,children:$},$))}):s.jsx("span",{style:{alignSelf:"center",fontSize:"0.85rem",color:"#666",minWidth:"30px"},children:O})]}),s.jsx("label",{style:Ce.label,children:"Notes (optional)"}),s.jsx("input",{value:G,onChange:$=>te($.target.value),style:Ce.input,placeholder:"e.g. finely diced"})]})]}),s.jsxs("div",{style:Ce.modalFooter,children:[s.jsx("button",{onClick:()=>T(!1),style:Ce.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>fs.mutate({ingredient_id:L,quantity:parseFloat(H),unit:O||void 0,notes:G||void 0}),disabled:!L||!H||fs.isPending,style:Ce.primaryBtn,children:fs.isPending?"Adding...":"Add"})]}),xn.error&&s.jsx("div",{style:Ce.errorMsg,children:xn.error.message})]})}),s.jsx(A0,{open:re,onClose:()=>me(!1),onSaved:$=>{const ze=XN($.standard_unit);W($.id),U($.standard_unit),I(ze),A($.name)},prePopulateName:F}),s.jsx(A0,{open:!!J&&!!hn,onClose:()=>ne(null),onSaved:()=>{ne(null),o.invalidateQueries({queryKey:["recipe",e]}),o.invalidateQueries({queryKey:["recipe-cost",e]}),o.invalidateQueries({queryKey:["recipe-flags",e]})},editingIngredient:hn||void 0}),X&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:Ce.modal,children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Add Sub-Recipe"}),s.jsx("button",{onClick:()=>pe(!1),style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("label",{style:Ce.label,children:"Select Component Recipe"}),s.jsxs("select",{value:(we==null?void 0:we.toString())||"",onChange:$=>{const ze=parseInt($.target.value);Ne(ze);const Qe=Ti==null?void 0:Ti.find(pt=>pt.id===ze);Le((Qe==null?void 0:Qe.batch_output_type)==="bulk"&&(Qe==null?void 0:Qe.batch_yield_unit)||"")},style:Ce.input,children:[s.jsx("option",{value:"",children:"Select..."}),Ti==null?void 0:Ti.filter($=>$.id!==e).map($=>s.jsxs("option",{value:$.id,children:[$.name," (",$.batch_output_type==="bulk"?`yield: ${$.batch_yield_qty}${$.batch_yield_unit}`:`batch: ${$.batch_portions}`,")"]},$.id))]}),(()=>{const $=Ti==null?void 0:Ti.find(kt=>kt.id===we),ze=($==null?void 0:$.batch_output_type)==="bulk",Qe=($==null?void 0:$.batch_yield_unit)||"",pt=ze?Qe==="ml"||Qe==="ltr"?["ml","ltr"]:Qe==="g"||Qe==="kg"?["g","kg"]:[Qe]:[];return s.jsxs(s.Fragment,{children:[s.jsx("label",{style:Ce.label,children:ze?"Amount":"Portions Needed"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{type:"number",value:st,onChange:kt=>Ve(kt.target.value),style:{...Ce.input,flex:1},step:ze?"0.1":"0.5",min:"0.1"}),ze&&pt.length>1?s.jsx("select",{value:Re,onChange:kt=>Le(kt.target.value),style:{...Ce.input,width:"80px",flex:"none"},children:pt.map(kt=>s.jsx("option",{value:kt,children:kt},kt))}):ze?s.jsx("span",{style:{padding:"0.5rem 0",fontSize:"0.85rem",color:"#555"},children:Qe}):null]})]})})()]}),s.jsxs("div",{style:Ce.modalFooter,children:[s.jsx("button",{onClick:()=>pe(!1),style:Ce.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>xn.mutate({child_recipe_id:we,portions_needed:parseFloat(st),portions_needed_unit:Re||void 0}),disabled:!we||!st||xn.isPending,style:Ce.primaryBtn,children:xn.isPending?"Adding...":"Add"})]}),xn.error&&s.jsx("div",{style:Ce.errorMsg,children:xn.error.message})]})}),rt&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:Ce.modal,children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:ut?"Edit Step":"Add Step"}),s.jsx("button",{onClick:()=>{$e(!1),Ot(null)},style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("label",{style:Ce.label,children:"Title (optional)"}),s.jsx("input",{value:ce,onChange:$=>Je($.target.value),style:Ce.input,placeholder:"e.g. Prepare the base, Sear the protein"}),s.jsx("label",{style:Ce.label,children:"Instructions"}),s.jsx("textarea",{value:jt,onChange:$=>ct($.target.value),style:{...Ce.input,minHeight:"80px"}}),s.jsx("label",{style:Ce.label,children:"Duration (minutes, optional)"}),s.jsx("input",{type:"number",value:Se,onChange:$=>ot($.target.value),style:Ce.input})]}),s.jsxs("div",{style:Ce.modalFooter,children:[s.jsx("button",{onClick:()=>{$e(!1),Ot(null)},style:Ce.cancelBtn,children:"Cancel"}),s.jsx("button",{onClick:()=>{ut?Zl.mutate({stepId:ut,data:{title:ce||"",instruction:jt,duration_minutes:Se?parseInt(Se):void 0}}):nn.mutate({title:ce||void 0,instruction:jt,step_number:((Ft==null?void 0:Ft.steps.length)||0)+1,duration_minutes:Se?parseInt(Se):void 0})},disabled:!jt||nn.isPending||Zl.isPending,style:Ce.primaryBtn,children:ut?Zl.isPending?"Saving...":"Save":nn.isPending?"Adding...":"Add Step"})]})]})}),xr&&s.jsxs("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.85)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,cursor:"pointer"},onClick:()=>Ss(null),children:[s.jsx("img",{src:xr,alt:"Dish image",style:{maxWidth:"90vw",maxHeight:"90vh",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0,0,0,0.5)"},onClick:$=>$.stopPropagation()}),s.jsx("button",{onClick:()=>Ss(null),style:{position:"absolute",top:"20px",right:"20px",background:"rgba(255,255,255,0.2)",border:"none",color:"white",fontSize:"1.5rem",cursor:"pointer",borderRadius:"50%",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center"},children:"✕"})]}),zi&&Ft&&s.jsx(UK,{recipeId:Ft.id,recipeName:Ft.name,recipeDesc:Ft.description||"",recipePrice:Ft.gross_sell_price,onClose:()=>aa(!1),onPublished:()=>{aa(!1),o.invalidateQueries({queryKey:["dish-menus",e]})}}),Ai&&s.jsx("div",{style:Ce.overlay,children:s.jsxs("div",{style:{...Ce.modal,width:"550px"},children:[s.jsxs("div",{style:Ce.modalHeader,children:[s.jsx("h3",{style:{margin:0},children:"Select SambaPOS Menu Item"}),s.jsx("button",{onClick:()=>{Ks(!1),Fr("")},style:Ce.closeBtn,children:"✕"})]}),s.jsxs("div",{style:Ce.modalBody,children:[s.jsx("input",{value:un,onChange:$=>Fr($.target.value),style:{...Ce.input,marginBottom:"0.75rem"},placeholder:"Search menu items...",autoFocus:!0}),js?js.length===0?s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"No items found. Check SambaPOS connection and tracked categories."}):(()=>{const $=js.filter(Gt=>!un||Gt.menu_item_name.toLowerCase().includes(un.toLowerCase())||Gt.portion_name.toLowerCase().includes(un.toLowerCase())),ze={},Qe={};for(const Gt of $)ze[Gt.category]||(ze[Gt.category]={}),ze[Gt.category][Gt.menu_item_name]||(ze[Gt.category][Gt.menu_item_name]=[]),ze[Gt.category][Gt.menu_item_name].push(Gt.portion_name),Qe[Gt.menu_item_name]=Gt.on_pos_menu;const pt=o.getQueryData(["recipes-list-dish"]),kt={};if(pt){for(const Gt of pt)if(Gt.kds_menu_item_name){const Er=`${Gt.kds_menu_item_name}|${Gt.sambapos_portion_name||""}`;kt[Er]=Gt.name}}const Ht=(Gt,Er)=>{S(Gt),b(!0),Ar.mutate({kds_menu_item_name:Gt,sambapos_portion_name:Er==="Normal"?null:Er}),Ks(!1),Fr("")};return s.jsxs("div",{style:{maxHeight:"400px",overflow:"auto"},children:[Object.entries(ze).map(([Gt,Er])=>s.jsxs("div",{style:{marginBottom:"0.75rem"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"#e94560",textTransform:"uppercase",padding:"0.3rem 0",borderBottom:"1px solid #eee",marginBottom:"0.25rem"},children:Gt}),Object.entries(Er).map(([ar,Kn])=>{const is=Kn.length===1&&Kn[0]==="Normal";return s.jsx("div",{children:is?s.jsxs("div",{onClick:()=>Ht(ar,"Normal"),style:{padding:"0.4rem 0.5rem",cursor:"pointer",borderBottom:"1px solid #f5f5f5",fontSize:"0.85rem",display:"flex",justifyContent:"space-between",alignItems:"center"},onMouseEnter:On=>On.currentTarget.style.background="#f0f7ff",onMouseLeave:On=>On.currentTarget.style.background="transparent",children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[ar,s.jsxs("span",{style:{fontSize:"0.65rem",color:Qe[ar]?"#16a34a":"#ccc",fontWeight:600},children:["POS ",Qe[ar]?"✓":"✗"]})]}),kt[`${ar}|`]&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#999"},children:["→ ",kt[`${ar}|`]]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{padding:"0.4rem 0.5rem",fontSize:"0.85rem",fontWeight:600,color:"#333",borderBottom:"1px solid #f5f5f5",display:"flex",alignItems:"center",gap:"0.5rem"},children:[ar,s.jsxs("span",{style:{fontSize:"0.65rem",color:Qe[ar]?"#16a34a":"#ccc",fontWeight:600},children:["POS ",Qe[ar]?"✓":"✗"]})]}),Kn.map(On=>{const sn=`${ar}|${On==="Normal"?"":On}`;return s.jsxs("div",{onClick:()=>Ht(ar,On),style:{padding:"0.35rem 0.5rem 0.35rem 1.5rem",cursor:"pointer",borderBottom:"1px solid #f5f5f5",fontSize:"0.85rem",display:"flex",justifyContent:"space-between",alignItems:"center"},onMouseEnter:ps=>ps.currentTarget.style.background="#f0f7ff",onMouseLeave:ps=>ps.currentTarget.style.background="transparent",children:[s.jsxs("span",{style:{color:"#555"},children:["↳ ",On]}),kt[sn]&&s.jsxs("span",{style:{fontSize:"0.7rem",color:"#999"},children:["→ ",kt[sn]]})]},On)})]})},ar)})]},Gt)),Object.keys(ze).length===0&&s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"No items match your search."})]})})():s.jsx("div",{style:{color:"#888",textAlign:"center",padding:"1rem"},children:"Loading SambaPOS items..."})]})]})})]})}const Ce={page:{padding:"1.5rem",maxWidth:"1000px",margin:"0 auto"},topBar:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},backBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer"},metaSection:{background:"white",padding:"1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},metaRow:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"0.75rem"},metaGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:"0.75rem",marginBottom:"0.75rem"},nameInput:{fontSize:"1.3rem",fontWeight:600,padding:"0.4rem",border:"1px solid #e0e0e0",borderRadius:"6px"},section:{background:"white",padding:"1rem 1.25rem",borderRadius:"8px",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",marginBottom:"1rem"},sectionHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},table:{width:"100%",borderCollapse:"collapse"},th:{padding:"0.5rem 0.5rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",fontSize:"0.75rem",fontWeight:600,color:"#666"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.4rem 0.5rem",fontSize:"0.85rem"},addBtn:{padding:"0.35rem 0.75rem",background:"#f0f0f0",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.8rem"},removeBtn:{padding:"2px 6px",background:"none",border:"1px solid #ddd",borderRadius:"4px",cursor:"pointer",fontSize:"0.7rem",color:"#e94560"},costPanel:{background:"#f8f9fa",padding:"1.25rem",borderRadius:"8px",border:"2px solid #e0e0e0",marginBottom:"1rem"},costHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},costGrid:{display:"flex",gap:"1.5rem",flexWrap:"wrap"},costBox:{minWidth:"120px"},costLabel:{fontSize:"0.75rem",color:"#666",fontWeight:600},costValue:{fontSize:"1.3rem",fontWeight:700,color:"#333"},gpBadge:{background:"white",padding:"0.35rem 0.75rem",borderRadius:"6px",border:"1px solid #ddd",fontSize:"0.8rem"},flagWarning:{background:"#fff3cd",color:"#856404",padding:"0.75rem 1rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.85rem"},logEntry:{display:"flex",gap:"0.5rem",padding:"0.35rem 0",borderBottom:"1px solid #f0f0f0",alignItems:"center"},linkBtn:{background:"none",border:"none",color:"#3b82f6",cursor:"pointer",fontSize:"0.8rem",padding:0},primaryBtn:{padding:"0.6rem 1.25rem",background:"#e94560",color:"white",border:"none",borderRadius:"6px",cursor:"pointer",fontWeight:600},secondaryBtn:{padding:"0.5rem 1rem",background:"white",border:"1px solid #ddd",borderRadius:"6px",cursor:"pointer",fontSize:"0.85rem"},cancelBtn:{padding:"0.6rem 1.25rem",background:"#f0f0f0",color:"#333",border:"none",borderRadius:"6px",cursor:"pointer"},loading:{padding:"3rem",textAlign:"center",color:"#888"},overlay:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"white",borderRadius:"10px",width:"450px",maxWidth:"95vw",maxHeight:"90vh",overflow:"auto",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},modalHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"1rem 1.25rem",borderBottom:"1px solid #eee"},modalBody:{padding:"1.25rem"},modalFooter:{display:"flex",justifyContent:"flex-end",gap:"0.75rem",padding:"1rem 1.25rem",borderTop:"1px solid #eee"},closeBtn:{background:"none",border:"none",fontSize:"1.2rem",cursor:"pointer",color:"#888"},label:{display:"block",fontSize:"0.8rem",fontWeight:600,color:"#555",marginTop:"0.5rem",marginBottom:"0.2rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",boxSizing:"border-box"},suggestions:{background:"white",border:"1px solid #ddd",borderRadius:"6px",maxHeight:"150px",overflow:"auto",marginTop:"4px"},suggestionItem:{padding:"0.5rem 0.75rem",cursor:"pointer",borderBottom:"1px solid #f0f0f0",fontSize:"0.85rem"},errorMsg:{padding:"0.75rem 1.25rem",color:"#dc3545",fontSize:"0.85rem"},reorderBtn:{padding:"0",width:"18px",height:"16px",background:"none",border:"1px solid #ddd",borderRadius:"3px",cursor:"pointer",fontSize:"0.55rem",color:"#666",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1},imageGrid:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))",gap:"0.75rem"},imageCard:{background:"#f8f9fa",borderRadius:"6px",border:"1px solid #e0e0e0",overflow:"hidden"},imageThumb:{width:"100%",height:"120px",objectFit:"cover",display:"block"}};function tpe(){const{token:n}=gn(),e=go(),t=pi(),[r,i]=k.useState(""),[o,a]=k.useState(!1),[l,d]=k.useState(""),[c,u]=k.useState(""),[f,p]=k.useState(""),[g,m]=k.useState(!0),[y,v]=k.useState(!1),[x,w]=k.useState(null),[S,_]=k.useState(null),[b,C]=k.useState(null),[T,F]=k.useState(""),{data:A,isLoading:D}=Oe({queryKey:["menus"],queryFn:async()=>{const H=await fetch("/api/menus",{headers:{Authorization:`Bearer ${n}`}});if(!H.ok)throw new Error("Failed to fetch menus");return H.json()},enabled:!!n,staleTime:0}),P=Ue({mutationFn:async H=>{const z=await fetch("/api/menus",{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(H)});if(!z.ok){const G=await z.json().catch(()=>({}));throw new Error(G.detail||"Failed to create menu")}return z.json()},onSuccess:H=>{t.invalidateQueries({queryKey:["menus"]}),a(!1),d(""),u(""),p(""),e(`/menus/${H.id}`)}}),L=Ue({mutationFn:async({id:H,is_active:z})=>{if(!(await fetch(`/api/menus/${H}`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({is_active:z})})).ok)throw new Error("Failed to update")},onSuccess:()=>t.invalidateQueries({queryKey:["menus"]})}),W=Ue({mutationFn:async H=>{if(!(await fetch(`/api/menus/${H}`,{method:"DELETE",headers:{Authorization:`Bearer ${n}`}})).ok)throw new Error("Failed to delete")},onSuccess:()=>t.invalidateQueries({queryKey:["menus"]})}),O=Ue({mutationFn:async({id:H,name:z})=>{const G=await fetch(`/api/menus/${H}/duplicate`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({name:z})});if(!G.ok){const te=await G.json().catch(()=>({}));throw new Error(te.detail||"Failed to duplicate")}return G.json()},onSuccess:H=>{t.invalidateQueries({queryKey:["menus"]}),C(null),F(""),e(`/menus/${H.id}`)}}),U=Ue({mutationFn:async H=>{if(!(await fetch("/api/menus/reorder",{method:"PATCH",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({ids:H})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>t.invalidateQueries({queryKey:["menus"]})}),M=()=>{if(x===null||S===null||!A)return;const H=[...A],[z]=H.splice(x,1);H.splice(S,0,z),U.mutate(H.map(G=>G.id)),w(null),_(null)},I=(A==null?void 0:A.filter(H=>!r||H.name.toLowerCase().includes(r.toLowerCase())))||[];return s.jsxs("div",{style:Xn.container,children:[s.jsxs("div",{style:Xn.header,children:[s.jsx("h2",{style:Xn.title,children:"Menus"}),s.jsxs("div",{style:Xn.headerActions,children:[s.jsx("input",{type:"text",placeholder:"Search menus...",value:r,onChange:H=>i(H.target.value),style:Xn.searchInput}),I.length>1&&s.jsx("button",{onClick:()=>v(!y),style:{...Xn.btn,background:y?"#3b82f6":void 0,color:y?"#fff":void 0},children:y?"Done":"Sort"}),s.jsx("button",{onClick:()=>a(!0),style:Xn.btnPrimary,children:"+ New Menu"})]})]}),D&&s.jsx("p",{style:{padding:"1rem"},children:"Loading..."}),!D&&I.length===0&&s.jsx("p",{style:{padding:"1rem",color:"#666"},children:"No menus found. Create your first menu to get started."}),s.jsx("div",{style:Xn.list,children:I.map((H,z)=>s.jsxs("div",{style:{...Xn.card,opacity:x===z?.4:1,background:S===z?"#e0f2fe":"#fff"},draggable:y,onDragStart:()=>{w(z)},onDragOver:G=>{G.preventDefault(),_(z)},onDrop:M,onDragEnd:()=>{w(null),_(null)},children:[y&&s.jsx("span",{style:Xn.dragHandle,children:"☰"}),s.jsxs("div",{style:Xn.cardContent,onClick:()=>e(`/menus/${H.id}`),children:[s.jsxs("div",{style:Xn.cardHeader,children:[s.jsx("span",{style:Xn.menuName,children:H.name}),s.jsx("span",{style:{...Xn.badge,background:H.is_active?"#dcfce7":"#f3f4f6",color:H.is_active?"#166534":"#6b7280"},children:H.is_active?"Active":"Inactive"})]}),H.description&&s.jsx("p",{style:Xn.desc,children:H.description}),s.jsxs("div",{style:Xn.meta,children:[s.jsxs("span",{children:[H.division_count," section",H.division_count!==1?"s":""]}),s.jsx("span",{style:{margin:"0 0.5rem"},children:"·"}),s.jsxs("span",{children:[H.item_count," dish",H.item_count!==1?"es":""]}),H.stale_count>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{margin:"0 0.5rem"},children:"·"}),s.jsxs("span",{style:{background:"#fef3c7",color:"#92400e",padding:"1px 6px",borderRadius:"3px",fontSize:"0.75rem",fontWeight:600},children:[H.stale_count," need",H.stale_count===1?"s":""," republishing"]})]})]})]}),s.jsxs("div",{style:Xn.cardActions,children:[s.jsx("button",{onClick:G=>{G.stopPropagation(),L.mutate({id:H.id,is_active:!H.is_active})},style:Xn.btnSmall,title:H.is_active?"Deactivate":"Activate",children:H.is_active?"Deactivate":"Activate"}),s.jsx("button",{onClick:G=>{G.stopPropagation(),C(H.id),F(`${H.name} (Copy)`)},style:Xn.btnSmall,children:"Duplicate"}),s.jsx("button",{onClick:G=>{G.stopPropagation(),confirm(`Delete "${H.name}"? This will remove all divisions and items.`)&&W.mutate(H.id)},style:{...Xn.btnSmall,color:"#dc2626"},children:"Delete"})]})]},H.id))}),o&&s.jsx("div",{style:Xn.overlay,onClick:()=>a(!1),children:s.jsxs("div",{style:Xn.modal,onClick:H=>H.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:"New Menu"}),s.jsx("label",{style:Xn.label,children:"Name *"}),s.jsx("input",{type:"text",value:l,onChange:H=>d(H.target.value),style:Xn.input,placeholder:"e.g. Evening Menu",autoFocus:!0}),s.jsx("label",{style:Xn.label,children:"Description (customer-facing)"}),s.jsx("input",{type:"text",value:c,onChange:H=>u(H.target.value),style:Xn.input,placeholder:"e.g. Seasonal tasting menu"}),s.jsx("label",{style:Xn.label,children:"Internal Notes"}),s.jsx("textarea",{value:f,onChange:H=>p(H.target.value),style:{...Xn.input,minHeight:"60px",resize:"vertical"},placeholder:"e.g. Available Fri-Sun 6pm-9pm"}),s.jsxs("label",{style:Xn.checkboxLabel,children:[s.jsx("input",{type:"checkbox",checked:g,onChange:H=>m(H.target.checked)}),s.jsx("span",{style:{marginLeft:"0.5rem"},children:"Pre-load default sections (Starters, Mains, Sides, Desserts)"})]}),s.jsxs("div",{style:Xn.modalActions,children:[s.jsx("button",{onClick:()=>a(!1),style:Xn.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>P.mutate({name:l.trim(),description:c.trim()||null,notes:f.trim()||null,preset_divisions:g}),style:Xn.btnPrimary,disabled:!l.trim()||P.isPending,children:P.isPending?"Creating...":"Create Menu"})]}),P.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:P.error.message})]})}),b!==null&&s.jsx("div",{style:Xn.overlay,onClick:()=>C(null),children:s.jsxs("div",{style:Xn.modal,onClick:H=>H.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:"Duplicate Menu"}),s.jsx("label",{style:Xn.label,children:"New menu name *"}),s.jsx("input",{type:"text",value:T,onChange:H=>F(H.target.value),style:Xn.input,autoFocus:!0}),s.jsxs("div",{style:Xn.modalActions,children:[s.jsx("button",{onClick:()=>C(null),style:Xn.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>O.mutate({id:b,name:T.trim()}),style:Xn.btnPrimary,disabled:!T.trim()||O.isPending,children:O.isPending?"Duplicating...":"Duplicate"})]}),O.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:O.error.message})]})})]})}const Xn={container:{maxWidth:"900px",margin:"0 auto",padding:"1rem"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",flexWrap:"wrap",gap:"0.5rem",marginBottom:"1rem"},title:{margin:0,fontSize:"1.5rem"},headerActions:{display:"flex",gap:"0.5rem",alignItems:"center",flexWrap:"wrap"},searchInput:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",width:"200px"},list:{display:"flex",flexDirection:"column",gap:"0.5rem"},card:{display:"flex",alignItems:"center",gap:"0.75rem",padding:"0.75rem 1rem",border:"1px solid #e5e7eb",borderRadius:"8px",background:"#fff",cursor:"pointer",transition:"box-shadow 0.2s"},dragHandle:{cursor:"grab",fontSize:"1rem",color:"#999"},cardContent:{flex:1,minWidth:0},cardHeader:{display:"flex",alignItems:"center",gap:"0.5rem"},menuName:{fontWeight:600,fontSize:"1rem"},badge:{padding:"2px 8px",borderRadius:"12px",fontSize:"0.75rem",fontWeight:500},desc:{margin:"0.25rem 0 0",fontSize:"0.875rem",color:"#666"},meta:{fontSize:"0.8rem",color:"#999",marginTop:"0.25rem"},cardActions:{display:"flex",gap:"0.25rem",flexShrink:0},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnSmall:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.75rem"},overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",minWidth:"360px",maxWidth:"500px",width:"90%"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.75rem"},input:{width:"100%",padding:"0.5rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",boxSizing:"border-box"},checkboxLabel:{display:"flex",alignItems:"center",marginTop:"1rem",fontSize:"0.875rem",cursor:"pointer"}};function npe({menuId:n,divisionId:e,divisionName:t,onClose:r,onPublished:i}){const{token:o,user:a}=gn(),[l,d]=k.useState("select"),[c,u]=k.useState(new Set),[f,p]=k.useState(""),[g,m]=k.useState((a==null?void 0:a.name)||""),[y,v]=k.useState({}),[x,w]=k.useState({}),{data:S}=Oe({queryKey:["dishes-for-bulk"],queryFn:async()=>{const D=await fetch("/api/recipes?recipe_type=dish",{headers:{Authorization:`Bearer ${o}`}});if(!D.ok)throw new Error("Failed");return D.json()},enabled:!!o}),{data:_}=Oe({queryKey:["bulk-flag-check",Array.from(c)],queryFn:async()=>{const D={};for(const P of c){const L=await fetch(`/api/food-flags/recipes/${P}/flags`,{headers:{Authorization:`Bearer ${o}`}});if(L.ok){const W=await L.json();D[P]={ok:!W.unassessed_ingredients||W.unassessed_ingredients.length===0,unassessed:W.unassessed_ingredients}}else D[P]={ok:!1}}return D},enabled:!!o&&l==="confirm"&&c.size>0}),b=Ue({mutationFn:async()=>{var W;const P=Array.from(c).filter(O=>{var U;return(U=_==null?void 0:_[O])==null?void 0:U.ok}).map(O=>{const U=S==null?void 0:S.find(M=>M.id===O);return{recipe_id:O,display_name:y[O]||(U==null?void 0:U.name)||"",description:(U==null?void 0:U.description)||null,price:x[O]?parseFloat(x[O]):(U==null?void 0:U.gross_sell_price)||null}}),L=await fetch(`/api/menus/${n}/items/bulk`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({division_id:e,confirmed_by_name:g.trim(),items:P})});if(!L.ok){const O=await L.json().catch(()=>({}));throw new Error(((W=O.detail)==null?void 0:W.message)||"Failed to bulk publish")}return L.json()},onSuccess:()=>i()}),C=(S||[]).filter(D=>!f||D.name.toLowerCase().includes(f.toLowerCase())),T=D=>{const P=new Set(c);P.has(D)?P.delete(D):P.add(D),u(P)},F=_?Array.from(c).filter(D=>{var P;return(P=_[D])==null?void 0:P.ok}).length:0,A=_?Array.from(c).filter(D=>_[D]&&!_[D].ok).length:0;return s.jsx("div",{style:ca.overlay,onClick:r,children:s.jsxs("div",{style:{...ca.modal,maxWidth:"600px"},onClick:D=>D.stopPropagation(),children:[s.jsxs("h3",{style:{margin:"0 0 0.5rem"},children:['Bulk Add Dishes to "',t,'"']}),l==="select"&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:f,onChange:D=>p(D.target.value),style:ca.input,placeholder:"Search dishes..."}),s.jsxs("div",{style:{maxHeight:"350px",overflow:"auto",border:"1px solid #eee",borderRadius:"4px",marginTop:"0.5rem"},children:[C.map(D=>{var P;return s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.5rem",cursor:"pointer",background:c.has(D.id)?"#eff6ff":"#fff",borderBottom:"1px solid #f3f4f6"},children:[s.jsx("input",{type:"checkbox",checked:c.has(D.id),onChange:()=>T(D.id)}),s.jsx("span",{style:{flex:1},children:D.name}),(P=D.flag_summary)==null?void 0:P.filter(L=>L.active).map((L,W)=>s.jsx("span",{style:ca.flagBadge,children:L.code||L.name},W))]},D.id)}),C.length===0&&s.jsx("p",{style:{padding:"0.5rem",color:"#999"},children:"No dishes found"})]}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#666",marginTop:"0.5rem"},children:[c.size," selected"]}),s.jsxs("div",{style:ca.modalActions,children:[s.jsx("button",{onClick:r,style:ca.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>d("confirm"),style:ca.btnPrimary,disabled:c.size===0,children:"Next: Review"})]})]}),l==="confirm"&&s.jsxs(s.Fragment,{children:[!_&&s.jsx("p",{children:"Checking allergens..."}),_&&s.jsxs(s.Fragment,{children:[A>0&&s.jsxs("div",{style:{background:"#fee2e2",padding:"0.5rem",borderRadius:"6px",marginBottom:"0.75rem",fontSize:"0.875rem"},children:[s.jsxs("strong",{style:{color:"#dc2626"},children:[A," dish",A!==1?"es":""," blocked"]})," — unassessed ingredients"]}),s.jsx("div",{style:{maxHeight:"300px",overflow:"auto"},children:Array.from(c).map(D=>{const P=S==null?void 0:S.find(W=>W.id===D),L=_[D];return P?s.jsxs("div",{style:{padding:"0.5rem",borderBottom:"1px solid #eee",opacity:L!=null&&L.ok?1:.5},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{fontWeight:500},children:P.name}),!(L!=null&&L.ok)&&s.jsx("span",{style:{color:"#dc2626",fontSize:"0.75rem"},children:"BLOCKED"})]}),(L==null?void 0:L.ok)&&s.jsxs("div",{style:{display:"flex",gap:"0.25rem",marginTop:"0.25rem"},children:[s.jsx("input",{value:y[D]??P.name,onChange:W=>v(O=>({...O,[D]:W.target.value})),style:{...ca.inputSm,flex:1},placeholder:"Display name"}),s.jsx("input",{value:x[D]??(P.gross_sell_price?String(P.gross_sell_price):""),onChange:W=>w(O=>({...O,[D]:W.target.value})),style:{...ca.inputSm,width:"80px"},placeholder:"Price"})]})]},D):null})}),s.jsx("label",{style:ca.label,children:"Confirmed by *"}),s.jsx("input",{value:g,onChange:D=>m(D.target.value),style:ca.input}),s.jsxs("div",{style:ca.modalActions,children:[s.jsx("button",{onClick:()=>d("select"),style:ca.btn,children:"Back"}),s.jsx("button",{onClick:r,style:ca.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>b.mutate(),style:ca.btnPrimary,disabled:F===0||!g.trim()||b.isPending,children:b.isPending?"Publishing...":`Publish ${F} Dishes`})]}),b.isError&&s.jsx("p",{style:{color:"#dc2626",marginTop:"0.5rem",fontSize:"0.875rem"},children:b.error.message})]})]})]})})}const ca={overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"90%",maxHeight:"90vh",overflow:"auto"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.75rem"},input:{width:"100%",padding:"0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",boxSizing:"border-box"},inputSm:{padding:"0.25rem 0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.8rem"},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"},flagBadge:{padding:"1px 6px",background:"#f3f4f6",borderRadius:"4px",fontSize:"0.7rem",color:"#374151"}};function rpe({menuId:n,menuName:e,onClose:t}){const{token:r}=gn(),{data:i,isLoading:o}=Oe({queryKey:["menu-flag-matrix",n],queryFn:async()=>{const l=await fetch(`/api/menus/${n}/flags`,{headers:{Authorization:`Bearer ${r}`}});if(!l.ok)throw new Error("Failed");return l.json()},enabled:!!r});if(o)return s.jsx("div",{style:hl.overlay,onClick:t,children:s.jsx("div",{style:hl.modal,onClick:l=>l.stopPropagation(),children:"Loading..."})});if(!i)return null;const a=new Map;for(const l of i.all_flags)a.has(l.category_name)||a.set(l.category_name,[]),a.get(l.category_name).push(l);for(const[l,d]of a);return s.jsx("div",{style:hl.overlay,onClick:t,children:s.jsxs("div",{style:hl.modal,onClick:l=>l.stopPropagation(),children:[s.jsxs("div",{style:hl.printHeader,children:[s.jsxs("h3",{style:{margin:0},children:[e," — Allergen Matrix"]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},className:"no-print",children:[s.jsx("button",{onClick:()=>window.print(),style:hl.btnPrimary,children:"Print"}),s.jsx("button",{onClick:t,style:hl.btn,children:"Close"})]})]}),i.divisions.length===0&&s.jsx("p",{style:{color:"#666"},children:"No items on this menu."}),i.divisions.length>0&&s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:hl.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{...hl.th,minWidth:"180px"},children:"Dish"}),i.all_flags.map(l=>s.jsx("th",{style:{...hl.th,writingMode:"vertical-lr",textAlign:"center",fontSize:"0.7rem",padding:"4px 2px",maxWidth:"30px"},children:l.code||l.name},l.id))]})}),s.jsx("tbody",{children:i.divisions.map(l=>s.jsxs(s.Fragment,{children:[s.jsx("tr",{children:s.jsx("td",{colSpan:i.all_flags.length+1,style:hl.sectionRow,children:l.name})},`div-${l.name}`),l.items.map(d=>s.jsxs("tr",{children:[s.jsx("td",{style:hl.td,children:d.display_name}),i.all_flags.map(c=>s.jsx("td",{style:{...hl.td,textAlign:"center",background:d.flags[String(c.id)]?"#fee2e2":"transparent",color:d.flags[String(c.id)]?"#dc2626":"#ccc",fontWeight:d.flags[String(c.id)]?700:400},children:d.flags[String(c.id)]?"Y":"-"},c.id))]},d.id))]}))})]})}),s.jsx("style",{children:` - @media print { - .no-print { display: none !important; } - body > * { display: none !important; } - body > div:last-child { display: block !important; } - } - `})]})})}const hl={overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"95%",maxWidth:"1000px",maxHeight:"90vh",overflow:"auto"},printHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},table:{width:"100%",borderCollapse:"collapse",fontSize:"0.85rem"},th:{padding:"0.4rem",borderBottom:"2px solid #e5e7eb",fontWeight:600,textAlign:"left",fontSize:"0.8rem"},td:{padding:"0.35rem 0.4rem",borderBottom:"1px solid #f3f4f6",fontSize:"0.8rem"},sectionRow:{padding:"0.5rem",fontWeight:700,background:"#f9fafb",fontSize:"0.85rem",borderBottom:"1px solid #e5e7eb"},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"}};function ipe(){var on;const{id:n}=G_(),e=parseInt(n||"0"),{token:t,user:r}=gn(),i=go(),o=pi(),[a,l]=k.useState(!1),[d,c]=k.useState(""),[u,f]=k.useState(!1),[p,g]=k.useState(""),[m,y]=k.useState(!1),[v,x]=k.useState(""),[w,S]=k.useState(!1),[_,b]=k.useState(""),[C,T]=k.useState(null),[F,A]=k.useState(""),[D,P]=k.useState(!1),[L,W]=k.useState(null),[O,U]=k.useState(null),[M,I]=k.useState(null),[H,z]=k.useState(null),[G,te]=k.useState(null),[re,me]=k.useState(null),[J,ne]=k.useState(""),[ye,ke]=k.useState(""),[Ye,De]=k.useState(""),[qe,ue]=k.useState(null),[Ze,ee]=k.useState(null),[Z,ge]=k.useState(null),[Te,Be]=k.useState(!1),[he,He]=k.useState(!1),[Ge,ae]=k.useState(""),[K,de]=k.useState(new Set),{data:Y,isLoading:Q}=Oe({queryKey:["menu",e],queryFn:async()=>{const Ke=await fetch(`/api/menus/${e}`,{headers:{Authorization:`Bearer ${t}`}});if(!Ke.ok)throw new Error("Failed to fetch menu");return Ke.json()},enabled:!!t&&e>0,staleTime:0}),X=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Ke)})).ok)throw new Error("Failed to update")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),pe=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/divisions`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:Ke})})).ok)throw new Error("Failed to add division")},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),S(!1),b("")}}),we=Ue({mutationFn:async({divId:Ke,name:Rt})=>{if(!(await fetch(`/api/menus/${e}/divisions/${Ke}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({name:Rt})})).ok)throw new Error("Failed to rename")},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),T(null)}}),Ne=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/divisions/${Ke}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),st=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/divisions/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ids:Ke})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),Ve=Ue({mutationFn:async({itemId:Ke,data:Rt})=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}`,{method:"PUT",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Rt)})).ok)throw new Error("Failed to update")},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),me(null)}}),Re=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to remove")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),Le=Ue({mutationFn:async({itemId:Ke,confirmed_by_name:Rt})=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}/republish`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({confirmed_by_name:Rt})})).ok)throw new Error("Failed to republish")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),rt=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/items/reorder`,{method:"PATCH",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({ids:Ke})})).ok)throw new Error("Failed to reorder")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),$e=Ue({mutationFn:async Ke=>{const Rt=await fetch(`/api/menus/${e}/republish-stale`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(Ke)});if(!Rt.ok)throw new Error("Failed to batch republish");return Rt.json()},onSuccess:()=>{o.invalidateQueries({queryKey:["menu",e]}),He(!1)}}),ce=Ue({mutationFn:async({itemId:Ke,file:Rt})=>{const vt=new FormData;if(vt.append("file",Rt),!(await fetch(`/api/menus/${e}/items/${Ke}/image`,{method:"POST",headers:{Authorization:`Bearer ${t}`},body:vt})).ok)throw new Error("Failed to upload image")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})}),Je=Ue({mutationFn:async Ke=>{if(!(await fetch(`/api/menus/${e}/items/${Ke}/image`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})).ok)throw new Error("Failed to delete image")},onSuccess:()=>o.invalidateQueries({queryKey:["menu",e]})});if(Q)return s.jsx("div",{style:{padding:"2rem"},children:"Loading..."});if(!Y)return s.jsx("div",{style:{padding:"2rem"},children:"Menu not found"});const jt=Y.divisions.flatMap(Ke=>Ke.items),ct=jt.filter(Ke=>Ke.is_stale).length,Se=jt.filter(Ke=>Ke.is_archived).length,ot=()=>{if(L===null||O===null)return;const Ke=[...Y.divisions],[Rt]=Ke.splice(L,1);Ke.splice(O,0,Rt),st.mutate(Ke.map(vt=>vt.id)),W(null),U(null)},ut=Ke=>{if(H===null||G===null)return;const Rt=[...Ke],[vt]=Rt.splice(H,1);Rt.splice(G,0,vt),rt.mutate(Rt.map(Cr=>Cr.id)),z(null),te(null)},Ot=Ke=>{const Rt=new Set(K);Rt.has(Ke)?Rt.delete(Ke):Rt.add(Ke),de(Rt)},An=jt.filter(Ke=>Ke.is_stale&&!Ke.is_archived);return s.jsxs("div",{style:qt.container,children:[s.jsx("button",{onClick:()=>i("/menus"),style:qt.backBtn,children:"← Menus"}),s.jsxs("div",{style:qt.menuHeader,children:[s.jsxs("div",{style:{flex:1},children:[a?s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{value:d,onChange:Ke=>c(Ke.target.value),style:qt.input,autoFocus:!0}),s.jsx("button",{onClick:()=>{X.mutate({name:d}),l(!1)},style:qt.btnPrimary,children:"Save"}),s.jsx("button",{onClick:()=>l(!1),style:qt.btn,children:"Cancel"})]}):s.jsx("h2",{style:{margin:0,cursor:"pointer"},onClick:()=>{c(Y.name),l(!0)},children:Y.name}),u?s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("input",{value:p,onChange:Ke=>g(Ke.target.value),style:qt.input,placeholder:"Customer-facing description"}),s.jsx("button",{onClick:()=>{X.mutate({description:p}),f(!1)},style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>f(!1),style:qt.btnSmall,children:"Cancel"})]}):s.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.875rem",color:"#666",cursor:"pointer"},onClick:()=>{g(Y.description||""),f(!0)},children:Y.description||"Click to add description..."}),m?s.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:"0.25rem"},children:[s.jsx("input",{value:v,onChange:Ke=>x(Ke.target.value),style:qt.input,placeholder:"Internal notes"}),s.jsx("button",{onClick:()=>{X.mutate({notes:v}),y(!1)},style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>y(!1),style:qt.btnSmall,children:"Cancel"})]}):s.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8rem",color:"#999",cursor:"pointer",fontStyle:"italic"},onClick:()=>{x(Y.notes||""),y(!0)},children:Y.notes?`Notes: ${Y.notes}`:"Click to add internal notes..."})]}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"flex-start",flexWrap:"wrap"},children:[s.jsx("button",{onClick:()=>X.mutate({is_active:!Y.is_active}),style:{...qt.btn,background:Y.is_active?"#dcfce7":"#f3f4f6",color:Y.is_active?"#166534":"#6b7280",border:"none"},children:Y.is_active?"Active":"Inactive"}),ct>0&&s.jsxs("button",{onClick:()=>{ae((r==null?void 0:r.name)||""),He(!0)},style:{...qt.btn,background:"#fef3c7",color:"#92400e",border:"none"},children:["Republish All Stale (",ct,")"]}),s.jsx("button",{onClick:()=>Be(!0),style:qt.btn,children:"Print Flag Matrix"})]})]}),ct>0&&s.jsxs("div",{style:{...qt.notifBar,background:"#fef3c7",borderColor:"#f59e0b"},children:[ct," item",ct!==1?"s":""," need",ct===1?"s":""," republishing"]}),Se>0&&s.jsxs("div",{style:{...qt.notifBar,background:"#fee2e2",borderColor:"#ef4444"},children:[Se," dish",Se!==1?"es have":" has"," been archived and should be removed"]}),s.jsxs("div",{style:qt.divHeader,children:[s.jsx("h3",{style:{margin:0},children:"Sections"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[Y.divisions.length>1&&s.jsx("button",{onClick:()=>P(!D),style:{...qt.btn,background:D?"#3b82f6":void 0,color:D?"#fff":void 0},children:D?"Done":"Sort"}),s.jsx("button",{onClick:()=>S(!0),style:qt.btnPrimary,children:"+ Add Section"})]})]}),w&&s.jsxs("div",{style:qt.inlineForm,children:[s.jsx("input",{value:_,onChange:Ke=>b(Ke.target.value),style:qt.input,placeholder:"Section name",autoFocus:!0}),s.jsx("button",{onClick:()=>{_.trim()&&pe.mutate(_.trim())},style:qt.btnPrimary,disabled:!_.trim(),children:"Add"}),s.jsx("button",{onClick:()=>{S(!1),b("")},style:qt.btn,children:"Cancel"})]}),Y.divisions.length===0&&s.jsx("p",{style:{color:"#666",padding:"1rem"},children:"No sections yet. Add a section to start publishing dishes."}),Y.divisions.map((Ke,Rt)=>s.jsxs("div",{style:{...qt.divisionCard,opacity:D&&L===Rt?.4:1,background:D&&O===Rt?"#e0f2fe":"#fff"},draggable:D,onDragStart:()=>W(Rt),onDragOver:vt=>{D&&(vt.preventDefault(),U(Rt))},onDrop:()=>{D&&ot()},onDragEnd:()=>{W(null),U(null)},children:[s.jsxs("div",{style:qt.divisionHeader,onClick:()=>Ot(Ke.id),children:[D&&s.jsx("span",{style:qt.dragHandle,children:"☰"}),s.jsx("span",{style:{cursor:"pointer",userSelect:"none"},children:K.has(Ke.id)?"▶":"▼"}),C===Ke.id?s.jsxs("div",{style:{display:"flex",gap:"0.5rem",flex:1},onClick:vt=>vt.stopPropagation(),children:[s.jsx("input",{value:F,onChange:vt=>A(vt.target.value),style:qt.input,autoFocus:!0}),s.jsx("button",{onClick:()=>we.mutate({divId:Ke.id,name:F}),style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>T(null),style:qt.btnSmall,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{fontWeight:600,flex:1},children:Ke.name}),s.jsxs("span",{style:{fontSize:"0.8rem",color:"#999"},children:[Ke.items.length," item",Ke.items.length!==1?"s":""]})]}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem"},onClick:vt=>vt.stopPropagation(),children:[s.jsx("button",{onClick:()=>{T(Ke.id),A(Ke.name)},style:qt.btnTiny,children:"Rename"}),s.jsx("button",{onClick:()=>ee(Ke.id),style:{...qt.btnTiny,background:"#eff6ff",color:"#2563eb"},children:"+ Dish"}),s.jsx("button",{onClick:()=>ge(Ke.id),style:{...qt.btnTiny,background:"#f0fdf4",color:"#166534"},children:"+ Bulk"}),s.jsx("button",{onClick:()=>{const vt=Ke.items.length>0?`Delete "${Ke.name}" and its ${Ke.items.length} item(s)?`:`Delete "${Ke.name}"?`;confirm(vt)&&Ne.mutate(Ke.id)},style:{...qt.btnTiny,color:"#dc2626"},children:"Delete"})]})]}),!K.has(Ke.id)&&s.jsxs("div",{style:qt.itemsList,children:[Ke.items.length>1&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",padding:"0.25rem 0"},children:s.jsx("button",{onClick:()=>I(M===Ke.id?null:Ke.id),style:{...qt.btnTiny,background:M===Ke.id?"#3b82f6":void 0,color:M===Ke.id?"#fff":void 0},children:M===Ke.id?"Done":"Sort"})}),Ke.items.map((vt,Cr)=>s.jsxs("div",{style:{...qt.itemRow,opacity:vt.is_archived?.5:M===Ke.id&&H===Cr?.4:1,background:M===Ke.id&&G===Cr?"#e0f2fe":vt.is_archived?"#f9fafb":"transparent"},draggable:M===Ke.id,onDragStart:()=>z(Cr),onDragOver:Qt=>{M===Ke.id&&(Qt.preventDefault(),te(Cr))},onDrop:()=>{M===Ke.id&&ut(Ke.items)},onDragEnd:()=>{z(null),te(null)},children:[M===Ke.id&&s.jsx("span",{style:qt.dragHandle,children:"☰"}),vt.has_image?s.jsx("img",{src:`/api/menus/${e}/items/${vt.id}/image?token=${t}`,alt:"",style:qt.thumbnail}):s.jsx("div",{style:qt.thumbnailPlaceholder,children:s.jsxs("label",{style:{cursor:"pointer",fontSize:"0.7rem",color:"#999"},children:["+ img",s.jsx("input",{type:"file",accept:"image/*",style:{display:"none"},onChange:Qt=>{var Lr;const Ci=(Lr=Qt.target.files)==null?void 0:Lr[0];Ci&&ce.mutate({itemId:vt.id,file:Ci})}})]})}),s.jsx("div",{style:{flex:1,minWidth:0},children:re===vt.id?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},onClick:Qt=>Qt.stopPropagation(),children:[s.jsx("input",{value:J,onChange:Qt=>ne(Qt.target.value),style:qt.inputSm,placeholder:"Display name"}),s.jsx("input",{value:ye,onChange:Qt=>ke(Qt.target.value),style:qt.inputSm,placeholder:"Description"}),s.jsxs("div",{style:{display:"flex",gap:"0.25rem",alignItems:"center"},children:[s.jsx("input",{value:Ye,onChange:Qt=>De(Qt.target.value),style:{...qt.inputSm,width:"80px"},placeholder:"Price"}),s.jsx("select",{value:qe||"",onChange:Qt=>ue(parseInt(Qt.target.value)),style:qt.inputSm,children:Y.divisions.map(Qt=>s.jsx("option",{value:Qt.id,children:Qt.name},Qt.id))}),s.jsx("button",{onClick:()=>{const Qt={};J&&(Qt.display_name=J),ye!==void 0&&(Qt.description=ye),Ye&&(Qt.price=parseFloat(Ye)),qe&&qe!==Ke.id&&(Qt.division_id=qe),Ve.mutate({itemId:vt.id,data:Qt})},style:qt.btnSmall,children:"Save"}),s.jsx("button",{onClick:()=>me(null),style:qt.btnSmall,children:"Cancel"})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[s.jsx("span",{style:{fontWeight:500},children:vt.display_name}),vt.price&&s.jsxs("span",{style:{color:"#666",fontSize:"0.875rem"},children:["£",vt.price]}),vt.is_archived&&s.jsx("span",{style:{...qt.badgeSm,background:"#fee2e2",color:"#dc2626"},children:"Archived"}),vt.is_stale&&s.jsx("span",{style:{...qt.badgeSm,background:"#fef3c7",color:"#92400e"},title:vt.stale_reason||"",children:"Needs Republishing"})]}),vt.description&&s.jsx("p",{style:{margin:"0.125rem 0 0",fontSize:"0.8rem",color:"#666"},children:vt.description}),vt.snapshot_json&&vt.snapshot_json.confirmed_flags&&s.jsx("div",{style:{display:"flex",gap:"0.25rem",marginTop:"0.25rem",flexWrap:"wrap"},children:vt.snapshot_json.confirmed_flags.map((Qt,Ci)=>s.jsx("span",{style:{...qt.flagBadge},children:Qt.code||Qt.name},Ci))})]})}),re!==vt.id&&s.jsxs("div",{style:{display:"flex",gap:"0.25rem",flexShrink:0},children:[s.jsx("button",{onClick:()=>{me(vt.id),ne(vt.display_name),ke(vt.description||""),De(vt.price||""),ue(Ke.id)},style:qt.btnTiny,children:"Edit"}),vt.is_stale&&!vt.is_archived&&s.jsx("button",{onClick:()=>{const Qt=prompt("Confirmed by:",(r==null?void 0:r.name)||"");Qt&&Le.mutate({itemId:vt.id,confirmed_by_name:Qt})},style:{...qt.btnTiny,background:"#fef3c7",color:"#92400e"},children:"Republish"}),vt.has_image&&s.jsx("button",{onClick:()=>{confirm("Remove image?")&&Je.mutate(vt.id)},style:{...qt.btnTiny,color:"#dc2626"},children:"- img"}),!vt.has_image&&s.jsxs("label",{style:{...qt.btnTiny,background:"#f0fdf4",color:"#166534",cursor:"pointer",display:"inline-flex",alignItems:"center"},children:["+ img",s.jsx("input",{type:"file",accept:"image/*",style:{display:"none"},onChange:Qt=>{var Lr;const Ci=(Lr=Qt.target.files)==null?void 0:Lr[0];Ci&&ce.mutate({itemId:vt.id,file:Ci})}})]}),s.jsx("button",{onClick:()=>{confirm(`Remove "${vt.display_name}" from menu?`)&&Re.mutate(vt.id)},style:{...qt.btnTiny,color:"#dc2626"},children:"Remove"})]})]},vt.id)),Ke.items.length===0&&s.jsxs("p",{style:{color:"#999",fontSize:"0.875rem",padding:"0.5rem 0"},children:["No dishes in this section."," ",s.jsx("button",{onClick:()=>ee(Ke.id),style:{...qt.btnTiny,background:"#eff6ff",color:"#2563eb"},children:"+ Add Dish"})]})]})]},Ke.id)),Ze!==null&&s.jsx(UK,{menuId:e,menuName:Y.name,divisions:Y.divisions,preSelectedDivisionId:Ze,onClose:()=>ee(null),onPublished:()=>{o.invalidateQueries({queryKey:["menu",e]}),ee(null)}}),Z!==null&&s.jsx(npe,{menuId:e,divisionId:Z,divisionName:((on=Y.divisions.find(Ke=>Ke.id===Z))==null?void 0:on.name)||"",onClose:()=>ge(null),onPublished:()=>{o.invalidateQueries({queryKey:["menu",e]}),ge(null)}}),Te&&s.jsx(rpe,{menuId:e,menuName:Y.name,onClose:()=>Be(!1)}),he&&s.jsx("div",{style:qt.overlay,onClick:()=>He(!1),children:s.jsxs("div",{style:{...qt.modal,maxWidth:"600px"},onClick:Ke=>Ke.stopPropagation(),children:[s.jsx("h3",{style:{margin:"0 0 1rem"},children:"Batch Republish Stale Items"}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"#666",marginBottom:"1rem"},children:[An.length," item",An.length!==1?"s":""," will be republished with updated allergen information."]}),s.jsx("div",{style:{maxHeight:"300px",overflow:"auto",marginBottom:"1rem"},children:An.map(Ke=>{const Rt=Ke.snapshot_json?Ke.snapshot_json.confirmed_flags||[]:[];return s.jsxs("div",{style:{padding:"0.5rem",borderBottom:"1px solid #eee"},children:[s.jsx("span",{style:{fontWeight:500},children:Ke.display_name}),Ke.stale_reason&&s.jsxs("span",{style:{fontSize:"0.75rem",color:"#92400e",marginLeft:"0.5rem"},children:["(",Ke.stale_reason,")"]}),s.jsx("div",{style:{display:"flex",gap:"0.25rem",marginTop:"0.25rem",flexWrap:"wrap"},children:Rt.map((vt,Cr)=>s.jsx("span",{style:qt.flagBadge,children:vt.code||vt.name},Cr))})]},Ke.id)})}),s.jsx("label",{style:qt.label,children:"Confirmed by *"}),s.jsx("input",{value:Ge,onChange:Ke=>ae(Ke.target.value),style:qt.input}),s.jsxs("div",{style:qt.modalActions,children:[s.jsx("button",{onClick:()=>He(!1),style:qt.btn,children:"Cancel"}),s.jsx("button",{onClick:()=>$e.mutate({confirmed_by_name:Ge,items:An.map(Ke=>({id:Ke.id,confirmed:!0}))}),style:qt.btnPrimary,disabled:!Ge.trim()||$e.isPending,children:$e.isPending?"Republishing...":`Republish ${An.length} Items`})]})]})})]})}const qt={container:{maxWidth:"1000px",margin:"0 auto",padding:"1rem"},backBtn:{background:"none",border:"none",color:"#2563eb",cursor:"pointer",fontSize:"0.875rem",padding:"0.25rem 0",marginBottom:"0.5rem"},menuHeader:{display:"flex",justifyContent:"space-between",gap:"1rem",marginBottom:"1rem",flexWrap:"wrap"},notifBar:{padding:"0.5rem 1rem",borderRadius:"6px",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.5rem",borderLeft:"4px solid"},divHeader:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.5rem",marginTop:"1rem"},divisionCard:{border:"1px solid #e5e7eb",borderRadius:"8px",marginBottom:"0.5rem",overflow:"hidden"},divisionHeader:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.75rem 1rem",background:"#f9fafb",cursor:"pointer",borderBottom:"1px solid #e5e7eb"},dragHandle:{cursor:"grab",fontSize:"1rem",color:"#999"},itemsList:{padding:"0.5rem 1rem"},itemRow:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0",borderBottom:"1px solid #f3f4f6"},thumbnail:{width:"48px",height:"48px",objectFit:"cover",borderRadius:"4px",flexShrink:0},thumbnailPlaceholder:{width:"48px",height:"48px",border:"1px dashed #ddd",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},flagBadge:{padding:"1px 6px",background:"#f3f4f6",borderRadius:"4px",fontSize:"0.7rem",color:"#374151"},badgeSm:{padding:"1px 6px",borderRadius:"10px",fontSize:"0.7rem",fontWeight:500},btn:{padding:"0.4rem 0.75rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnPrimary:{padding:"0.4rem 0.75rem",border:"none",borderRadius:"4px",background:"#2563eb",color:"#fff",cursor:"pointer",fontSize:"0.8rem"},btnSmall:{padding:"0.25rem 0.5rem",border:"1px solid #ddd",borderRadius:"4px",background:"#fff",cursor:"pointer",fontSize:"0.75rem"},btnTiny:{padding:"2px 6px",border:"1px solid #e5e7eb",borderRadius:"3px",background:"#fff",cursor:"pointer",fontSize:"0.7rem"},inlineForm:{display:"flex",gap:"0.5rem",marginBottom:"0.75rem",alignItems:"center"},input:{padding:"0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.875rem",flex:1},inputSm:{padding:"0.25rem 0.4rem",border:"1px solid #ddd",borderRadius:"4px",fontSize:"0.8rem"},overlay:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},modal:{background:"#fff",borderRadius:"8px",padding:"1.5rem",width:"90%",maxWidth:"500px"},modalActions:{display:"flex",justifyContent:"flex-end",gap:"0.5rem",marginTop:"1rem"},label:{display:"block",fontSize:"0.875rem",fontWeight:500,marginBottom:"0.25rem",marginTop:"0.5rem"}};function spe(){const{token:n}=gn(),e=pi(),[t,r]=k.useState(""),[i,o]=k.useState(""),[a,l]=k.useState(!1),[d,c]=k.useState(null),{data:u}=Oe({queryKey:["ingredients-bulk"],queryFn:async()=>{const b=await fetch("/api/ingredients?limit=9999",{headers:{Authorization:`Bearer ${n}`}});if(!b.ok)throw new Error("Failed to fetch ingredients");return b.json()},enabled:!!n}),{data:f}=Oe({queryKey:["ingredient-categories"],queryFn:async()=>{const b=await fetch("/api/ingredients/categories",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():[]},enabled:!!n}),{data:p}=Oe({queryKey:["food-flag-categories-full"],queryFn:async()=>{const b=await fetch("/api/food-flags/categories",{headers:{Authorization:`Bearer ${n}`}});if(!b.ok)throw new Error("Failed to fetch flag categories");return b.json()},enabled:!!n}),{data:g}=Oe({queryKey:["bulk-nones"],queryFn:async()=>{const b=await fetch("/api/ingredients/bulk-nones",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():{}},enabled:!!n}),{data:m}=Oe({queryKey:["bulk-suggestions"],queryFn:async()=>{const b=await fetch("/api/food-flags/suggest/bulk",{headers:{Authorization:`Bearer ${n}`}});return b.ok?b.json():{}},enabled:!!n}),y=Ue({mutationFn:async({ingredientId:b,flagId:C,action:T})=>{const F=u==null?void 0:u.find(L=>L.id===b),A=(F==null?void 0:F.flags.map(L=>L.food_flag_id))||[];let D;if(T==="add"?D=[...A,C]:D=A.filter(L=>L!==C),!(await fetch(`/api/ingredients/${b}/flags`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({food_flag_ids:D})})).ok)throw new Error("Failed to update flags")},onSuccess:()=>{e.invalidateQueries({queryKey:["ingredients-bulk"]}),e.invalidateQueries({queryKey:["bulk-nones"]})}}),v=Ue({mutationFn:async({ingredientId:b,categoryId:C})=>{if(!(await fetch(`/api/ingredients/${b}/flags/none`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({category_id:C})})).ok)throw new Error("Failed to toggle none")},onSuccess:()=>{e.invalidateQueries({queryKey:["ingredients-bulk"]}),e.invalidateQueries({queryKey:["bulk-nones"]})}}),x=b=>{c(d===b.id?null:b.id)},w=(p==null?void 0:p.filter(b=>b.required))||[],S=[];for(const b of w)for(const C of b.flags)S.push({flagId:C.id,flagName:C.name,flagCode:C.code,categoryId:b.id,categoryName:b.name,propagation:b.propagation_type});const _=(u||[]).filter(b=>{if(t&&!b.name.toLowerCase().includes(t.toLowerCase())||i&&b.category_id!==parseInt(i))return!1;if(a){const C=(g==null?void 0:g[b.id])||[];for(const T of w){if(C.includes(T.id))continue;if(!b.flags.some(A=>T.flags.some(D=>D.id===A.food_flag_id)))return!0}return!1}return!0});return s.jsxs("div",{style:fl.page,children:[s.jsx("h2",{style:{margin:"0 0 0.75rem 0"},children:"Bulk Allergen Assessment"}),s.jsxs("div",{style:fl.filterBar,children:[s.jsx("input",{type:"text",placeholder:"Search ingredients...",value:t,onChange:b=>r(b.target.value),style:fl.searchInput}),s.jsxs("select",{value:i,onChange:b=>o(b.target.value),style:fl.select,children:[s.jsx("option",{value:"",children:"All Categories"}),f==null?void 0:f.map(b=>s.jsx("option",{value:b.id,children:b.name},b.id))]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"0.85rem",cursor:"pointer"},children:[s.jsx("input",{type:"checkbox",checked:a,onChange:b=>l(b.target.checked)}),"Unassessed only"]}),s.jsxs("span",{style:{fontSize:"0.85rem",color:"#666",marginLeft:"auto"},children:[_.length," ingredients"]})]}),S.length===0?s.jsx("div",{style:fl.emptyState,children:'No required flag categories found. Go to Settings > Food Flags and mark allergen categories as "Required".'}):s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:fl.table,children:[s.jsx("thead",{style:{position:"sticky",top:0,zIndex:3},children:s.jsxs("tr",{children:[s.jsx("th",{style:{...fl.th,position:"sticky",left:0,background:"#fafafa",zIndex:4,minWidth:"200px"},children:"Ingredient"}),w.map(b=>s.jsx("th",{style:{...fl.th,textAlign:"center",fontSize:"0.7rem",background:"#f0fdf4",minWidth:"50px"},title:`None apply for ${b.name}`,children:"None"},`cat-none-${b.id}`)),S.map(b=>s.jsx("th",{style:{...fl.th,textAlign:"center",minWidth:"45px",writingMode:"vertical-lr",fontSize:"0.7rem"},title:`${b.flagName} (${b.categoryName})`,children:b.flagCode||b.flagName},b.flagId))]})}),_.map(b=>{const C=new Set(b.flags.map(W=>W.food_flag_id)),T=(g==null?void 0:g[b.id])||[],F=d===b.id,A=m==null?void 0:m[b.id],D=A==null?void 0:A.filter(W=>!C.has(W.flag_id)),P=!!(D!=null&&D.length),L=1+w.length+S.length;return s.jsxs("tbody",{children:[s.jsxs("tr",{style:fl.tr,children:[s.jsxs("td",{style:{...fl.td,position:"sticky",left:0,zIndex:1,fontWeight:500,cursor:"pointer",background:F?"#f0f7ff":P?"#fffbeb":"white",borderLeft:P?"3px solid #f59e0b":void 0},onClick:()=>x(b),title:P?`${D.length} suggested allergen(s) — click to review`:"Click to show details",children:[s.jsx("span",{style:{fontSize:"0.65rem",color:"#888",marginRight:"4px"},children:F?"▼":"▶"}),b.name,b.category_name&&s.jsx("span",{style:{fontSize:"0.7rem",color:"#999",marginLeft:"6px"},children:b.category_name}),b.is_prepackaged&&s.jsx("span",{style:{fontSize:"0.6rem",color:"#6366f1",marginLeft:"6px",fontWeight:600},children:"PKG"})]}),w.map(W=>{const O=T.includes(W.id);return s.jsx("td",{style:{...fl.td,textAlign:"center",background:O?"#dcfce7":void 0},children:s.jsx("input",{type:"checkbox",checked:O,onChange:()=>v.mutate({ingredientId:b.id,categoryId:W.id}),disabled:v.isPending,style:{cursor:"pointer"},title:`None apply for ${W.name}`})},`none-${W.id}`)}),S.map(W=>{const O=C.has(W.flagId),U=T.includes(W.categoryId),M=D==null?void 0:D.some(I=>I.flag_id===W.flagId);return s.jsx("td",{style:{...fl.td,textAlign:"center",background:O?W.propagation==="contains"?"#fef2f2":"#dcfce7":M?"#fffbeb":U?"#f8f8f8":void 0,opacity:U?.4:1},children:s.jsx("input",{type:"checkbox",checked:O,onChange:()=>y.mutate({ingredientId:b.id,flagId:W.flagId,action:O?"remove":"add"}),disabled:U||y.isPending,style:{cursor:U?"not-allowed":"pointer"},title:W.flagName+(M?" (suggested)":"")})},W.flagId)})]}),F&&s.jsx("tr",{children:s.jsx("td",{colSpan:L,style:{padding:"0.5rem 0.75rem",background:"#f8fafc",borderBottom:"2px solid #e0e0e0"},children:s.jsxs("div",{style:{display:"flex",gap:"1.5rem",fontSize:"0.8rem"},children:[s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontWeight:600,color:"#555",marginBottom:"0.25rem",fontSize:"0.7rem",textTransform:"uppercase"},children:"Notes"}),s.jsx("div",{style:{color:b.notes?"#333":"#bbb",whiteSpace:"pre-wrap"},children:b.notes||"No notes"})]}),s.jsxs("div",{style:{flex:2},children:[s.jsxs("div",{style:{fontWeight:600,color:"#555",marginBottom:"0.25rem",fontSize:"0.7rem",textTransform:"uppercase"},children:["Label Ingredients ",b.is_prepackaged&&s.jsx("span",{style:{color:"#6366f1"},children:"(prepackaged)"})]}),s.jsx("div",{style:{color:b.product_ingredients?"#333":"#bbb",whiteSpace:"pre-wrap",maxHeight:"80px",overflow:"auto"},children:b.product_ingredients||"Not available"})]}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontWeight:600,color:"#555",marginBottom:"0.25rem",fontSize:"0.7rem",textTransform:"uppercase"},children:"Keyword Suggestions"}),D!=null&&D.length?s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.2rem"},children:D.map(W=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0.15rem 0.3rem",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:"4px"},children:[s.jsxs("span",{children:[s.jsx("strong",{style:{fontSize:"0.75rem"},children:W.flag_name}),s.jsx("span",{style:{color:"#999",fontSize:"0.65rem",marginLeft:"0.25rem"},children:W.matched_keywords.join(", ")})]}),s.jsx("button",{onClick:()=>{w.find(U=>U.flags.some(M=>M.id===W.flag_id))&&y.mutate({ingredientId:b.id,flagId:W.flag_id,action:"add"})},disabled:y.isPending,style:{background:"#f59e0b",color:"white",border:"none",borderRadius:"3px",padding:"0.1rem 0.3rem",fontSize:"0.65rem",fontWeight:600,cursor:"pointer"},children:"Apply"})]},W.flag_id))}):s.jsx("div",{style:{color:"#bbb"},children:"No suggestions"})]})]})})})]},b.id)})]})})]})}const fl={page:{padding:"1.5rem",maxWidth:"1600px",margin:"0 auto"},filterBar:{display:"flex",gap:"0.75rem",alignItems:"center",marginBottom:"1rem",flexWrap:"wrap"},searchInput:{padding:"0.5rem 0.75rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem",width:"250px"},select:{padding:"0.5rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.9rem"},emptyState:{padding:"3rem",textAlign:"center",color:"#888",background:"#fafafa",borderRadius:"8px"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.5rem 0.4rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.75rem",fontWeight:600,color:"#555"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.35rem 0.4rem",fontSize:"0.85rem"}};function ZP(n,e){return e==="g"&&n<1?`£${(n*1e3).toFixed(2)}/kg`:e==="ml"&&n<1?`£${(n*1e3).toFixed(2)}/ltr`:`£${n.toFixed(4)}/${e||"?"}`}function ope(){const{token:n}=gn(),e=go(),[t,r]=k.useState(14),[i,o]=k.useState(null),[a,l]=k.useState("all"),{data:d,isLoading:c}=Oe({queryKey:["price-impact",t],queryFn:async()=>{const g=await fetch(`/api/recipes/price-impact?days=${t}`,{headers:{Authorization:`Bearer ${n}`}});if(!g.ok)throw new Error("Failed to fetch price impact");return g.json()},enabled:!!n}),u=(d==null?void 0:d.recipes.filter(g=>a==="all"||g.recipe_type===a))||[],f=(d==null?void 0:d.recipes.filter(g=>g.recipe_type==="dish").length)||0,p=(d==null?void 0:d.recipes.filter(g=>g.recipe_type==="component").length)||0;return s.jsxs("div",{style:gs.page,children:[s.jsxs("div",{style:gs.header,children:[s.jsx("h2",{style:{margin:0},children:"Price Impact Report"}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("label",{style:{fontSize:"0.85rem",color:"#666"},children:"Period:"}),s.jsxs("select",{value:t,onChange:g=>r(Number(g.target.value)),style:gs.select,children:[s.jsx("option",{value:7,children:"7 days"}),s.jsx("option",{value:14,children:"14 days"}),s.jsx("option",{value:30,children:"30 days"}),s.jsx("option",{value:60,children:"60 days"}),s.jsx("option",{value:90,children:"90 days"})]})]})]}),c&&s.jsx("div",{style:{padding:"2rem",color:"#888"},children:"Loading..."}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:gs.statsBar,children:[s.jsxs("span",{children:[d.recipes.length," recipes affected"]}),s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{children:[f," dishes"]}),s.jsx("span",{style:{color:"#888"},children:"|"}),s.jsxs("span",{children:[p," components"]}),s.jsx("div",{style:{marginLeft:"auto",display:"flex",gap:"0.25rem"},children:["all","dish","component"].map(g=>s.jsx("button",{onClick:()=>l(g),style:{...gs.filterBtn,...a===g?gs.filterBtnActive:{}},children:g==="all"?"All":g==="dish"?"Dishes":"Recipes"},g))})]}),u.length===0?s.jsxs("div",{style:{padding:"2rem",textAlign:"center",color:"#888"},children:["No recipes affected by ingredient price changes in the last ",t," days."]}):s.jsxs("table",{style:gs.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:gs.th,children:"Recipe"}),s.jsx("th",{style:gs.th,children:"Type"}),s.jsx("th",{style:{...gs.th,textAlign:"right"},children:"Previous Cost"}),s.jsx("th",{style:{...gs.th,textAlign:"right"},children:"Current Cost"}),s.jsx("th",{style:{...gs.th,textAlign:"right"},children:"Change"}),s.jsx("th",{style:{...gs.th,textAlign:"center"},children:"Details"})]})}),s.jsx("tbody",{children:u.map(g=>s.jsxs(s.Fragment,{children:[s.jsxs("tr",{style:gs.tr,children:[s.jsx("td",{style:{...gs.td,fontWeight:500},children:s.jsx("span",{style:{cursor:"pointer",color:"#e94560"},onClick:()=>e(g.recipe_type==="dish"?`/dishes/${g.recipe_id}`:`/recipes/${g.recipe_id}`),children:g.recipe_name})}),s.jsx("td",{style:gs.td,children:s.jsx("span",{style:{background:g.recipe_type==="dish"?"#e94560":"#3b82f6",color:"white",padding:"1px 6px",borderRadius:"4px",fontSize:"0.7rem",fontWeight:600},children:g.recipe_type.toUpperCase()})}),s.jsx("td",{style:{...gs.td,textAlign:"right",fontFamily:"monospace"},children:g.previous_cost_per_unit!=null?`£${g.previous_cost_per_unit.toFixed(4)}/${g.output_unit}`:"-"}),s.jsx("td",{style:{...gs.td,textAlign:"right",fontFamily:"monospace"},children:g.current_cost_per_unit!=null?`£${g.current_cost_per_unit.toFixed(4)}/${g.output_unit}`:"-"}),s.jsx("td",{style:{...gs.td,textAlign:"right",fontFamily:"monospace",fontWeight:600,color:g.cost_change!=null?g.cost_change>0?"#dc3545":g.cost_change<0?"#22c55e":"#888":"#888"},children:g.cost_change!=null?s.jsxs(s.Fragment,{children:[g.cost_change>0?"+":"",`£${g.cost_change.toFixed(4)}`,g.cost_change_pct!=null&&s.jsxs("span",{style:{fontSize:"0.75rem",marginLeft:"4px"},children:["(",g.cost_change_pct>0?"+":"",g.cost_change_pct,"%)"]})]}):"-"}),s.jsx("td",{style:{...gs.td,textAlign:"center"},children:s.jsxs("button",{onClick:()=>o(i===g.recipe_id?null:g.recipe_id),style:gs.detailBtn,children:[g.ingredient_changes.length," change",g.ingredient_changes.length!==1?"s":"",i===g.recipe_id?" ▴":" ▾"]})})]},g.recipe_id),i===g.recipe_id&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,style:{padding:"0 0.75rem 0.75rem 2rem",background:"#fafafa"},children:s.jsx("div",{style:{fontSize:"0.8rem",color:"#555"},children:g.ingredient_changes.map((m,y)=>s.jsxs("div",{style:{padding:"3px 0",borderBottom:ye(`/invoice/${m.source_invoice_id}`),children:m.source_invoice_number||`#${m.source_invoice_id}`}),m.ingredient_name&&m.old_price!=null&&m.new_price!=null?s.jsxs(s.Fragment,{children:[m.ingredient_name," price changed: ",ZP(m.old_price,m.unit)," → ",ZP(m.new_price,m.unit)]}):m.ingredient_name&&m.new_price!=null&&m.old_price==null?s.jsxs(s.Fragment,{children:[m.ingredient_name," price set: ",ZP(m.new_price,m.unit)]}):m.summary]}),m.cost_impact!=null&&s.jsxs("span",{style:{fontFamily:"monospace",fontWeight:600,fontSize:"0.75rem",color:m.cost_impact>0?"#dc3545":m.cost_impact<0?"#22c55e":"#888",marginLeft:"1rem",whiteSpace:"nowrap"},children:[m.cost_impact>0?"+":"",`£${m.cost_impact.toFixed(4)}`,"/",g.output_unit]})]},y))})})},`${g.recipe_id}-detail`)]}))})]})]})]})}const gs={page:{padding:"1.5rem",maxWidth:"1100px",margin:"0 auto"},header:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},select:{padding:"0.4rem 0.6rem",border:"1px solid #ddd",borderRadius:"6px",fontSize:"0.85rem"},statsBar:{display:"flex",gap:"0.75rem",alignItems:"center",padding:"0.5rem 0",marginBottom:"0.5rem",fontSize:"0.85rem",color:"#555"},filterBtn:{padding:"3px 10px",border:"1px solid #ddd",borderRadius:"4px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.75rem",color:"#555"},filterBtnActive:{background:"#e94560",color:"white",borderColor:"#e94560"},table:{width:"100%",borderCollapse:"collapse",background:"white",borderRadius:"8px",overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.1)"},th:{padding:"0.6rem 0.75rem",textAlign:"left",borderBottom:"2px solid #e0e0e0",background:"#fafafa",fontSize:"0.8rem",fontWeight:600,color:"#555"},tr:{borderBottom:"1px solid #f0f0f0"},td:{padding:"0.5rem 0.75rem",fontSize:"0.85rem"},detailBtn:{padding:"2px 8px",border:"1px solid #ddd",borderRadius:"4px",background:"#f5f5f5",cursor:"pointer",fontSize:"0.75rem",color:"#555"}};function ape(){return s.jsx(iJ,{children:s.jsxs(iZ,{children:[s.jsx(Zn,{path:"/upload-app",element:s.jsx(Mce,{})}),s.jsxs(Zn,{element:s.jsx(FJ,{}),children:[s.jsx(Zn,{path:"/",element:s.jsx(Gz,{to:"/dashboard",replace:!0})}),s.jsx(Zn,{path:"/dashboard",element:s.jsx(Oce,{})}),s.jsx(Zn,{path:"/upload",element:s.jsx(Lce,{})}),s.jsx(Zn,{path:"/invoices",element:s.jsx(Nce,{})}),s.jsx(Zn,{path:"/invoice/:id",element:s.jsx(mfe,{})}),s.jsx(Zn,{path:"/disputes",element:s.jsx(bfe,{})}),s.jsx(Zn,{path:"/search/invoices",element:s.jsx(Ufe,{})}),s.jsx(Zn,{path:"/search/line-items",element:s.jsx(qfe,{})}),s.jsx(Zn,{path:"/purchase-orders",element:s.jsx(Vfe,{})}),s.jsx(Zn,{path:"/gp",element:s.jsx(Ffe,{})}),s.jsx(Zn,{path:"/purchases-report",element:s.jsx(Pfe,{})}),s.jsx(Zn,{path:"/purchases",element:s.jsx(jfe,{})}),s.jsx(Zn,{path:"/purchases/reconcile",element:s.jsx(zfe,{})}),s.jsx(Zn,{path:"/allowances-report",element:s.jsx(Ife,{})}),s.jsx(Zn,{path:"/sales-gp",element:s.jsx(Mfe,{})}),s.jsx(Zn,{path:"/usage-variance",element:s.jsx(Wfe,{})}),s.jsx(Zn,{path:"/logbook",element:s.jsx(Tse,{})}),s.jsx(Zn,{path:"/budget",element:s.jsx(Cfe,{})}),s.jsx(Zn,{path:"/event-orders",element:s.jsx(Qfe,{})}),s.jsx(Zn,{path:"/event-orders/:id",element:s.jsx($fe,{})}),s.jsx(Zn,{path:"/resos",element:s.jsx(zJ,{})}),s.jsx(Zn,{path:"/resos-stats",element:s.jsx(_se,{})}),s.jsx(Zn,{path:"/residents-table-chart",element:s.jsx(OJ,{})}),s.jsx(Zn,{path:"/newbook",element:s.jsx(BJ,{})}),s.jsx(Zn,{path:"/ingredients",element:s.jsx(Gfe,{})}),s.jsx(Zn,{path:"/recipes",element:s.jsx(Kfe,{})}),s.jsx(Zn,{path:"/recipes/:id",element:s.jsx(Yfe,{})}),s.jsx(Zn,{path:"/dishes",element:s.jsx(Zfe,{})}),s.jsx(Zn,{path:"/dishes/:id",element:s.jsx(epe,{})}),s.jsx(Zn,{path:"/menus",element:s.jsx(tpe,{})}),s.jsx(Zn,{path:"/menus/:id",element:s.jsx(ipe,{})}),s.jsx(Zn,{path:"/allergens",element:s.jsx(spe,{})}),s.jsx(Zn,{path:"/price-impact",element:s.jsx(ope,{})}),s.jsx(Zn,{path:"/settings",element:s.jsx(EJ,{})}),s.jsx(Zn,{path:"*",element:s.jsx(Gz,{to:"/dashboard",replace:!0})})]})]})})}const lpe=new VZ({defaultOptions:{queries:{staleTime:5*60*1e3,retry:1}}});JP.createRoot(document.getElementById("root")).render(s.jsx(nF.StrictMode,{children:s.jsx(fZ,{basename:"/kitchen",children:s.jsx(GZ,{client:lpe,children:s.jsx(ape,{})})})})); diff --git a/frontend/dist/icons/icon-192.png b/frontend/dist/icons/icon-192.png deleted file mode 100644 index b002c3a..0000000 Binary files a/frontend/dist/icons/icon-192.png and /dev/null differ diff --git a/frontend/dist/icons/icon-512.png b/frontend/dist/icons/icon-512.png deleted file mode 100644 index 9bfe3e7..0000000 Binary files a/frontend/dist/icons/icon-512.png and /dev/null differ diff --git a/frontend/dist/index.html b/frontend/dist/index.html deleted file mode 100644 index 8bdfa24..0000000 --- a/frontend/dist/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - Kitchen - - - - -
- - diff --git a/frontend/dist/kds-manifest.json b/frontend/dist/kds-manifest.json deleted file mode 100644 index 23ac061..0000000 --- a/frontend/dist/kds-manifest.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "Kitchen Display System", - "short_name": "KDS", - "description": "Kitchen Display System for Kitchen Invoice Flash", - "start_url": "/kds-app", - "display": "standalone", - "background_color": "#1a1a2e", - "theme_color": "#1a1a2e", - "orientation": "landscape", - "icons": [ - { - "src": "/icons/icon-192.png", - "sizes": "192x192", - "type": "image/png", - "purpose": "any maskable" - }, - { - "src": "/icons/icon-512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "any maskable" - } - ] -} diff --git a/frontend/dist/manifest.json b/frontend/dist/manifest.json deleted file mode 100644 index 1a1f407..0000000 --- a/frontend/dist/manifest.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "Kitchen Invoice Upload", - "short_name": "Invoice Upload", - "description": "Quick invoice photo upload for Kitchen Invoice Flash", - "start_url": "/upload-app", - "display": "standalone", - "background_color": "#1a1a2e", - "theme_color": "#1a1a2e", - "orientation": "portrait", - "icons": [ - { - "src": "/icons/icon-192.png", - "sizes": "192x192", - "type": "image/png", - "purpose": "any maskable" - }, - { - "src": "/icons/icon-512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "any maskable" - } - ] -} diff --git a/frontend/dist/pdf.worker.min.mjs b/frontend/dist/pdf.worker.min.mjs deleted file mode 100644 index 82d3b72..0000000 --- a/frontend/dist/pdf.worker.min.mjs +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @licstart The following is the entire license notice for the - * JavaScript code in this page - * - * Copyright 2024 Mozilla Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @licend The above is the entire license notice for the - * JavaScript code in this page - */ -/** - * pdfjsVersion = 5.4.530 - * pdfjsBuild = 50cc4adac - */const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),t=[.001,0,0,.001,0,0],a=1.35,r=.35,i=.25925925925925924,n=1,s=2,o=4,c=8,l=16,h=64,u=128,d=256,f="pdfjs_internal_editor_",g=3,p=9,m=13,b=15,y=101,w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},x=1,S=2,k=3,C=0,v=4,F=1,T=2,O=3,D={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},M="Group",R="R",N=1,E=2,L=4,_=16,U=32,j=128,X=512,q=1,H=2,W=4096,z=8192,$=32768,G=65536,V=131072,K=1048576,J=2097152,Y=8388608,Z=16777216,Q=1,ee=2,te=3,ae=4,re=5,ie={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},ne={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},se={O:"PageOpen",C:"PageClose"},oe=1,ce=5,le=1,he=2,ue=3,de=4,fe=5,ge=6,pe=7,me=8,be=9,ye=10,we=11,xe=12,Se=13,Ae=14,ke=15,Ce=16,ve=17,Fe=18,Ie=19,Te=20,Oe=21,De=22,Me=23,Re=24,Be=25,Ne=26,Pe=27,Ee=28,Le=29,_e=30,Ue=31,je=32,Xe=33,qe=34,He=35,We=36,ze=37,$e=38,Ge=39,Ve=40,Ke=41,Je=42,Ye=43,Ze=44,Qe=45,et=46,tt=47,at=48,rt=49,it=50,nt=51,st=52,ot=53,ct=54,lt=55,ht=56,ut=57,dt=58,ft=59,gt=60,pt=61,mt=62,bt=63,yt=64,wt=65,xt=66,St=67,At=68,kt=69,Ct=70,vt=71,Ft=72,It=73,Tt=74,Ot=75,Dt=76,Mt=77,Rt=80,Bt=81,Nt=83,Pt=84,Et=85,Lt=86,_t=87,Ut=88,jt=89,Xt=90,qt=91,Ht=92,Wt=93,zt=94,$t=0,Gt=1,Vt=2,Kt=3,Jt=4,Yt=1,Zt=2;let Qt=oe;function getVerbosityLevel(){return Qt}function info(e){Qt>=ce&&console.info(`Info: ${e}`)}function warn(e){Qt>=oe&&console.warn(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,a=null){if(!e)return null;if(a&&"string"==typeof e){if(a.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(a.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const r=t?URL.parse(e,t):URL.parse(e);return function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(r)?r:null}function shadow(e,t,a,r=!1){Object.defineProperty(e,t,{value:a,enumerable:!r,configurable:!0,writable:!1});return a}const ea=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ea{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ea{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ea{constructor(e){super(e,"InvalidPDFException")}}class ResponseException extends ea{constructor(e,t,a){super(e,"ResponseException");this.status=t;this.missing=a}}class FormatError extends ea{constructor(e){super(e,"FormatError")}}class AbortException extends ea{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,a=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:e,userAgent:t}=navigator;return shadow(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(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const ta=Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,"0"));class Util{static makeHexColor(e,t,a){return`#${ta[e]}${ta[t]}${ta[a]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,t){let a;if(e[0]){if(e[0]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[3];t[3]*=e[3]}else{a=t[0];t[0]=t[1];t[1]=a;a=t[2];t[2]=t[3];t[3]=a;if(e[1]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){a=t[0];t[0]=t[2];t[2]=a}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,a=0){const r=e[a],i=e[a+1];e[a]=r*t[0]+i*t[2]+t[4];e[a+1]=r*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,a=0){const r=t[0],i=t[1],n=t[2],s=t[3],o=t[4],c=t[5];for(let t=0;t<6;t+=2){const l=e[a+t],h=e[a+t+1];e[a+t]=l*r+h*n+o;e[a+t+1]=l*i+h*s+c}}static applyInverseTransform(e,t){const a=e[0],r=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(a*t[3]-r*t[2]+t[2]*t[5]-t[4]*t[3])/i;e[1]=(-a*t[1]+r*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,a){const r=t[0],i=t[1],n=t[2],s=t[3],o=t[4],c=t[5],l=e[0],h=e[1],u=e[2],d=e[3];let f=r*l+o,g=f,p=r*u+o,m=p,b=s*h+c,y=b,w=s*d+c,x=w;if(0!==i||0!==n){const e=i*l,t=i*u,a=n*h,r=n*d;f+=a;m+=a;p+=r;g+=r;b+=e;x+=e;w+=t;y+=t}a[0]=Math.min(a[0],f,p,g,m);a[1]=Math.min(a[1],b,w,y,x);a[2]=Math.max(a[2],f,p,g,m);a[3]=Math.max(a[3],b,w,y,x)}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 a=e[0],r=e[1],i=e[2],n=e[3],s=a**2+r**2,o=a*i+r*n,c=i**2+n**2,l=(s+c)/2,h=Math.sqrt(l**2-(s*c-o**2));t[0]=Math.sqrt(l+h||1);t[1]=Math.sqrt(l-h||1)}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const a=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(a>r)return null;const i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),n=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>n?null:[a,i,r,n]}static pointBoundingBox(e,t,a){a[0]=Math.min(a[0],e);a[1]=Math.min(a[1],t);a[2]=Math.max(a[2],e);a[3]=Math.max(a[3],t)}static rectBoundingBox(e,t,a,r,i){i[0]=Math.min(i[0],e,a);i[1]=Math.min(i[1],t,r);i[2]=Math.max(i[2],e,a);i[3]=Math.max(i[3],t,r)}static#e(e,t,a,r,i,n,s,o,c,l){if(c<=0||c>=1)return;const h=1-c,u=c*c,d=u*c,f=h*(h*(h*e+3*c*t)+3*u*a)+d*r,g=h*(h*(h*i+3*c*n)+3*u*s)+d*o;l[0]=Math.min(l[0],f);l[1]=Math.min(l[1],g);l[2]=Math.max(l[2],f);l[3]=Math.max(l[3],g)}static#t(e,t,a,r,i,n,s,o,c,l,h,u){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,a,r,i,n,s,o,-h/l,u);return}const d=l**2-4*h*c;if(d<0)return;const f=Math.sqrt(d),g=2*c;this.#e(e,t,a,r,i,n,s,o,(-l+f)/g,u);this.#e(e,t,a,r,i,n,s,o,(-l-f)/g,u)}static bezierBoundingBox(e,t,a,r,i,n,s,o,c){c[0]=Math.min(c[0],e,s);c[1]=Math.min(c[1],t,o);c[2]=Math.max(c[2],e,s);c[3]=Math.max(c[3],t,o);this.#t(e,a,i,s,t,r,n,o,3*(3*(a-i)-e+s),6*(e-2*a+i),3*(a-e),c);this.#t(e,a,i,s,t,r,n,o,3*(3*(r-n)-t+o),6*(t-2*r+n),3*(r-t),c)}}const aa=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e,t=!1){if(e[0]>="ï"){let a;if("þ"===e[0]&&"ÿ"===e[1]){a="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){a="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(a="utf-8");if(a)try{const r=new TextDecoder(a,{fatal:!0}),i=stringToBytes(e),n=r.decode(i);return t||!n.includes("")?n:n.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,"")}catch(e){warn(`stringToPDFString: "${e}".`)}}const a=[];for(let r=0,i=e.length;rta[e]).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise(a=>{a(e(...t))})});"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(e){return e.reduce((e,t)=>e+t,0)});const na=Symbol("CIRCULAR_REF"),sa=Symbol("EOF");let oa=Object.create(null),ca=Object.create(null),la=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return ca[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return oa[e]||=new Cmd(e)}}const ha=function nonSerializableClosure(){return ha};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=ha}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,a){let r=this._map.get(e);if(void 0===r&&void 0!==t){r=this._map.get(t);void 0===r&&void 0!==a&&(r=this._map.get(a))}return r instanceof Ref&&this.xref?this.xref.fetch(r,this.suppressEncryption):r}async getAsync(e,t,a){let r=this._map.get(e);if(void 0===r&&void 0!==t){r=this._map.get(t);void 0===r&&void 0!==a&&(r=this._map.get(a))}return r instanceof Ref&&this.xref?this.xref.fetchAsync(r,this.suppressEncryption):r}getArray(e,t,a){let r=this._map.get(e);if(void 0===r&&void 0!==t){r=this._map.get(t);void 0===r&&void 0!==a&&(r=this._map.get(a))}r instanceof Ref&&this.xref&&(r=this.xref.fetch(r,this.suppressEncryption));if(Array.isArray(r)){r=r.slice();for(let e=0,t=r.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:a=!1}){const r=new Dict(e),i=new Map;for(const e of t)if(e instanceof Dict)for(const[t,r]of e._map){let e=i.get(t);if(void 0===e){e=[];i.set(t,e)}else if(!(a&&r instanceof Dict))continue;e.push(r)}for(const[t,a]of i){if(1===a.length||!(a[0]instanceof Dict)){r._map.set(t,a[0]);continue}const i=new Dict(e);for(const e of a)for(const[t,a]of e._map)i._map.has(t)||i._map.set(t,a);i.size>0&&r._map.set(t,i)}i.clear();return r.size>0?r:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){this._map.delete(e)}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=la[e];if(t)return t;const a=/^(\d+)R(\d*)$/.exec(e);return a&&"0"!==a[1]?la[e]=new Ref(parseInt(a[1]),a[2]?parseInt(a[2]):0):null}static get(e,t){const a=0===t?`${e}R`:`${e}R${t}`;return la[a]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}*keys(){for(const e of this._map.keys())yield Ref.fromString(e)}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get isAsyncDecoder(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,a=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}getOriginalStream(){return this.stream?.getOriginalStream()||this}}const ua=/^[1-9]\.\d$/,da=2**31-1,fa=[1,0,0,1,0,0],ga=["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"],pa=["ExtGState","Font","Properties","XObject"];function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ea{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ea{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ea{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ea{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let a=0;for(let r=0;r0,"The number should be a positive integer.");const a="M".repeat(e/1e3|0)+ma[e%1e3/100|0]+ma[10+(e%100/10|0)]+ma[20+e%10];return t?a.toLowerCase():a}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every(e=>"number"==typeof e):ArrayBuffer.isView(e)&&!(e instanceof BigInt64Array||e instanceof BigUint64Array)&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map(e=>{const a=e.match(t);return a?{name:a[1],pos:parseInt(a[2],10)}:{name:e,pos:0}})}function escapePDFName(e){const t=[];let a=0;for(let r=0,i=e.length;r126||35===i||40===i||41===i||60===i||62===i||91===i||93===i||123===i||125===i||47===i||37===i){a"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`)}function _collectJS(e,t,a,r){if(!e)return;let i=null;if(e instanceof Ref){if(r.has(e))return;i=e;r.put(i);e=t.fetch(e)}if(Array.isArray(e))for(const i of e)_collectJS(i,t,a,r);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let r;t instanceof BaseStream?r=t.getString():"string"==typeof t&&(r=t);r&&=stringToPDFString(r,!0).replaceAll("\0","");r&&a.push(r.trim())}_collectJS(e.getRaw("Next"),t,a,r)}i&&r.remove(i)}function collectActions(e,t,a){const r=Object.create(null),i=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(i)for(let t=i.length-1;t>=0;t--){const n=i[t];if(n instanceof Dict)for(const t of n.getKeys()){const i=a[t];if(!i)continue;const s=[];_collectJS(n.getRaw(t),e,s,new RefSet);s.length>0&&(r[i]=s)}}if(t.has("A")){const a=[];_collectJS(t.get("A"),e,a,new RefSet);a.length>0&&(r.Action=a)}return objectSize(r)>0?r:null}const ba={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,a=e.length;t55295&&(a<57344||a>65533)&&t++;yield a}}function encodeToXmlString(e){const t=[];let a=0;for(let r=0,i=e.length;r55295&&(i<57344||i>65533)&&r++;a=r+1}}if(0===t.length)return e;a: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:a,fontWeight:r,italicAngle:i}=e;if(!validateFontName(a,!0))return!1;const n=r?r.toString():"";e.fontWeight=t.has(n)?n:"400";const s=parseFloat(i);e.italicAngle=isNaN(s)||s<-90||s>90?"14":i.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[a,r]of e){if(!a.startsWith(f))continue;let e=t.get(r.pageIndex);if(!e){e=[];t.set(r.pageIndex,e)}e.push(r)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return null==e||function isAscii(e){if("string"!=typeof e)return!1;return!e||/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let a=0,r=e.length;a>8&255],ta[255&r])}return t.join("")}function stringToUTF16String(e,t=!1){const a=[];t&&a.push("þÿ");for(let t=0,r=e.length;t>8&255),String.fromCharCode(255&r))}return a.join("")}function getRotationMatrix(e,t,a){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,a];case 270:return[0,-1,1,0,0,a];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class QCMS{static#a=null;static _memory=null;static _mustAddAlpha=!1;static _destBuffer=null;static _destOffset=0;static _destLength=0;static _cssColor="";static _makeHexColor=null;static get _memoryArray(){const e=this.#a;return e?.byteLength?e:this.#a=new Uint8Array(this._memory.buffer)}}let ya;const wa="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&wa.decode();let xa=null;function getUint8ArrayMemory0(){null!==xa&&0!==xa.byteLength||(xa=new Uint8Array(ya.memory.buffer));return xa}let Sa=0;function passArray8ToWasm0(e,t){const a=t(1*e.length,1)>>>0;getUint8ArrayMemory0().set(e,a/1);Sa=e.length;return a}const Aa=Object.freeze({RGB8:0,0:"RGB8",RGBA8:1,1:"RGBA8",BGRA8:2,2:"BGRA8",Gray8:3,3:"Gray8",GrayA8:4,4:"GrayA8",CMYK:5,5:"CMYK"}),ka=Object.freeze({Perceptual:0,0:"Perceptual",RelativeColorimetric:1,1:"RelativeColorimetric",Saturation:2,2:"Saturation",AbsoluteColorimetric:3,3:"AbsoluteColorimetric"});function __wbg_get_imports(){const e={wbg:{}};e.wbg.__wbg_copyresult_b08ee7d273f295dd=function(e,t){!function copy_result(e,t){const{_mustAddAlpha:a,_destBuffer:r,_destOffset:i,_destLength:n,_memoryArray:s}=QCMS;if(t!==n)if(a)for(let a=e,n=e+t,o=i;a>>0,t>>>0)};e.wbg.__wbg_copyrgb_d60ce17bb05d9b67=function(e){!function copy_rgb(e){const{_destBuffer:t,_destOffset:a,_memoryArray:r}=QCMS;t[a]=r[e];t[a+1]=r[e+1];t[a+2]=r[e+2]}(e>>>0)};e.wbg.__wbg_makecssRGB_893bf0cd9fdb302d=function(e){!function make_cssRGB(e){const{_memoryArray:t}=QCMS;QCMS._cssColor=QCMS._makeHexColor(t[e],t[e+1],t[e+2])}(e>>>0)};e.wbg.__wbindgen_init_externref_table=function(){const e=ya.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0);e.set(t+0,void 0);e.set(t+1,null);e.set(t+2,!0);e.set(t+3,!1)};e.wbg.__wbindgen_throw=function(e,t){throw new Error(function getStringFromWasm0(e,t){e>>>=0;return wa.decode(getUint8ArrayMemory0().subarray(e,e+t))}(e,t))};return e}function __wbg_finalize_init(e,t){ya=e.exports;__wbg_init.__wbindgen_wasm_module=t;xa=null;ya.__wbindgen_start();return ya}async function __wbg_init(e){if(void 0!==ya)return ya;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module_or_path:e}=e):console.warn("using deprecated parameters for the initialization function; pass a single object instead"));const t=__wbg_get_imports();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:a,module:r}=await async function __wbg_load(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const a=await e.arrayBuffer();return await WebAssembly.instantiate(a,t)}{const a=await WebAssembly.instantiate(e,t);return a instanceof WebAssembly.Instance?{instance:a,module:e}:a}}(await e,t);return __wbg_finalize_init(a,r)}class ColorSpace{static#r=new Uint8ClampedArray(3);constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t,a=new Uint8ClampedArray(3)){this.getRgbItem(e,t,a,0);return a}getRgbHex(e,t){const a=this.getRgb(e,t,ColorSpace.#r);return Util.makeHexColor(a[0],a[1],a[2])}getRgbItem(e,t,a,r){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,a,r,i,n,s){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,a,r,i,n,s,o,c){const l=t*a;let h=null;const u=1<u&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=s<=8?new Uint8Array(u):new Uint16Array(u);for(let e=0;e=.99554525?1:MathClamp(1.055*e**(1/2.4)-.055,0,1)}#b(e){return e<0?-this.#b(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#d}#y(e,t,a){if(0===e[0]&&0===e[1]&&0===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=this.#b(0),i=(1-r)/(1-this.#b(e[0])),n=1-i,s=(1-r)/(1-this.#b(e[1])),o=1-s,c=(1-r)/(1-this.#b(e[2])),l=1-c;a[0]=t[0]*i+n;a[1]=t[1]*s+o;a[2]=t[2]*c+l}#w(e,t,a){if(1===e[0]&&1===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=a;this.#f(CalRGBCS.#n,t,r);const i=CalRGBCS.#l;this.#g(e,r,i);this.#f(CalRGBCS.#s,i,a)}#x(e,t,a){const r=a;this.#f(CalRGBCS.#n,t,r);const i=CalRGBCS.#l;this.#p(e,r,i);this.#f(CalRGBCS.#s,i,a)}#i(e,t,a,r,i){const n=MathClamp(e[t]*i,0,1),s=MathClamp(e[t+1]*i,0,1),o=MathClamp(e[t+2]*i,0,1),c=1===n?1:n**this.GR,l=1===s?1:s**this.GG,h=1===o?1:o**this.GB,u=this.MXA*c+this.MXB*l+this.MXC*h,d=this.MYA*c+this.MYB*l+this.MYC*h,f=this.MZA*c+this.MZB*l+this.MZC*h,g=CalRGBCS.#h;g[0]=u;g[1]=d;g[2]=f;const p=CalRGBCS.#u;this.#w(this.whitePoint,g,p);const m=CalRGBCS.#h;this.#y(this.blackPoint,p,m);const b=CalRGBCS.#u;this.#x(CalRGBCS.#c,m,b);const y=CalRGBCS.#h;this.#f(CalRGBCS.#o,b,y);a[r]=255*this.#m(y[0]);a[r+1]=255*this.#m(y[1]);a[r+2]=255*this.#m(y[2])}getRgbItem(e,t,a,r){this.#i(e,t,a,r,1)}getRgbBuffer(e,t,a,r,i,n,s){const o=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#S(e){return e>=6/29?e**3:108/841*(e-4/29)}#A(e,t,a,r){return a+e*(r-a)/t}#i(e,t,a,r,i){let n=e[t],s=e[t+1],o=e[t+2];if(!1!==a){n=this.#A(n,a,0,100);s=this.#A(s,a,this.amin,this.amax);o=this.#A(o,a,this.bmin,this.bmax)}s>this.amax?s=this.amax:sthis.bmax?o=this.bmax:ofunction qcms_convert_one(e,t,a){ya.qcms_convert_one(e,t,a)}(this.#k,255*e[t],a);break;case 3:r=Aa.RGB8;this.#C=(e,t,a)=>function qcms_convert_three(e,t,a,r,i){ya.qcms_convert_three(e,t,a,r,i)}(this.#k,255*e[t],255*e[t+1],255*e[t+2],a);break;case 4:r=Aa.CMYK;this.#C=(e,t,a)=>function qcms_convert_four(e,t,a,r,i,n){ya.qcms_convert_four(e,t,a,r,i,n)}(this.#k,255*e[t],255*e[t+1],255*e[t+2],255*e[t+3],a);break;default:throw new Error(`Unsupported number of components: ${a}`)}this.#k=function qcms_transformer_from_memory(e,t,a){const r=passArray8ToWasm0(e,ya.__wbindgen_malloc),i=Sa;return ya.qcms_transformer_from_memory(r,i,t,a)>>>0}(e,r,ka.Perceptual);if(!this.#k)throw new Error("Failed to create ICC color space");IccColorSpace.#I||=new FinalizationRegistry(e=>{!function qcms_drop_transformer(e){ya.qcms_drop_transformer(e)}(e)});IccColorSpace.#I.register(this,this.#k)}getRgbHex(e,t){this.#C(e,t,!0);return QCMS._cssColor}getRgbItem(e,t,a,r){QCMS._destBuffer=a;QCMS._destOffset=r;QCMS._destLength=3;this.#C(e,t,!1);QCMS._destBuffer=null}getRgbBuffer(e,t,a,r,i,n,s){e=e.subarray(t,t+a*this.numComps);if(8!==n){const t=255/((1<=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e)return t.subarray(a,r);let i=a+e;i>r&&(i=r);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,a=null){return new Stream(this.bytes.buffer,e,t,a)}clone(){return new Stream(this.bytes.buffer,this.start,this.end-this.start,this.dict.clone())}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,a){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=a;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,a=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=a;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const a=Math.floor(e/this.chunkSize);if(a>this.numChunks)return;const r=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let i=a;i=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e){r>this.progressiveDataLength&&this.ensureRange(a,r);return t.subarray(a,r)}let i=a+e;i>r&&(i=r);i>this.progressiveDataLength&&this.ensureRange(a,i);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,a=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),a=Math.floor((this.end-1)/e)+1,r=[];for(let e=t;e{const readChunk=({value:n,done:s})=>{try{if(s){const t=arrayBuffersToBytes(r);r=null;e(t);return}i+=n.byteLength;a.isStreamingSupported&&this.onProgress({loaded:i});r.push(n);a.read().then(readChunk,t)}catch(e){t(e)}};a.read().then(readChunk,t)}).then(t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})})}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,a=new Set;this._chunksNeededByRequest.set(t,a);for(const t of e)this.stream.hasChunk(t)||a.add(t);if(0===a.size)return Promise.resolve();const r=Promise.withResolvers();this._promisesByRequest.set(t,r);const i=[];for(const e of a){let a=this._requestsByChunk.get(e);if(!a){a=[];this._requestsByChunk.set(e,a);i.push(e)}a.push(t)}if(i.length>0){const e=this.groupChunks(i);for(const t of e){const e=t.beginChunk*this.chunkSize,a=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,a).catch(r.reject)}}return r.promise.catch(e=>{if(!this.aborted)throw e})}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const a=this.getBeginChunk(e),r=this.getEndChunk(t),i=[];for(let e=a;ee-t);return this._requestChunks(t)}groupChunks(e){const t=[];let a=-1,r=-1;for(let i=0,n=e.length;i=0&&r+1!==n){t.push({beginChunk:a,endChunk:r+1});a=n}i+1===e.length&&t.push({beginChunk:a,endChunk:n+1});r=n}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,a=void 0===e.begin,r=a?this.progressiveDataLength:e.begin,i=r+t.byteLength,n=Math.floor(r/this.chunkSize),s=i0||o.push(a)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(s);Number.isInteger(e)&&this._requestChunks([e])}for(const e of o){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}function convertToRGBA(e){switch(e.kind){case F:return convertBlackAndWhiteToRGBA(e);case T:return function convertRGBToRGBA({src:e,srcPos:t=0,dest:a,destPos:r=0,width:i,height:n}){let s=0;const o=i*n*3,c=o>>2,l=new Uint32Array(e.buffer,t,c);if(FeatureTest.isLittleEndian){for(;s>>24|t<<8|4278190080;a[r+2]=t>>>16|i<<16|4278190080;a[r+3]=i>>>8|4278190080}for(let i=4*s,n=t+o;i>>8|255;a[r+2]=t<<16|i>>>16|255;a[r+3]=i<<8|255}for(let i=4*s,n=t+o;i>3,u=7&r,d=e.length;a=new Uint32Array(a.buffer);let f=0;for(let r=0;ra||t>a)return!0;const r=e*t;if(this._hasMaxArea)return r>this.MAX_AREA;if(r(this.MAX_AREA=this.#O**2)}static getReducePowerForJPX(e,t,a){const r=e*t,i=2**30/(4*a);if(!this.needsToBeResized(e,t))return r>i?Math.ceil(Math.log2(r/i)):0;const{MAX_DIM:n,MAX_AREA:s}=this,o=Math.max(e/n,t/n,Math.sqrt(r/Math.min(i,s)));return Math.ceil(Math.log2(o))}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#O,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#D=t}static _areGoodDims(e,t){try{const a=new OffscreenCanvas(e,t),r=a.getContext("2d");r.fillRect(0,0,1,1);const i=r.getImageData(0,0,1,1).data[3];a.width=a.height=1;return 0!==i}catch{return!1}}static _guessMax(e,t,a,r){for(;e+a+1da){const e=this.#M();if(e)return e}const r=this._encodeBMP();let i,n;if(await ImageResizer.canUseImageDecoder){i=new ImageDecoder({data:r,type:"image/bmp",preferAnimation:!1,transfer:[r.buffer]});n=i.decode().catch(e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))}).finally(()=>{i.close()})}else n=createImageBitmap(new Blob([r.buffer],{type:"image/bmp"}));const{MAX_AREA:s,MAX_DIM:o}=ImageResizer,c=Math.max(t/o,a/o,Math.sqrt(t*a/s)),l=Math.max(c,2),h=Math.round(10*(c+1.25))/10/l,u=Math.floor(Math.log2(h)),d=new Array(u+2).fill(2);d[0]=l;d.splice(-1,1,h/(1<>s,c=r>>s;let l,h=r;try{l=new Uint8Array(n)}catch{let e=Math.floor(Math.log2(n+1));for(;;)try{l=new Uint8Array(2**e-1);break}catch{e-=1}h=Math.floor((2**e-1)/(4*a));const t=a*h*4;t>s;e>3,s=a+3&-4;if(a!==s){const e=new Uint8Array(s*t);let r=0;for(let n=0,o=t*a;ni&&(r=i)}else{for(;!this.eof;)this.readBlock(t);r=this.bufferLength}this.pos=r;return this.buffer.subarray(a,r)}async getImageData(e,t){if(!this.canAsyncDecodeImageFromBuffer)return this.isAsyncDecoder?this.decodeImage(null,t):this.getBytes(e,t);const a=await this.stream.asyncGetBytes();return this.decodeImage(a,t)}reset(){this.pos=0}makeSubStream(e,t,a=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const a=e+t;for(;this.bufferLength<=a&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,a)}getBaseStreams(){return this.stream?this.stream.getBaseStreams():null}clone(){for(;!this.eof;)this.readBlock();return new Stream(this.buffer,this.start,this.end-this.start,this.dict.clone())}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter(e=>e instanceof BaseStream);let a=0;for(const t of e)a+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(a);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let a;try{a=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const r=this.bufferLength,i=r+a.length;this.ensureBuffer(i).set(a,r);this.bufferLength=i}getBaseStreams(){const e=[];for(const t of this.streams){const a=t.getBaseStreams();a&&e.push(...a)}return e.length>0?e:null}}class ColorSpaceUtils{static parse({cs:e,xref:t,resources:a=null,pdfFunctionFactory:r,globalColorSpaceCache:i,localColorSpaceCache:n,asyncIfNotCached:s=!1}){const o={xref:t,resources:a,pdfFunctionFactory:r,globalColorSpaceCache:i,localColorSpaceCache:n};let c,l,h;if(e instanceof Ref){l=e;const a=i.getByRef(l)||n.getByRef(l);if(a)return a;e=t.fetch(e)}if(e instanceof Name){c=e.name;const t=n.getByName(c);if(t)return t}try{h=this.#R(e,o)}catch(e){if(s&&!(e instanceof MissingDataException))return Promise.reject(e);throw e}if(c||l){n.set(c,l,h);l&&i.set(null,l,h)}return s?Promise.resolve(h):h}static#B(e,t){const{globalColorSpaceCache:a}=t;let r;if(e instanceof Ref){r=e;const t=a.getByRef(r);if(t)return t}const i=this.#R(e,t);r&&a.set(null,r,i);return i}static#R(e,t){const{xref:a,resources:r,pdfFunctionFactory:i,globalColorSpaceCache:n}=t;if((e=a.fetchIfRef(e))instanceof Name)switch(e.name){case"G":case"DeviceGray":return this.gray;case"RGB":case"DeviceRGB":return this.rgb;case"DeviceRGBA":return this.rgba;case"CMYK":case"DeviceCMYK":return this.cmyk;case"Pattern":return new PatternCS(null);default:if(r instanceof Dict){const a=r.get("ColorSpace");if(a instanceof Dict){const r=a.get(e.name);if(r){if(r instanceof Name)return this.#R(r,t);e=r;break}}}warn(`Unrecognized ColorSpace: ${e.name}`);return this.gray}if(Array.isArray(e)){const r=a.fetchIfRef(e[0]).name;let s,o,c,l,h,u;switch(r){case"G":case"DeviceGray":return this.gray;case"RGB":case"DeviceRGB":return this.rgb;case"CMYK":case"DeviceCMYK":return this.cmyk;case"CalGray":s=a.fetchIfRef(e[1]);l=s.getArray("WhitePoint");h=s.getArray("BlackPoint");u=s.get("Gamma");return new CalGrayCS(l,h,u);case"CalRGB":s=a.fetchIfRef(e[1]);l=s.getArray("WhitePoint");h=s.getArray("BlackPoint");u=s.getArray("Gamma");const d=s.getArray("Matrix");return new CalRGBCS(l,h,u,d);case"ICCBased":const f=e[1]instanceof Ref;if(f){const t=n.getByRef(e[1]);if(t)return t}const g=a.fetchIfRef(e[1]),p=g.dict;o=p.get("N");if(IccColorSpace.isUsable)try{const t=new IccColorSpace(g.getBytes(),"ICCBased",o);f&&n.set(null,e[1],t);return t}catch(t){if(t instanceof MissingDataException)throw t;warn(`ICCBased color space (${e[1]}): "${t}".`)}const m=p.getRaw("Alternate");if(m){const e=this.#B(m,t);if(e.numComps===o)return e;warn("ICCBased color space: Ignoring incorrect /Alternate entry.")}if(1===o)return this.gray;if(3===o)return this.rgb;if(4===o)return this.cmyk;break;case"Pattern":c=e[1]||null;c&&(c=this.#B(c,t));return new PatternCS(c);case"I":case"Indexed":c=this.#B(e[1],t);const b=MathClamp(a.fetchIfRef(e[2]),0,255),y=a.fetchIfRef(e[3]);return new IndexedCS(c,b,y);case"Separation":case"DeviceN":const w=a.fetchIfRef(e[1]);o=Array.isArray(w)?w.length:1;c=this.#B(e[2],t);const x=i.create(e[3]);return new AlternateCS(o,c,x);case"Lab":s=a.fetchIfRef(e[1]);l=s.getArray("WhitePoint");h=s.getArray("BlackPoint");const S=s.getArray("Range");return new LabCS(l,h,S);default:warn(`Unimplemented ColorSpace object: ${r}`);return this.gray}}warn(`Unrecognized ColorSpace object: ${e}`);return this.gray}static get gray(){return shadow(this,"gray",new DeviceGrayCS)}static get rgb(){return shadow(this,"rgb",new DeviceRgbCS)}static get rgba(){return shadow(this,"rgba",new DeviceRgbaCS)}static get cmyk(){if(CmykICCBasedCS.isUsable)try{return shadow(this,"cmyk",new CmykICCBasedCS)}catch{warn("CMYK fallback: DeviceCMYK")}return shadow(this,"cmyk",new DeviceCmykCS)}}class JpegError extends ea{constructor(e){super(e,"JpegError")}}class DNLMarkerError extends ea{constructor(e,t){super(e,"DNLMarkerError");this.scanLines=t}}class EOIMarkerError extends ea{constructor(e){super(e,"EOIMarkerError")}}const va=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),Fa=4017,Ia=799,Ta=3406,Oa=2276,Da=1567,Ma=3784,Ra=5793,Ba=2896;function buildHuffmanTable(e,t){let a,r,i=0,n=16;for(;n>0&&!e[n-1];)n--;const s=[{children:[],index:0}];let o,c=s[0];for(a=0;a0;)c=s.pop();c.index++;s.push(c);for(;s.length<=a;){s.push(o={children:[],index:0});c.children[c.index]=o.children;c=o}i++}if(a+10){g--;return f>>g&1}f=e[t++];if(255===f){const r=e[t++];if(r){if(220===r&&l){const r=readUint16(e,t+=2);t+=2;if(r>0&&r!==a.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",r)}else if(217===r){if(l){const e=y*(8===a.precision?8:0);if(e>0&&Math.round(a.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(f<<8|r).toString(16)}`)}}g=7;return f>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){p--;return}let a=n;const r=s;for(;a<=r;){const r=decodeHuffman(e.huffmanTableAC),i=15&r,n=r>>4;if(0===i){if(n<15){p=receive(n)+(1<>4;if(0===i)if(l<15){p=receive(l)+(1<>4;if(0===r){if(n<15)break;i+=16;continue}i+=n;const s=va[i];e.blockData[t+s]=receiveAndExtend(r);i++}};let T,O=0;const D=1===w?r[0].blocksPerLine*r[0].blocksPerColumn:h*a.mcusPerColumn;let M,R;for(;O<=D;){const a=i?Math.min(D-O,i):D;if(a>0){for(S=0;S0?"unexpected":"excessive"} MCU data, current marker is: ${T.invalid}`);t=T.offset}if(!(T.marker>=65488&&T.marker<=65495))break;t+=2}return t-d}function quantizeAndInverse(e,t,a){const r=e.quantizationTable,i=e.blockData;let n,s,o,c,l,h,u,d,f,g,p,m,b,y,w,x,S;if(!r)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){f=i[t+e];g=i[t+e+1];p=i[t+e+2];m=i[t+e+3];b=i[t+e+4];y=i[t+e+5];w=i[t+e+6];x=i[t+e+7];f*=r[e];if(0!==(g|p|m|b|y|w|x)){g*=r[e+1];p*=r[e+2];m*=r[e+3];b*=r[e+4];y*=r[e+5];w*=r[e+6];x*=r[e+7];n=Ra*f+128>>8;s=Ra*b+128>>8;o=p;c=w;l=Ba*(g-x)+128>>8;d=Ba*(g+x)+128>>8;h=m<<4;u=y<<4;n=n+s+1>>1;s=n-s;S=o*Ma+c*Da+128>>8;o=o*Da-c*Ma+128>>8;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Oa+d*Ta+2048>>12;l=l*Ta-d*Oa+2048>>12;d=S;S=h*Ia+u*Fa+2048>>12;h=h*Fa-u*Ia+2048>>12;u=S;a[e]=n+d;a[e+7]=n-d;a[e+1]=s+u;a[e+6]=s-u;a[e+2]=o+h;a[e+5]=o-h;a[e+3]=c+l;a[e+4]=c-l}else{S=Ra*f+512>>10;a[e]=S;a[e+1]=S;a[e+2]=S;a[e+3]=S;a[e+4]=S;a[e+5]=S;a[e+6]=S;a[e+7]=S}}for(let e=0;e<8;++e){f=a[e];g=a[e+8];p=a[e+16];m=a[e+24];b=a[e+32];y=a[e+40];w=a[e+48];x=a[e+56];if(0!==(g|p|m|b|y|w|x)){n=Ra*f+2048>>12;s=Ra*b+2048>>12;o=p;c=w;l=Ba*(g-x)+2048>>12;d=Ba*(g+x)+2048>>12;h=m;u=y;n=4112+(n+s+1>>1);s=n-s;S=o*Ma+c*Da+2048>>12;o=o*Da-c*Ma+2048>>12;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Oa+d*Ta+2048>>12;l=l*Ta-d*Oa+2048>>12;d=S;S=h*Ia+u*Fa+2048>>12;h=h*Fa-u*Ia+2048>>12;u=S;f=n+d;x=n-d;g=s+u;w=s-u;p=o+h;y=o-h;m=c+l;b=c-l;f<16?f=0:f>=4080?f=255:f>>=4;g<16?g=0:g>=4080?g=255:g>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;b<16?b=0:b>=4080?b=255:b>>=4;y<16?y=0:y>=4080?y=255:y>>=4;w<16?w=0:w>=4080?w=255:w>>=4;x<16?x=0:x>=4080?x=255:x>>=4;i[t+e]=f;i[t+e+8]=g;i[t+e+16]=p;i[t+e+24]=m;i[t+e+32]=b;i[t+e+40]=y;i[t+e+48]=w;i[t+e+56]=x}else{S=Ra*f+8192>>14;S=S<-2040?0:S>=2024?255:S+2056>>4;i[t+e]=S;i[t+e+8]=S;i[t+e+16]=S;i[t+e+24]=S;i[t+e+32]=S;i[t+e+40]=S;i[t+e+48]=S;i[t+e+56]=S}}}function buildComponentData(e,t){const a=t.blocksPerLine,r=t.blocksPerColumn,i=new Int16Array(64);for(let e=0;e=r)return null;const n=readUint16(e,t);if(n>=65472&&n<=65534)return{invalid:null,marker:n,offset:t};let s=readUint16(e,i);for(;!(s>=65472&&s<=65534);){if(++i>=r)return null;s=readUint16(e,i)}return{invalid:n.toString(16),marker:s,offset:i}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),a=Math.ceil(e.scanLines/8/e.maxV);for(const r of e.components){const i=Math.ceil(Math.ceil(e.samplesPerLine/8)*r.h/e.maxH),n=Math.ceil(Math.ceil(e.scanLines/8)*r.v/e.maxV),s=t*r.h,o=64*(a*r.v)*(s+1);r.blockData=new Int16Array(o);r.blocksPerLine=i;r.blocksPerColumn=n}e.mcusPerLine=t;e.mcusPerColumn=a}function readDataBlock(e,t){const a=readUint16(e,t);let r=(t+=2)+a-2;const i=findNextFileMarker(e,r,t);if(i?.invalid){warn("readDataBlock - incorrect length, current marker is: "+i.invalid);r=i.offset}const n=e.subarray(t,r);return{appData:n,oldOffset:t,newOffset:t+n.length}}function skipData(e,t){const a=readUint16(e,t),r=(t+=2)+a-2,i=findNextFileMarker(e,r,t);return i?.invalid?i.offset:r}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let a=null,r=0,i=null,n=readUint16(e,r);r+=2;if(65496!==n)throw new JpegError("SOI not found");n=readUint16(e,r);r+=2;e:for(;65497!==n;){switch(n){case 65505:const{appData:t,oldOffset:s,newOffset:o}=readDataBlock(e,r);r=o;if(69===t[0]&&120===t[1]&&105===t[2]&&102===t[3]&&0===t[4]&&0===t[5]){if(a)throw new JpegError("Duplicate EXIF-blocks found.");a={exifStart:s+6,exifEnd:o}}n=readUint16(e,r);r+=2;continue;case 65472:case 65473:case 65474:i=e[r+7];break e;case 65535:255!==e[r]&&r--}r=skipData(e,r);n=readUint16(e,r);r+=2}return 4===i||3===i&&0===t?null:a||{}}parse(e,{dnlScanLines:t=null}={}){let a,r,i=0,n=null,s=null,o=0;const c=[],l=[],h=[];let u=readUint16(e,i);i+=2;if(65496!==u)throw new JpegError("SOI not found");u=readUint16(e,i);i+=2;e:for(;65497!==u;){let d,f,g;switch(u){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:p,newOffset:m}=readDataBlock(e,i);i=m;65504===u&&74===p[0]&&70===p[1]&&73===p[2]&&70===p[3]&&0===p[4]&&(n={version:{major:p[5],minor:p[6]},densityUnits:p[7],xDensity:p[8]<<8|p[9],yDensity:p[10]<<8|p[11],thumbWidth:p[12],thumbHeight:p[13],thumbData:p.subarray(14,14+3*p[12]*p[13])});65518===u&&65===p[0]&&100===p[1]&&111===p[2]&&98===p[3]&&101===p[4]&&(s={version:p[5]<<8|p[6],flags0:p[7]<<8|p[8],flags1:p[9]<<8|p[10],transformCode:p[11]});break;case 65499:const b=readUint16(e,i);i+=2;const y=b+i-2;let w;for(;i>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(f=0;f<64;f++){w=va[f];a[w]=readUint16(e,i);i+=2}}else for(f=0;f<64;f++){w=va[f];a[w]=e[i++]}c[15&t]=a}break;case 65472:case 65473:case 65474:if(a)throw new JpegError("Only single frame JPEGs supported");i+=2;a={};a.extended=65473===u;a.progressive=65474===u;a.precision=e[i++];const x=readUint16(e,i);i+=2;a.scanLines=t||x;a.samplesPerLine=readUint16(e,i);i+=2;a.components=[];a.componentIds={};const S=e[i++];let k=0,C=0;for(d=0;d>4,n=15&e[i+1];k>4?l:h)[15&t]=buildHuffmanTable(a,n)}break;case 65501:i+=2;r=readUint16(e,i);i+=2;break;case 65498:const F=1===++o&&!t;i+=2;const T=e[i++],O=[];for(d=0;d>4];n.huffmanTableAC=l[15&s];O.push(n)}const D=e[i++],M=e[i++],R=e[i++];try{i+=decodeScan(e,i,a,O,r,D,M,R>>4,15&R,F)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break e}throw t}break;case 65500:i+=4;break;case 65535:255!==e[i]&&i--;break;default:const N=findNextFileMarker(e,i-2,i-3);if(N?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+N.invalid);i=N.offset;break}if(!N||i>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break e}throw new JpegError("JpegImage.parse - unknown marker: "+u.toString(16))}u=readUint16(e,i);i+=2}if(!a)throw new JpegError("JpegImage.parse - no frame data found.");this.width=a.samplesPerLine;this.height=a.scanLines;this.jfif=n;this.adobe=s;this.components=[];for(const e of a.components){const t=c[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/a.maxH,scaleY:e.v/a.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,a=!1){const r=this.width/e,i=this.height/t;let n,s,o,c,l,h,u,d,f,g,p,m=0;const b=this.components.length,y=e*t*b,w=new Uint8ClampedArray(y),x=new Uint32Array(e),S=4294967288;let k;for(u=0;u>8)+C[f+1];return w}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,a,r;for(let i=0,n=e.length;i4)throw new JpegError("Unsupported color mode");const n=this._getLinearizedBlockData(e,t,i);if(1===this.numComponents&&(a||r)){const e=n.length*(a?4:3),t=new Uint8ClampedArray(e);let r=0;if(a)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let a=0,r=e.length;a0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#N(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const a=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=a;this.bufferLength=a.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const a=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!a)return null;let r=this.#N(a);const i=JpegImage.canUseImageDecoder(r,e.colorTransform);if(!i)return null;if(i.exifStart){r=r.slice();r.fill(0,i.exifStart,i.exifEnd)}t=new ImageDecoder({data:r,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}const Na=async function OpenJPEG(e={}){var t=e,a="./this.program",quit_=(e,t)=>{throw t},r=import.meta.url;try{new URL(".",r).href}catch{}0;var i,n,s,o,c,l,h,u,d=console.log.bind(console),f=console.error.bind(console),g=!1,p=!1;function updateMemoryViews(){var e=o.buffer;c=new Int8Array(e);new Int16Array(e);l=new Uint8Array(e);new Uint16Array(e);h=new Int32Array(e);u=new Uint32Array(e);new Float32Array(e);new Float64Array(e);new BigInt64Array(e);new BigUint64Array(e)}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var m,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(t)},b=[],addOnPostRun=e=>b.push(e),y=[],addOnPreRun=e=>y.push(e),w=!0,x=0,S={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return i;quit_(0,e)},keepRuntimeAlive=()=>w||x>0,_proc_exit=e=>{i=e;if(!keepRuntimeAlive()){t.onExit?.(e);g=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{i=e;_proc_exit(e)},callUserCallback=e=>{if(!g)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(i)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},alignMemory=(e,t)=>Math.ceil(e/t)*t,growMemory=e=>{var t=(e-o.buffer.byteLength+65535)/65536|0;try{o.grow(t);updateMemoryViews();return 1}catch(e){}},k={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.language||"C").replace("-","_")+".UTF-8",_:a||"./this.program"};for(var t in k)void 0===k[t]?delete e[t]:e[t]=k[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToUTF8=(e,t,a)=>((e,t,a,r)=>{if(!(r>0))return 0;for(var i=a,n=a+r-1,s=0;s=n)break;t[a++]=o}else if(o<=2047){if(a+1>=n)break;t[a++]=192|o>>6;t[a++]=128|63&o}else if(o<=65535){if(a+2>=n)break;t[a++]=224|o>>12;t[a++]=128|o>>6&63;t[a++]=128|63&o}else{if(a+3>=n)break;t[a++]=240|o>>18;t[a++]=128|o>>12&63;t[a++]=128|o>>6&63;t[a++]=128|63&o;s++}}t[a]=0;return a-i})(e,l,t,a),lengthBytesUTF8=e=>{for(var t=0,a=0;a=55296&&r<=57343){t+=4;++a}else t+=3}return t},C=[null,[],[]],v="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,a,r)=>{var i=((e,t,a,r)=>{var i=t+a;if(r)return i;for(;e[t]&&!(t>=i);)++t;return t})(e,t,a,r);if(i-t>16&&e.buffer&&v)return v.decode(e.subarray(t,i));for(var n="";t>10,56320|1023&l)}}else n+=String.fromCharCode((31&s)<<6|o)}else n+=String.fromCharCode(s)}return n},printChar=(e,t)=>{var a=C[e];if(0===t||10===t){(1===e?d:f)(UTF8ArrayToString(a));a.length=0}else a.push(t)},UTF8ToString=(e,t,a)=>e?UTF8ArrayToString(l,e,t,a):"";t.noExitRuntime&&(w=t.noExitRuntime);t.print&&(d=t.print);t.printErr&&(f=t.printErr);t.wasmBinary&&t.wasmBinary;t.arguments&&t.arguments;t.thisProgram&&(a=t.thisProgram);if(t.preInit){"function"==typeof t.preInit&&(t.preInit=[t.preInit]);for(;t.preInit.length>0;)t.preInit.shift()()}t.writeArrayToMemory=(e,t)=>{c.set(e,t)};var F,T={k:()=>function abort(e){t.onAbort?.(e);f(e="Aborted("+e+")");g=!0;e+=". Build with -sASSERTIONS for more info.";var a=new WebAssembly.RuntimeError(e);s?.(a);throw a}(""),j:()=>{w=!1;x=0},l:(e,t)=>{if(S[e]){clearTimeout(S[e].id);delete S[e]}if(!t)return 0;var a=setTimeout(()=>{delete S[e];callUserCallback(()=>m(e,performance.now()))},t);S[e]={id:a,timeout_ms:t};return 0},f:function _copy_pixels_1(e,a){e>>=2;const r=t.imageData=new Uint8ClampedArray(a),i=h.subarray(e,e+a);r.set(i)},e:function _copy_pixels_3(e,a,r,i){e>>=2;a>>=2;r>>=2;const n=t.imageData=new Uint8ClampedArray(3*i),s=h.subarray(e,e+i),o=h.subarray(a,a+i),c=h.subarray(r,r+i);for(let e=0;e>=2;a>>=2;r>>=2;i>>=2;const s=t.imageData=new Uint8ClampedArray(4*n),o=h.subarray(e,e+n),c=h.subarray(a,a+n),l=h.subarray(r,r+n),u=h.subarray(i,i+n);for(let e=0;e{var t=l.length,a=2147483648;if((e>>>=0)>a)return!1;for(var r=1;r<=4;r*=2){var i=t*(1+.2/r);i=Math.min(i,e+100663296);var n=Math.min(a,alignMemory(Math.max(e,i),65536));if(growMemory(n))return!0}return!1},o:(e,t)=>{var a=0,r=0;for(var i of getEnvStrings()){var n=t+a;u[e+r>>2]=n;a+=stringToUTF8(i,n,1/0)+1;r+=4}return 0},p:(e,t)=>{var a=getEnvStrings();u[e>>2]=a.length;var r=0;for(var i of a)r+=lengthBytesUTF8(i)+1;u[t>>2]=r;return 0},n:function _fd_seek(e,t,a,r){t=(i=t)<-9007199254740992||i>9007199254740992?NaN:Number(i);var i;return 70},b:(e,t,a,r)=>{for(var i=0,n=0;n>2],o=u[t+4>>2];t+=8;for(var c=0;c>2]=i;return 0},q:function _gray_to_rgba(e,a){e>>=2;const r=t.imageData=new Uint8ClampedArray(4*a),i=h.subarray(e,e+a);for(let e=0;e>=2;a>>=2;const i=t.imageData=new Uint8ClampedArray(4*r),n=h.subarray(e,e+r),s=h.subarray(a,a+r);for(let e=0;e>=2;a>>=2;r>>=2;const n=t.imageData=new Uint8ClampedArray(4*i),s=h.subarray(e,e+i),o=h.subarray(a,a+i),c=h.subarray(r,r+i);for(let e=0;e{t.instantiateWasm(e,(e,t)=>{a(receiveInstance(e))})})}();!function run(){!function preRun(){if(t.preRun){"function"==typeof t.preRun&&(t.preRun=[t.preRun]);for(;t.preRun.length;)addOnPreRun(t.preRun.shift())}callRuntimeCallbacks(y)}();function doRun(){t.calledRun=!0;if(!g){!function initRuntime(){p=!0;F.s()}();n?.(t);t.onRuntimeInitialized?.();!function postRun(){if(t.postRun){"function"==typeof t.postRun&&(t.postRun=[t.postRun]);for(;t.postRun.length;)addOnPostRun(t.postRun.shift())}callRuntimeCallbacks(b)}()}}if(t.setStatus){t.setStatus("Running...");setTimeout(()=>{setTimeout(()=>t.setStatus(""),1);doRun()},1)}else doRun()}();return p?t:new Promise((e,t)=>{n=e;s=t})};class JpxError extends ea{constructor(e){super(e,"JpxError")}}class JpxImage{static#P=null;static#E=null;static#L=null;static#v=!0;static#_=!0;static#F=null;static setOptions({handler:e,useWasm:t,useWorkerFetch:a,wasmUrl:r}){this.#v=t;this.#_=a;this.#F=r;a||(this.#E=e)}static async#U(e){const t=`${this.#F}openjpeg_nowasm_fallback.js`;let a=null;try{a=(await import( -/*webpackIgnore: true*/ -/*@vite-ignore*/ -t)).default()}catch(e){warn(`JpxImage#getJsModule: ${e}`)}e(a)}static async#j(e,t,a){const r="openjpeg.wasm";try{this.#P||(this.#_?this.#P=await fetchBinaryData(`${this.#F}${r}`):this.#P=await this.#E.sendWithPromise("FetchBinaryData",{type:"wasmFactory",filename:r}));return a((await WebAssembly.instantiate(this.#P,t)).instance)}catch(t){warn(`JpxImage#instantiateWasm: ${t}`);this.#U(e);return null}finally{this.#E=null}}static async decode(e,{numComponents:t=4,isIndexedColormap:a=!1,smaskInData:r=!1,reducePower:i=0}={}){if(!this.#L){const{promise:e,resolve:t}=Promise.withResolvers(),a=[e];this.#v?a.push(Na({warn,instantiateWasm:this.#j.bind(this,t)})):this.#U(t);this.#L=Promise.race(a)}const n=await this.#L;if(!n)throw new JpxError("OpenJPEG failed to initialize");let s;try{const o=e.length;s=n._malloc(o);n.writeArrayToMemory(e,s);if(n._jp2_decode(s,o,t>0?t:0,!!a,!!r,i)){const{errorMessages:e}=n;if(e){delete n.errorMessages;throw new JpxError(e)}throw new JpxError("Unknown error")}const{imageData:c}=n;n.imageData=null;return c}finally{s&&n._free(s)}}static cleanup(){this.#L=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const a=t;t=e.getByte();if(65361===(a<<8|t)){e.skip(4);const t=e.getInt32()>>>0,a=e.getInt32()>>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0;e.skip(16);return{width:t-r,height:a-i,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}function addState(e,t,a,r,i){let n=e;for(let e=0,a=t.length-1;e1e3){l=Math.max(l,d);f+=u+2;d=0;u=0}h.push({transform:t,x:d,y:f,w:a.width,h:a.height});d+=a.width+2;u=Math.max(u,a.height)}const g=Math.max(l,d)+1,p=f+u+1,m=new Uint8Array(g*p*4),b=g<<2;for(let e=0;e=0;){t[n-4]=t[n];t[n-3]=t[n+1];t[n-2]=t[n+2];t[n-1]=t[n+3];t[n+a]=t[n+a-4];t[n+a+1]=t[n+a-3];t[n+a+2]=t[n+a-2];t[n+a+3]=t[n+a-1];n-=b}}const y={width:g,height:p};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(g,p);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(m.buffer),g,p),0,0);y.bitmap=e.transferToImageBitmap();y.data=null}else{y.kind=O;y.data=m}a.splice(n,4*c,_t);r.splice(n,4*c,[y,h]);return n+1});addState(Pa,[ye,xe,Nt,we],null,function iterateImageMaskGroup(e,t){const a=e.fnArray,r=(t-(e.iCurr-3))%4;switch(r){case 0:return a[t]===ye;case 1:return a[t]===xe;case 2:return a[t]===Nt;case 3:return a[t]===we}throw new Error(`iterateImageMaskGroup - invalid pos: ${r}`)},function foundImageMaskGroup(e,t){const a=e.fnArray,r=e.argsArray,i=e.iCurr,n=i-3,s=i-2,o=i-1;let c=Math.floor((t-n)/4);if(c<10)return t-(t-n)%4;let l,h,u=!1;const d=r[o][0],f=r[s][0],g=r[s][1],p=r[s][2],m=r[s][3];if(g===p){u=!0;l=s+4;let e=o+4;for(let t=1;t=4&&a[n-4]===a[s]&&a[n-3]===a[o]&&a[n-2]===a[c]&&a[n-1]===a[l]&&r[n-4][0]===h&&r[n-4][1]===u){d++;f-=5}let g=f+4;for(let e=1;e{const t=e.argsArray,a=t[e.iCurr-1][0];if(a!==Te&&a!==Oe&&a!==Re&&a!==Be&&a!==Ne&&a!==Pe)return!0;const r=t[e.iCurr-2];return 1===r[0]&&0===r[1]&&0===r[2]&&1===r[3]},()=>!1,(e,t)=>{const{fnArray:a,argsArray:r}=e,i=e.iCurr,n=i-3,s=i-2,o=r[i-1],c=r[s],[,[l],h]=o;if(h){Util.scaleMinMax(c,h);for(let e=0,t=l.length;e=a)break}r=(r||Pa)[e[t]];if(r&&!Array.isArray(r)){n.iCurr=t;t++;if(!r.checkFn||(0,r.checkFn)(n)){i=r;r=null}else r=null}else t++}this.state=r;this.match=i;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;static isOffscreenCanvasSupported=!1;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&d?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}static setOptions({isOffscreenCanvasSupported:e}){this.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===we||e===je))&&this.flush()}addImageOps(e,t,a,r=!1){if(r){this.addOp(ye);this.addOp(be,[[["SMask",!1]]])}void 0!==a&&this.addOp(Ct,["OC",a]);this.addOp(e,t);void 0!==a&&this.addOp(vt,[]);r&&this.addOp(we)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(le,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,a=e.length;t>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,a){let r=0;for(let i=a;i>=0;i--){r+=e[i]+t[i];e[i]=255&r;r>>=8}}function incHex(e,t){let a=1;for(let r=t;r>=0&&a>0;r--){a+=e[r];e[r]=255&a;a>>=8}}const Ea=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const a=this.readByte();if(a<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&a);t=t<<7|127&a}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let a;const r=this.tmpBuf;let i=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");a=!(128&e);r[i++]=127&e}while(!a);let n=t,s=0,o=0;for(;n>=0;){for(;o<8&&r.length>0;){s|=r[--i]<>=8;o-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const a=1&e[t]?255:0;let r=0;for(let i=0;i<=t;i++){r=(1&r)<<8|e[i];e[i]=r>>1^a}}readString(){const e=this.readNumber(),t=new Array(e);for(let a=0;a=0;){const e=d>>5;if(7===e){switch(31&d){case 0:r.readString();break;case 1:n=r.readString()}continue}const a=!!(16&d),i=15&d;if(i+1>Ea)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const f=1,g=r.readNumber();switch(e){case 0:r.readHex(s,i);r.readHexNumber(o,i);addHex(o,s,i);t.addCodespaceRange(i+1,hexToInt(s,i),hexToInt(o,i));for(let e=1;e=0;--i){r[a+i]=255&s;s>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.stream=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.stream.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,a=this.ensureBuffer(this.bufferLength+t);let r=this.bufferLength,i=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(i<0)i=e;else{a[r++]=i<<4|e;i=-1}}if(i>=0&&this.eof){a[r++]=i<<4;i=-1}this.firstDigit=i;this.bufferLength=r}}const La=-1,_a=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Ua=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],ja=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Xa=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],qa=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Ha=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let a;for(;0===(a=this._lookBits(12));)this._eatBits(1);1===a&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,a=this.columns;let r,i,n,s,o;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let n,o,c;if(this.nextLine2D){for(s=0;t[s]=64);do{o+=c=this._getWhiteCode()}while(c>=64)}else{do{n+=c=this._getWhiteCode()}while(c>=64);do{o+=c=this._getBlackCode()}while(c>=64)}this._addPixels(t[this.codingPos]+n,i);t[this.codingPos]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]=64);else do{n+=c=this._getWhiteCode()}while(c>=64);this._addPixels(t[this.codingPos]+n,i);i^=1}}let l=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){n=this._lookBits(12);if(this.eoline)for(;n!==La&&1!==n;){this._eatBits(1);n=this._lookBits(12)}else for(;0===n;){this._eatBits(1);n=this._lookBits(12)}if(1===n){this._eatBits(12);l=!0}else n===La&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&l&&this.byteAlign){n=this._lookBits(12);if(1===n){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(s=0;s<4;++s){n=this._lookBits(12);1!==n&&info("bad rtc code: "+n);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){n=this._lookBits(13);if(n===La){this.eof=!0;return-1}if(n>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&n)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){o=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]n){o<<=n;1&this.codingPos||(o|=255>>8-n);this.outputBits-=n;n=0}else{o<<=this.outputBits;1&this.codingPos||(o|=255>>8-this.outputBits);n-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){o<<=n;n=0}}}while(n)}this.black&&(o^=255);return o}_addPixels(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}this.codingPos=r}_addPixelsNeg(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}else if(e0&&e=i){const t=a[e-i];if(t[0]===r){this._eatBits(r);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=_a[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,_a);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return La}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===La)return 1;e=t>>5?ja[t>>3]:Ua[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,ja);if(e[0])return e[1];e=this._findTableCode(11,12,Ua);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===La)return 1;t=e>>7?!(e>>9)&&e>>7?qa[(e>>1)-64]:Ha[e>>7]:Xa[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Ha);if(e[0])return e[1];e=this._findTableCode(7,12,qa,64);if(e[0])return e[1];e=this._findTableCode(10,13,Xa);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.dict=e.dict;a instanceof Dict||(a=Dict.empty);const r={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(r,{K:a.get("K"),EndOfLine:a.get("EndOfLine"),EncodedByteAlign:a.get("EncodedByteAlign"),Columns:a.get("Columns"),Rows:a.get("Rows"),EndOfBlock:a.get("EndOfBlock"),BlackIs1:a.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Wa=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),za=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]),$a=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]),Ga=[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],Va=[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];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.stream=e;this.dict=e.dict;const a=e.getByte(),r=e.getByte();if(-1===a||-1===r)throw new FormatError(`Invalid header in flate stream: ${a}, ${r}`);if(8!=(15&a))throw new FormatError(`Unknown compression method in flate stream: ${a}, ${r}`);if(((a<<8)+r)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${a}, ${r}`);if(32&r)throw new FormatError(`FDICT bit set in flate stream: ${a}, ${r}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const a=await this.asyncGetBytes();return a?a.length<=e?a:a.subarray(0,e):this.getBytes(e)}async asyncGetBytes(){this.stream.reset();const e=this.stream.getBytes();try{const{readable:t,writable:a}=new DecompressionStream("deflate"),r=a.getWriter();await r.ready;r.write(e).then(async()=>{await r.ready;await r.close()}).catch(()=>{});const i=[];let n=0;for await(const e of t){i.push(e);n+=e.byteLength}const s=new Uint8Array(n);let o=0;for(const e of i){s.set(e,o);o+=e.byteLength}return s}catch{this.stream=new Stream(e,2,e.length,this.stream.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.stream;let a,r=this.codeSize,i=this.codeBuf;for(;r>e;this.codeSize=r-=e;return a}getCode(e){const t=this.stream,a=e[0],r=e[1];let i,n=this.codeSize,s=this.codeBuf;for(;n>16,l=65535&o;if(c<1||n>c;this.codeSize=n-c;return l}generateHuffmanTable(e){const t=e.length;let a,r=0;for(a=0;ar&&(r=e[a]);const i=1<>=1}for(a=e;a>=1;if(0===t){let t;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}let a=t;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}a|=t<<8;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}let i=t;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}i|=t<<8;if(i!==(65535&~a)&&(0!==a||0!==i))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const n=this.bufferLength,s=n+a;e=this.ensureBuffer(s);this.bufferLength=s;if(0===a)-1===r.peekByte()&&(this.eof=!0);else{const t=r.getBytes(a);e.set(t,n);t.length0;)h[o++]=f}i=this.generateHuffmanTable(h.subarray(0,e));n=this.generateHuffmanTable(h.subarray(e,l))}}e=this.buffer;let s=e?e.length:0,o=this.bufferLength;for(;;){let t=this.getCode(i);if(t<256){if(o+1>=s){e=this.ensureBuffer(o+1);s=e.length}e[o++]=t;continue}if(256===t){this.bufferLength=o;return}t-=257;t=za[t];let r=t>>16;r>0&&(r=this.getBits(r));a=(65535&t)+r;t=this.getCode(n);t=$a[t];r=t>>16;r>0&&(r=this.getBits(r));const c=(65535&t)+r;if(o+a>=s){e=this.ensureBuffer(o+a);s=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let a=e[t]>>1,r=1&e[t];const i=Ka[a],n=i.qe;let s,o=this.a-n;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&o));this.a=o;e[t]=a<<1|r;return s}}class Jbig2Error extends ea{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,a){this.data=e;this.start=t;this.end=a}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,a){const r=e.getContexts(t);let i=1;function readBits(e){let t=0;for(let n=0;n>>0}const n=readBits(1),s=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let o;0===n?o=s:s>0&&(o=-s);return o>=-2147483648&&o<=da?o:null}function decodeIAID(e,t,a){const r=e.getContexts("IAID");let i=1;for(let e=0;ee.y-t.y||e.x-t.x);const h=l.length,u=new Int8Array(h),d=new Int8Array(h),f=[];let g,p,m=0,b=0,y=0,w=0;for(p=0;p=v&&E=F){q=q<<1&m;for(p=0;p=0&&_=0){U=M[L][_];U&&(q|=U<=e?l<<=1:l=l<<1|S[o][c]}for(f=0;f=w||c<0||c>=y?l<<=1:l=l<<1|r[o][c]}const g=k.readBit(C,l);t[s]=g}}return S}function decodeTextRegion(e,t,a,r,i,n,s,o,c,l,h,u,d,f,g,p,m,b,y){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const w=[];let x,S;for(x=0;x1&&(i=e?y.readBits(b):decodeInteger(C,"IAIT",k));const n=s*v+i,F=e?f.symbolIDTable.decode(y):decodeIAID(C,k,c),T=t&&(e?y.readBit():decodeInteger(C,"IARI",k));let O=o[F],D=O[0].length,M=O.length;if(T){const e=decodeInteger(C,"IARDW",k),t=decodeInteger(C,"IARDH",k);D+=e;M+=t;O=decodeRefinement(D,M,g,O,(e>>1)+decodeInteger(C,"IARDX",k),(t>>1)+decodeInteger(C,"IARDY",k),!1,p,m)}let R=0;l?1&u?R=M-1:r+=M-1:u>1?r+=D-1:R=D-1;const N=n-(1&u?0:M-1),E=r-(2&u?D-1:0);let L,_,U;if(l)for(L=0;L>5&7;const c=[31&s];let l=t+6;if(7===o){o=536870911&readUint32(e,l-1);l+=3;let t=o+8>>3;c[0]=e[l++];for(;--t>0;)c.push(e[l++])}else if(5===o||6===o)throw new Jbig2Error("invalid referred-to flags");a.retainBits=c;let h=4;a.number<=256?h=1:a.number<=65536&&(h=2);const u=[];let d,f;for(d=0;d>>24&255;n[3]=t.height>>16&255;n[4]=t.height>>8&255;n[5]=255&t.height;for(d=l,f=e.length;d>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;l+=2;if(!e.huffman){c=0===e.template?4:1;s=[];for(o=0;o>2&3;h.stripSize=1<>4&3;h.transposed=!!(64&u);h.combinationOperator=u>>7&3;h.defaultPixelValue=u>>9&1;h.dsOffset=u<<17>>27;h.refinementTemplate=u>>15&1;if(h.huffman){const e=readUint16(r,l);l+=2;h.huffmanFS=3&e;h.huffmanDS=e>>2&3;h.huffmanDT=e>>4&3;h.huffmanRefinementDW=e>>6&3;h.huffmanRefinementDH=e>>8&3;h.huffmanRefinementDX=e>>10&3;h.huffmanRefinementDY=e>>12&3;h.huffmanRefinementSizeSelector=!!(16384&e)}if(h.refinement&&!h.refinementTemplate){s=[];for(o=0;o<2;o++){s.push({x:readInt8(r,l),y:readInt8(r,l+1)});l+=2}h.refinementAt=s}h.numberOfSymbolInstances=readUint32(r,l);l+=4;n=[h,a.referredTo,r,l,i];break;case 16:const d={},f=r[l++];d.mmr=!!(1&f);d.template=f>>1&3;d.patternWidth=r[l++];d.patternHeight=r[l++];d.maxPatternIndex=readUint32(r,l);l+=4;n=[d,a.number,r,l,i];break;case 22:case 23:const g={};g.info=readRegionSegmentInformation(r,l);l+=tr;const p=r[l++];g.mmr=!!(1&p);g.template=p>>1&3;g.enableSkip=!!(8&p);g.combinationOperator=p>>4&7;g.defaultPixelValue=p>>7&1;g.gridWidth=readUint32(r,l);l+=4;g.gridHeight=readUint32(r,l);l+=4;g.gridOffsetX=4294967295&readUint32(r,l);l+=4;g.gridOffsetY=4294967295&readUint32(r,l);l+=4;g.gridVectorX=readUint16(r,l);l+=2;g.gridVectorY=readUint16(r,l);l+=2;n=[g,a.referredTo,r,l,i];break;case 38:case 39:const m={};m.info=readRegionSegmentInformation(r,l);l+=tr;const b=r[l++];m.mmr=!!(1&b);m.template=b>>1&3;m.prediction=!!(8&b);if(!m.mmr){c=0===m.template?4:1;s=[];for(o=0;o>2&1;y.combinationOperator=w>>3&3;y.requiresBuffer=!!(32&w);y.combinationOperatorOverride=!!(64&w);n=[y];break;case 49:case 50:case 51:case 62:break;case 53:n=[a.number,r,l,i];break;default:throw new Jbig2Error(`segment type ${a.typeName}(${a.type}) is not implemented`)}const h="on"+a.typeName;h in t&&t[h].apply(t,n)}function processSegments(e,t){for(let a=0,r=e.length;a>3,a=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&a.fill(255);this.buffer=a}drawBitmap(e,t){const a=this.currentPageInfo,r=e.width,i=e.height,n=a.width+7>>3,s=a.combinationOperatorOverride?e.combinationOperator:a.combinationOperator,o=this.buffer,c=128>>(7&e.x);let l,h,u,d,f=e.y*n+(e.x>>3);switch(s){case 0:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;case 2:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;default:throw new Jbig2Error(`operator ${s} is not supported`)}}onImmediateGenericRegion(e,t,a,r){const i=e.info,n=new DecodingContext(t,a,r),s=decodeBitmap(e.mmr,i.width,i.height,e.template,e.prediction,null,e.at,n);this.drawBitmap(i,s)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,a,r,i,n){let s,o;if(e.huffman){s=function getSymbolDictionaryHuffmanTables(e,t,a){let r,i,n,s,o=0;switch(e.huffmanDHSelector){case 0:case 1:r=getStandardTable(e.huffmanDHSelector+4);break;case 3:r=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:i=getStandardTable(e.huffmanDWSelector+2);break;case 3:i=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){n=getCustomHuffmanTable(o,t,a);o++}else n=getStandardTable(1);s=e.aggregationInstancesSelector?getCustomHuffmanTable(o,t,a):getStandardTable(1);return{tableDeltaHeight:r,tableDeltaWidth:i,tableBitmapSize:n,tableAggregateInstances:s}}(e,a,this.customTables);o=new Reader(r,i,n)}let c=this.symbols;c||(this.symbols=c={});const l=[];for(const e of a){const t=c[e];t&&l.push(...t)}const h=new DecodingContext(r,i,n);c[t]=function decodeSymbolDictionary(e,t,a,r,i,n,s,o,c,l,h,u){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const d=[];let f=0,g=log2(a.length+r);const p=h.decoder,m=h.contextCache;let b,y;if(e){b=getStandardTable(1);y=[];g=Math.max(g,1)}for(;d.length1)w=decodeTextRegion(e,t,r,f,0,i,1,a.concat(d),g,0,0,1,0,n,c,l,h,0,u);else{const e=decodeIAID(m,p,g),t=decodeInteger(m,"IARDX",p),i=decodeInteger(m,"IARDY",p);w=decodeRefinement(r,f,c,e=32){let a,r,s;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");r=i.readBits(2)+3;a=n[e-1].prefixLength;break;case 33:r=i.readBits(3)+3;a=0;break;case 34:r=i.readBits(7)+11;a=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(s=0;s=0;m--){O=e?decodeMMRBitmap(T,c,l,!0):decodeBitmap(!1,c,l,a,!1,null,v,g);F[m]=O}for(D=0;D=0;b--){R^=F[b][D][M];N|=R<>8;_=u+D*d-M*f>>8;if(L>=0&&L+S<=r&&_>=0&&_+k<=i)for(m=0;m=i)){j=p[t];U=E[m];for(b=0;b=0&&e>1&7),c=1+(r>>4&7),l=[];let h,u,d=i;do{h=s.readBits(o);u=s.readBits(c);l.push(new HuffmanLine([d,h,u,0]));d+=1<>t&1;if(t<=0)this.children[a]=new HuffmanTreeNode(e);else{let r=this.children[a];r||(this.children[a]=r=new HuffmanTreeNode(null));r.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,a=e.length;t0&&this.rootNode.buildTree(a,a.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let a=0;for(let r=0;r=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,a=0;for(t=e-1;t>=0;t--)a|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,a){let r=0;for(let i=0,n=t.length;i>a&1;a--}}if(r&&!o){const e=5;for(let t=0;t>>t&(1<0;if(e<256){d[0]=e;f=1}else{if(!(e>=258)){if(256===e){h=9;s=258;f=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){d[t]=o[a];a=l[a]}}else d[f++]=d[0]}if(i){l[s]=u;c[s]=c[u]+1;o[s]=d[0];s++;h=s+n&s+n-1?h:0|Math.min(Math.log(s+n)/.6931471805599453+1,12)}u=e;g+=f;if(r15))throw new FormatError(`Unsupported predictor: ${r}`);this.readBlock=2===r?this.readBlockTiff:this.readBlockPng;this.stream=e;this.dict=e.dict;const i=this.colors=a.get("Colors")||1,n=this.bits=a.get("BPC","BitsPerComponent")||8,s=this.columns=a.get("Columns")||1;this.pixBytes=i*n+7>>3;this.rowBytes=s*i*n+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,a=this.ensureBuffer(t+e),r=this.bits,i=this.colors,n=this.stream.getBytes(e);this.eof=!n.length;if(this.eof)return;let s,o=0,c=0,l=0,h=0,u=t;if(1===r&&1===i)for(s=0;s>1;e^=e>>2;e^=e>>4;o=(1&e)<<7;a[u++]=e}else if(8===r){for(s=0;s>8&255;a[u++]=255&e}}else{const e=new Uint8Array(i+1),u=(1<>l-r)&u;l-=r;c=c<=8){a[f++]=c>>h-8&255;h-=8}}h>0&&(a[f++]=(c<<8-h)+(o&(1<<8-h)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,a=this.stream.getByte(),r=this.stream.getBytes(e);this.eof=!r.length;if(this.eof)return;const i=this.bufferLength,n=this.ensureBuffer(i+e);let s=n.subarray(i-e,i);0===s.length&&(s=new Uint8Array(e));let o,c,l,h=i;switch(a){case 0:for(o=0;o>1)+r[o];for(;o>1)+r[o]&255;h++}break;case 4:for(o=0;o0){const e=this.stream.getBytes(r);t.set(e,a);a+=r}}else{r=257-r;t=this.ensureBuffer(a+r+1);t.fill(e[1],a,a+r);a+=r}this.bufferLength=a}}class Parser{constructor({lexer:e,xref:t,allowStreams:a=!1,recoveryMode:r=!1}){this.lexer=e;this.xref=t;this.allowStreams=a;this.recoveryMode=r;this.imageCache=Object.create(null);this._imageId=0;this.refill()}refill(){this.buf1=this.lexer.getObj();this.buf2=this.lexer.getObj()}shift(){if(this.buf2 instanceof Cmd&&"ID"===this.buf2.cmd){this.buf1=this.buf2;this.buf2=null}else{this.buf1=this.buf2;this.buf2=this.lexer.getObj()}}tryShift(){try{this.shift();return!0}catch(e){if(e instanceof MissingDataException)throw e;return!1}}getObj(e=null){const t=this.buf1;this.shift();if(t instanceof Cmd)switch(t.cmd){case"BI":return this.makeInlineImage(e);case"[":const a=[];for(;!isCmd(this.buf1,"]")&&this.buf1!==sa;)a.push(this.getObj(e));if(this.buf1===sa){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside array.")}this.shift();return a;case"<<":const r=new Dict(this.xref);for(;!isCmd(this.buf1,">>")&&this.buf1!==sa;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===sa)break;r.set(t,this.getObj(e))}if(this.buf1===sa){if(this.recoveryMode)return r;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(r,e):r;this.shift();return r;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,a=e.pos;let r,i,n=0;for(;-1!==(r=e.getByte());)if(0===n)n=69===r?1:0;else if(1===n)n=73===r?2:0;else if(32===r||10===r||13===r){i=e.pos;const a=e.peekBytes(15),s=a.length;if(0===s)break;for(let e=0;e127))){n=0;break}}if(2!==n)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const o=new Lexer(new Stream(e.peekBytes(75)),t);o._hexStringWarn=()=>{};let c=0;for(;;){const e=o.getObj();if(e===sa){n=0;break}if(e instanceof Cmd){const a=t[e.cmd];if(!a){n=0;break}if(a.variableArgs?c<=a.numArgs:c===a.numArgs)break;c=0;continue}c++}if(2===n)break}else n=0;if(-1===r){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(i){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-i))}}let s=4;e.skip(-s);r=e.peekByte();e.skip(s);isWhiteSpace(r)||s--;return e.pos-s-a}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let a,r,i=!1;for(;-1!==(a=e.getByte());)if(255===a){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:i=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:r=e.getUint16();r>2?e.skip(r-2):e.skip(-2)}if(i)break}const n=e.pos-t;if(-1===a){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-n);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return n}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte());)if(126===a){const t=e.pos;a=e.peekByte();for(;isWhiteSpace(a);){e.skip();a=e.peekByte()}if(62===a){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const r=e.pos-t;if(-1===a){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte())&&62!==a;);const r=e.pos-t;if(-1===a){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}inlineStreamSkipEI(e){let t,a=0;for(;-1!==(t=e.getByte());)if(0===a)a=69===t?1:0;else if(1===a)a=73===t?2:0;else if(2===a)break}makeInlineImage(e){const t=this.lexer,a=t.stream,r=Object.create(null);let i;for(;!isCmd(this.buf1,"ID")&&this.buf1!==sa;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===sa)break;r[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(i=a.pos-t.beginInlineImagePos);const n=this.xref.fetchIfRef(r.F||r.Filter);let s;if(n instanceof Name)s=n.name;else if(Array.isArray(n)){const e=this.xref.fetchIfRef(n[0]);e instanceof Name&&(s=e.name)}const o=a.pos;let c,l;switch(s){case"DCT":case"DCTDecode":c=this.findDCTDecodeInlineStreamEnd(a);break;case"A85":case"ASCII85Decode":c=this.findASCII85DecodeInlineStreamEnd(a);break;case"AHx":case"ASCIIHexDecode":c=this.findASCIIHexDecodeInlineStreamEnd(a);break;default:c=this.findDefaultInlineStreamEnd(a)}if(c<1e3&&i>0){const e=a.pos;a.pos=t.beginInlineImagePos;l=function getInlineImageCacheKey(e){const t=[],a=e.length;let r=0;for(;r=r){let r=!1;for(const e of i){const t=e.length;let i=0;for(;i=n){r=!0;break}if(i>=t){if(isWhiteSpace(s[c+o+i])){info(`Found "${bytesToString([...a,...e])}" when searching for endstream command.`);r=!0}break}}if(r){t.pos+=c;return t.pos-e}}c++}t.pos+=o}return-1}makeStream(e,t){const a=this.lexer;let r=a.stream;a.skipToNextLine();const i=r.pos-1;let n=e.get("Length");if(!Number.isInteger(n)){info(`Bad length "${n&&n.toString()}" in stream.`);n=0}r.pos=i+n;a.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{n=this.#q(i);if(n<0)throw new FormatError("Missing endstream command.");a.nextChar();this.shift();this.shift()}this.shift();r=r.makeSubStream(i,n,e);t&&(r=t.createStream(r,n));r=this.filter(r,e,n);r.dict=e;return r}filter(e,t,a){let r=t.get("F","Filter"),i=t.get("DP","DecodeParms");if(r instanceof Name){Array.isArray(i)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,r.name,a,i)}let n=a;if(Array.isArray(r)){const t=r,a=i;for(let s=0,o=t.length;s=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,a=0,r=1;if(45===e){r=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){a=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||40===e||60===e||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let i=e-48,n=0,s=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const r=e-48;if(t)n=10*n+r;else{0!==a&&(a*=10);i=10*i+r}}else if(46===e){if(0!==a)break;a=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){s=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==a&&(i/=a);t&&(i*=10**(s*n));return r*i}getString(){let e=1,t=!1;const a=this.strBuf;a.length=0;let r=this.nextChar();for(;;){let i=!1;switch(0|r){case-1:warn("Unterminated string");t=!0;break;case 40:++e;a.push("(");break;case 41:if(0===--e){this.nextChar();t=!0}else a.push(")");break;case 92:r=this.nextChar();switch(r){case-1:warn("Unterminated string");t=!0;break;case 110:a.push("\n");break;case 114:a.push("\r");break;case 116:a.push("\t");break;case 98:a.push("\b");break;case 102:a.push("\f");break;case 92:case 40:case 41:a.push(String.fromCharCode(r));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&r;r=this.nextChar();i=!0;if(r>=48&&r<=55){e=(e<<3)+(15&r);r=this.nextChar();if(r>=48&&r<=55){i=!1;e=(e<<3)+(15&r)}}a.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:a.push(String.fromCharCode(r))}break;default:a.push(String.fromCharCode(r))}if(t)break;i||(r=this.nextChar())}return a.join("")}getName(){let e,t;const a=this.strBuf;a.length=0;for(;(e=this.nextChar())>=0&&!rr[e];)if(35===e){e=this.nextChar();if(rr[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");a.push("#");break}const r=toHexDigit(e);if(-1!==r){t=e;e=this.nextChar();const i=toHexDigit(e);if(-1===i){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);a.push("#",String.fromCharCode(t));if(rr[e])break;a.push(String.fromCharCode(e));continue}a.push(String.fromCharCode(r<<4|i))}else a.push("#",String.fromCharCode(e))}else a.push(String.fromCharCode(e));a.length>127&&warn(`Name token is longer than allowed by the spec: ${a.length}`);return Name.get(a.join(""))}_hexStringWarn(e){5!==this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,a=-1,r=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==rr[t]){r=toHexDigit(t);if(-1===r)this._hexStringWarn(t);else if(-1===a)a=r;else{e.push(String.fromCharCode(a<<4|r));a=-1}t=this.nextChar()}else t=this.nextChar()}-1!==a&&e.push(String.fromCharCode(a<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return sa;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==rr[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let a=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(a)}}const r=this.knownCommands;let i=void 0!==r?.[a];for(;(t=this.nextChar())>=0&&!rr[t];){const e=a+String.fromCharCode(t);if(i&&void 0===r[e])break;if(128===a.length)throw new FormatError(`Command token too long: ${a.length}`);a=e;i=void 0!==r?.[a]}if("true"===a)return!0;if("false"===a)return!1;if("null"===a)return null;"BI"===a&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(a)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,a=!1){const r=e.get(t);if(Number.isInteger(r)&&(a?r>=0:r>0))return r;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),a=t.getObj(),r=t.getObj(),i=t.getObj(),n=t.getObj();let s,o;if(!(Number.isInteger(a)&&Number.isInteger(r)&&isCmd(i,"obj")&&n instanceof Dict&&"number"==typeof(s=n.get("Linearized"))&&s>0))return null;if((o=getInt(n,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:o,hints:function getHints(e){const t=e.get("H");let a;if(Array.isArray(t)&&(2===(a=t.length)||4===a)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(n),objectNumberFirst:getInt(n,"O"),endFirst:getInt(n,"E"),numPages:getInt(n,"N"),mainXRefEntriesOffset:getInt(n,"T"),pageFirst:n.has("P")?getInt(n,"P",!0):0}}}const ir=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],nr=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,a){this.codespaceRanges[e-1].push(t,a);this.numCodespaceRanges++}mapCidRange(e,t,a){if(t-e>nr)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=a++}mapBfRange(e,t,a){if(t-e>nr)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const r=a.length-1;for(;e<=t;){this._map[e++]=a;const t=a.charCodeAt(r)+1;t>255?a=a.substring(0,r-1)+String.fromCharCode(a.charCodeAt(r-1)+1)+"\0":a=a.substring(0,r)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,a){if(t-e>nr)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const r=a.length;let i=0;for(;e<=t&&i>>0;const s=i[n];for(let e=0,t=s.length;e=t&&r<=i){a.charcode=r;a.length=n+1;return}}}a.charcode=0;a.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let a=0,r=t.length;a=i&&e<=n)return a+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,a){unreachable("should not call mapCidRange")}mapBfRange(e,t,a){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,a){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let a=0;a>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endbfchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=a;e.mapOne(r,i)}}function parseBfRange(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endbfrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();if(Number.isInteger(a)||"string"==typeof a){const t=Number.isInteger(a)?String.fromCharCode(a):a;e.mapBfRange(r,i,t)}else{if(!isCmd(a,"["))break;{a=t.getObj();const n=[];for(;!isCmd(a,"]")&&a!==sa;){n.push(a);a=t.getObj()}e.mapBfRangeToArray(r,i,n)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endcidchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectInt(a);const i=a;e.mapOne(r,i)}}function parseCidRange(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endcidrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();expectInt(a);const n=a;e.mapCidRange(r,i,n)}}function parseCodespaceRange(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endcodespacerange"))return;if("string"!=typeof a)break;const r=strToInt(a);a=t.getObj();if("string"!=typeof a)break;const i=strToInt(a);e.addCodespaceRange(a.length,r,i)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const a=t.getObj();Number.isInteger(a)&&(e.vertical=!!a)}function parseCMapName(e,t){const a=t.getObj();a instanceof Name&&(e.name=a.name)}async function parseCMap(e,t,a,r){let i,n;e:for(;;)try{const a=t.getObj();if(a===sa)break;if(a instanceof Name){"WMode"===a.name?parseWMode(e,t):"CMapName"===a.name&&parseCMapName(e,t);i=a}else if(a instanceof Cmd)switch(a.cmd){case"endcmap":break e;case"usecmap":i instanceof Name&&(n=i.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!r&&n&&(r=n);return r?extendCMap(e,a,r):e}async function extendCMap(e,t,a){e.useCMap=await createBuiltInCMap(a,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let a=0;aextendCMap(i,t,e));const n=new Lexer(new Stream(a));return parseCMap(i,n,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:a}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const r=await parseCMap(new CMap,new Lexer(e),t,a);return r.isIdentityCMap?createBuiltInCMap(r.name,t):r}throw new Error("Encoding required.")}}const sr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],or=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],cr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],lr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],hr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],ur=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],dr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return hr;case"StandardEncoding":return lr;case"MacRomanEncoding":return cr;case"SymbolSetEncoding":return ur;case"ZapfDingbatsEncoding":return dr;case"ExpertEncoding":return sr;case"MacExpertEncoding":return or;default:return null}}const fr=getLookupTableFactory(function(e){e.A=65;e.AE=198;e.AEacute=508;e.AEmacron=482;e.AEsmall=63462;e.Aacute=193;e.Aacutesmall=63457;e.Abreve=258;e.Abreveacute=7854;e.Abrevecyrillic=1232;e.Abrevedotbelow=7862;e.Abrevegrave=7856;e.Abrevehookabove=7858;e.Abrevetilde=7860;e.Acaron=461;e.Acircle=9398;e.Acircumflex=194;e.Acircumflexacute=7844;e.Acircumflexdotbelow=7852;e.Acircumflexgrave=7846;e.Acircumflexhookabove=7848;e.Acircumflexsmall=63458;e.Acircumflextilde=7850;e.Acute=63177;e.Acutesmall=63412;e.Acyrillic=1040;e.Adblgrave=512;e.Adieresis=196;e.Adieresiscyrillic=1234;e.Adieresismacron=478;e.Adieresissmall=63460;e.Adotbelow=7840;e.Adotmacron=480;e.Agrave=192;e.Agravesmall=63456;e.Ahookabove=7842;e.Aiecyrillic=1236;e.Ainvertedbreve=514;e.Alpha=913;e.Alphatonos=902;e.Amacron=256;e.Amonospace=65313;e.Aogonek=260;e.Aring=197;e.Aringacute=506;e.Aringbelow=7680;e.Aringsmall=63461;e.Asmall=63329;e.Atilde=195;e.Atildesmall=63459;e.Aybarmenian=1329;e.B=66;e.Bcircle=9399;e.Bdotaccent=7682;e.Bdotbelow=7684;e.Becyrillic=1041;e.Benarmenian=1330;e.Beta=914;e.Bhook=385;e.Blinebelow=7686;e.Bmonospace=65314;e.Brevesmall=63220;e.Bsmall=63330;e.Btopbar=386;e.C=67;e.Caarmenian=1342;e.Cacute=262;e.Caron=63178;e.Caronsmall=63221;e.Ccaron=268;e.Ccedilla=199;e.Ccedillaacute=7688;e.Ccedillasmall=63463;e.Ccircle=9400;e.Ccircumflex=264;e.Cdot=266;e.Cdotaccent=266;e.Cedillasmall=63416;e.Chaarmenian=1353;e.Cheabkhasiancyrillic=1212;e.Checyrillic=1063;e.Chedescenderabkhasiancyrillic=1214;e.Chedescendercyrillic=1206;e.Chedieresiscyrillic=1268;e.Cheharmenian=1347;e.Chekhakassiancyrillic=1227;e.Cheverticalstrokecyrillic=1208;e.Chi=935;e.Chook=391;e.Circumflexsmall=63222;e.Cmonospace=65315;e.Coarmenian=1361;e.Csmall=63331;e.D=68;e.DZ=497;e.DZcaron=452;e.Daarmenian=1332;e.Dafrican=393;e.Dcaron=270;e.Dcedilla=7696;e.Dcircle=9401;e.Dcircumflexbelow=7698;e.Dcroat=272;e.Ddotaccent=7690;e.Ddotbelow=7692;e.Decyrillic=1044;e.Deicoptic=1006;e.Delta=8710;e.Deltagreek=916;e.Dhook=394;e.Dieresis=63179;e.DieresisAcute=63180;e.DieresisGrave=63181;e.Dieresissmall=63400;e.Digammagreek=988;e.Djecyrillic=1026;e.Dlinebelow=7694;e.Dmonospace=65316;e.Dotaccentsmall=63223;e.Dslash=272;e.Dsmall=63332;e.Dtopbar=395;e.Dz=498;e.Dzcaron=453;e.Dzeabkhasiancyrillic=1248;e.Dzecyrillic=1029;e.Dzhecyrillic=1039;e.E=69;e.Eacute=201;e.Eacutesmall=63465;e.Ebreve=276;e.Ecaron=282;e.Ecedillabreve=7708;e.Echarmenian=1333;e.Ecircle=9402;e.Ecircumflex=202;e.Ecircumflexacute=7870;e.Ecircumflexbelow=7704;e.Ecircumflexdotbelow=7878;e.Ecircumflexgrave=7872;e.Ecircumflexhookabove=7874;e.Ecircumflexsmall=63466;e.Ecircumflextilde=7876;e.Ecyrillic=1028;e.Edblgrave=516;e.Edieresis=203;e.Edieresissmall=63467;e.Edot=278;e.Edotaccent=278;e.Edotbelow=7864;e.Efcyrillic=1060;e.Egrave=200;e.Egravesmall=63464;e.Eharmenian=1335;e.Ehookabove=7866;e.Eightroman=8551;e.Einvertedbreve=518;e.Eiotifiedcyrillic=1124;e.Elcyrillic=1051;e.Elevenroman=8554;e.Emacron=274;e.Emacronacute=7702;e.Emacrongrave=7700;e.Emcyrillic=1052;e.Emonospace=65317;e.Encyrillic=1053;e.Endescendercyrillic=1186;e.Eng=330;e.Enghecyrillic=1188;e.Enhookcyrillic=1223;e.Eogonek=280;e.Eopen=400;e.Epsilon=917;e.Epsilontonos=904;e.Ercyrillic=1056;e.Ereversed=398;e.Ereversedcyrillic=1069;e.Escyrillic=1057;e.Esdescendercyrillic=1194;e.Esh=425;e.Esmall=63333;e.Eta=919;e.Etarmenian=1336;e.Etatonos=905;e.Eth=208;e.Ethsmall=63472;e.Etilde=7868;e.Etildebelow=7706;e.Euro=8364;e.Ezh=439;e.Ezhcaron=494;e.Ezhreversed=440;e.F=70;e.Fcircle=9403;e.Fdotaccent=7710;e.Feharmenian=1366;e.Feicoptic=996;e.Fhook=401;e.Fitacyrillic=1138;e.Fiveroman=8548;e.Fmonospace=65318;e.Fourroman=8547;e.Fsmall=63334;e.G=71;e.GBsquare=13191;e.Gacute=500;e.Gamma=915;e.Gammaafrican=404;e.Gangiacoptic=1002;e.Gbreve=286;e.Gcaron=486;e.Gcedilla=290;e.Gcircle=9404;e.Gcircumflex=284;e.Gcommaaccent=290;e.Gdot=288;e.Gdotaccent=288;e.Gecyrillic=1043;e.Ghadarmenian=1346;e.Ghemiddlehookcyrillic=1172;e.Ghestrokecyrillic=1170;e.Gheupturncyrillic=1168;e.Ghook=403;e.Gimarmenian=1331;e.Gjecyrillic=1027;e.Gmacron=7712;e.Gmonospace=65319;e.Grave=63182;e.Gravesmall=63328;e.Gsmall=63335;e.Gsmallhook=667;e.Gstroke=484;e.H=72;e.H18533=9679;e.H18543=9642;e.H18551=9643;e.H22073=9633;e.HPsquare=13259;e.Haabkhasiancyrillic=1192;e.Hadescendercyrillic=1202;e.Hardsigncyrillic=1066;e.Hbar=294;e.Hbrevebelow=7722;e.Hcedilla=7720;e.Hcircle=9405;e.Hcircumflex=292;e.Hdieresis=7718;e.Hdotaccent=7714;e.Hdotbelow=7716;e.Hmonospace=65320;e.Hoarmenian=1344;e.Horicoptic=1e3;e.Hsmall=63336;e.Hungarumlaut=63183;e.Hungarumlautsmall=63224;e.Hzsquare=13200;e.I=73;e.IAcyrillic=1071;e.IJ=306;e.IUcyrillic=1070;e.Iacute=205;e.Iacutesmall=63469;e.Ibreve=300;e.Icaron=463;e.Icircle=9406;e.Icircumflex=206;e.Icircumflexsmall=63470;e.Icyrillic=1030;e.Idblgrave=520;e.Idieresis=207;e.Idieresisacute=7726;e.Idieresiscyrillic=1252;e.Idieresissmall=63471;e.Idot=304;e.Idotaccent=304;e.Idotbelow=7882;e.Iebrevecyrillic=1238;e.Iecyrillic=1045;e.Ifraktur=8465;e.Igrave=204;e.Igravesmall=63468;e.Ihookabove=7880;e.Iicyrillic=1048;e.Iinvertedbreve=522;e.Iishortcyrillic=1049;e.Imacron=298;e.Imacroncyrillic=1250;e.Imonospace=65321;e.Iniarmenian=1339;e.Iocyrillic=1025;e.Iogonek=302;e.Iota=921;e.Iotaafrican=406;e.Iotadieresis=938;e.Iotatonos=906;e.Ismall=63337;e.Istroke=407;e.Itilde=296;e.Itildebelow=7724;e.Izhitsacyrillic=1140;e.Izhitsadblgravecyrillic=1142;e.J=74;e.Jaarmenian=1345;e.Jcircle=9407;e.Jcircumflex=308;e.Jecyrillic=1032;e.Jheharmenian=1355;e.Jmonospace=65322;e.Jsmall=63338;e.K=75;e.KBsquare=13189;e.KKsquare=13261;e.Kabashkircyrillic=1184;e.Kacute=7728;e.Kacyrillic=1050;e.Kadescendercyrillic=1178;e.Kahookcyrillic=1219;e.Kappa=922;e.Kastrokecyrillic=1182;e.Kaverticalstrokecyrillic=1180;e.Kcaron=488;e.Kcedilla=310;e.Kcircle=9408;e.Kcommaaccent=310;e.Kdotbelow=7730;e.Keharmenian=1364;e.Kenarmenian=1343;e.Khacyrillic=1061;e.Kheicoptic=998;e.Khook=408;e.Kjecyrillic=1036;e.Klinebelow=7732;e.Kmonospace=65323;e.Koppacyrillic=1152;e.Koppagreek=990;e.Ksicyrillic=1134;e.Ksmall=63339;e.L=76;e.LJ=455;e.LL=63167;e.Lacute=313;e.Lambda=923;e.Lcaron=317;e.Lcedilla=315;e.Lcircle=9409;e.Lcircumflexbelow=7740;e.Lcommaaccent=315;e.Ldot=319;e.Ldotaccent=319;e.Ldotbelow=7734;e.Ldotbelowmacron=7736;e.Liwnarmenian=1340;e.Lj=456;e.Ljecyrillic=1033;e.Llinebelow=7738;e.Lmonospace=65324;e.Lslash=321;e.Lslashsmall=63225;e.Lsmall=63340;e.M=77;e.MBsquare=13190;e.Macron=63184;e.Macronsmall=63407;e.Macute=7742;e.Mcircle=9410;e.Mdotaccent=7744;e.Mdotbelow=7746;e.Menarmenian=1348;e.Mmonospace=65325;e.Msmall=63341;e.Mturned=412;e.Mu=924;e.N=78;e.NJ=458;e.Nacute=323;e.Ncaron=327;e.Ncedilla=325;e.Ncircle=9411;e.Ncircumflexbelow=7754;e.Ncommaaccent=325;e.Ndotaccent=7748;e.Ndotbelow=7750;e.Nhookleft=413;e.Nineroman=8552;e.Nj=459;e.Njecyrillic=1034;e.Nlinebelow=7752;e.Nmonospace=65326;e.Nowarmenian=1350;e.Nsmall=63342;e.Ntilde=209;e.Ntildesmall=63473;e.Nu=925;e.O=79;e.OE=338;e.OEsmall=63226;e.Oacute=211;e.Oacutesmall=63475;e.Obarredcyrillic=1256;e.Obarreddieresiscyrillic=1258;e.Obreve=334;e.Ocaron=465;e.Ocenteredtilde=415;e.Ocircle=9412;e.Ocircumflex=212;e.Ocircumflexacute=7888;e.Ocircumflexdotbelow=7896;e.Ocircumflexgrave=7890;e.Ocircumflexhookabove=7892;e.Ocircumflexsmall=63476;e.Ocircumflextilde=7894;e.Ocyrillic=1054;e.Odblacute=336;e.Odblgrave=524;e.Odieresis=214;e.Odieresiscyrillic=1254;e.Odieresissmall=63478;e.Odotbelow=7884;e.Ogoneksmall=63227;e.Ograve=210;e.Ogravesmall=63474;e.Oharmenian=1365;e.Ohm=8486;e.Ohookabove=7886;e.Ohorn=416;e.Ohornacute=7898;e.Ohorndotbelow=7906;e.Ohorngrave=7900;e.Ohornhookabove=7902;e.Ohorntilde=7904;e.Ohungarumlaut=336;e.Oi=418;e.Oinvertedbreve=526;e.Omacron=332;e.Omacronacute=7762;e.Omacrongrave=7760;e.Omega=8486;e.Omegacyrillic=1120;e.Omegagreek=937;e.Omegaroundcyrillic=1146;e.Omegatitlocyrillic=1148;e.Omegatonos=911;e.Omicron=927;e.Omicrontonos=908;e.Omonospace=65327;e.Oneroman=8544;e.Oogonek=490;e.Oogonekmacron=492;e.Oopen=390;e.Oslash=216;e.Oslashacute=510;e.Oslashsmall=63480;e.Osmall=63343;e.Ostrokeacute=510;e.Otcyrillic=1150;e.Otilde=213;e.Otildeacute=7756;e.Otildedieresis=7758;e.Otildesmall=63477;e.P=80;e.Pacute=7764;e.Pcircle=9413;e.Pdotaccent=7766;e.Pecyrillic=1055;e.Peharmenian=1354;e.Pemiddlehookcyrillic=1190;e.Phi=934;e.Phook=420;e.Pi=928;e.Piwrarmenian=1363;e.Pmonospace=65328;e.Psi=936;e.Psicyrillic=1136;e.Psmall=63344;e.Q=81;e.Qcircle=9414;e.Qmonospace=65329;e.Qsmall=63345;e.R=82;e.Raarmenian=1356;e.Racute=340;e.Rcaron=344;e.Rcedilla=342;e.Rcircle=9415;e.Rcommaaccent=342;e.Rdblgrave=528;e.Rdotaccent=7768;e.Rdotbelow=7770;e.Rdotbelowmacron=7772;e.Reharmenian=1360;e.Rfraktur=8476;e.Rho=929;e.Ringsmall=63228;e.Rinvertedbreve=530;e.Rlinebelow=7774;e.Rmonospace=65330;e.Rsmall=63346;e.Rsmallinverted=641;e.Rsmallinvertedsuperior=694;e.S=83;e.SF010000=9484;e.SF020000=9492;e.SF030000=9488;e.SF040000=9496;e.SF050000=9532;e.SF060000=9516;e.SF070000=9524;e.SF080000=9500;e.SF090000=9508;e.SF100000=9472;e.SF110000=9474;e.SF190000=9569;e.SF200000=9570;e.SF210000=9558;e.SF220000=9557;e.SF230000=9571;e.SF240000=9553;e.SF250000=9559;e.SF260000=9565;e.SF270000=9564;e.SF280000=9563;e.SF360000=9566;e.SF370000=9567;e.SF380000=9562;e.SF390000=9556;e.SF400000=9577;e.SF410000=9574;e.SF420000=9568;e.SF430000=9552;e.SF440000=9580;e.SF450000=9575;e.SF460000=9576;e.SF470000=9572;e.SF480000=9573;e.SF490000=9561;e.SF500000=9560;e.SF510000=9554;e.SF520000=9555;e.SF530000=9579;e.SF540000=9578;e.Sacute=346;e.Sacutedotaccent=7780;e.Sampigreek=992;e.Scaron=352;e.Scarondotaccent=7782;e.Scaronsmall=63229;e.Scedilla=350;e.Schwa=399;e.Schwacyrillic=1240;e.Schwadieresiscyrillic=1242;e.Scircle=9416;e.Scircumflex=348;e.Scommaaccent=536;e.Sdotaccent=7776;e.Sdotbelow=7778;e.Sdotbelowdotaccent=7784;e.Seharmenian=1357;e.Sevenroman=8550;e.Shaarmenian=1351;e.Shacyrillic=1064;e.Shchacyrillic=1065;e.Sheicoptic=994;e.Shhacyrillic=1210;e.Shimacoptic=1004;e.Sigma=931;e.Sixroman=8549;e.Smonospace=65331;e.Softsigncyrillic=1068;e.Ssmall=63347;e.Stigmagreek=986;e.T=84;e.Tau=932;e.Tbar=358;e.Tcaron=356;e.Tcedilla=354;e.Tcircle=9417;e.Tcircumflexbelow=7792;e.Tcommaaccent=354;e.Tdotaccent=7786;e.Tdotbelow=7788;e.Tecyrillic=1058;e.Tedescendercyrillic=1196;e.Tenroman=8553;e.Tetsecyrillic=1204;e.Theta=920;e.Thook=428;e.Thorn=222;e.Thornsmall=63486;e.Threeroman=8546;e.Tildesmall=63230;e.Tiwnarmenian=1359;e.Tlinebelow=7790;e.Tmonospace=65332;e.Toarmenian=1337;e.Tonefive=444;e.Tonesix=388;e.Tonetwo=423;e.Tretroflexhook=430;e.Tsecyrillic=1062;e.Tshecyrillic=1035;e.Tsmall=63348;e.Twelveroman=8555;e.Tworoman=8545;e.U=85;e.Uacute=218;e.Uacutesmall=63482;e.Ubreve=364;e.Ucaron=467;e.Ucircle=9418;e.Ucircumflex=219;e.Ucircumflexbelow=7798;e.Ucircumflexsmall=63483;e.Ucyrillic=1059;e.Udblacute=368;e.Udblgrave=532;e.Udieresis=220;e.Udieresisacute=471;e.Udieresisbelow=7794;e.Udieresiscaron=473;e.Udieresiscyrillic=1264;e.Udieresisgrave=475;e.Udieresismacron=469;e.Udieresissmall=63484;e.Udotbelow=7908;e.Ugrave=217;e.Ugravesmall=63481;e.Uhookabove=7910;e.Uhorn=431;e.Uhornacute=7912;e.Uhorndotbelow=7920;e.Uhorngrave=7914;e.Uhornhookabove=7916;e.Uhorntilde=7918;e.Uhungarumlaut=368;e.Uhungarumlautcyrillic=1266;e.Uinvertedbreve=534;e.Ukcyrillic=1144;e.Umacron=362;e.Umacroncyrillic=1262;e.Umacrondieresis=7802;e.Umonospace=65333;e.Uogonek=370;e.Upsilon=933;e.Upsilon1=978;e.Upsilonacutehooksymbolgreek=979;e.Upsilonafrican=433;e.Upsilondieresis=939;e.Upsilondieresishooksymbolgreek=980;e.Upsilonhooksymbol=978;e.Upsilontonos=910;e.Uring=366;e.Ushortcyrillic=1038;e.Usmall=63349;e.Ustraightcyrillic=1198;e.Ustraightstrokecyrillic=1200;e.Utilde=360;e.Utildeacute=7800;e.Utildebelow=7796;e.V=86;e.Vcircle=9419;e.Vdotbelow=7806;e.Vecyrillic=1042;e.Vewarmenian=1358;e.Vhook=434;e.Vmonospace=65334;e.Voarmenian=1352;e.Vsmall=63350;e.Vtilde=7804;e.W=87;e.Wacute=7810;e.Wcircle=9420;e.Wcircumflex=372;e.Wdieresis=7812;e.Wdotaccent=7814;e.Wdotbelow=7816;e.Wgrave=7808;e.Wmonospace=65335;e.Wsmall=63351;e.X=88;e.Xcircle=9421;e.Xdieresis=7820;e.Xdotaccent=7818;e.Xeharmenian=1341;e.Xi=926;e.Xmonospace=65336;e.Xsmall=63352;e.Y=89;e.Yacute=221;e.Yacutesmall=63485;e.Yatcyrillic=1122;e.Ycircle=9422;e.Ycircumflex=374;e.Ydieresis=376;e.Ydieresissmall=63487;e.Ydotaccent=7822;e.Ydotbelow=7924;e.Yericyrillic=1067;e.Yerudieresiscyrillic=1272;e.Ygrave=7922;e.Yhook=435;e.Yhookabove=7926;e.Yiarmenian=1349;e.Yicyrillic=1031;e.Yiwnarmenian=1362;e.Ymonospace=65337;e.Ysmall=63353;e.Ytilde=7928;e.Yusbigcyrillic=1130;e.Yusbigiotifiedcyrillic=1132;e.Yuslittlecyrillic=1126;e.Yuslittleiotifiedcyrillic=1128;e.Z=90;e.Zaarmenian=1334;e.Zacute=377;e.Zcaron=381;e.Zcaronsmall=63231;e.Zcircle=9423;e.Zcircumflex=7824;e.Zdot=379;e.Zdotaccent=379;e.Zdotbelow=7826;e.Zecyrillic=1047;e.Zedescendercyrillic=1176;e.Zedieresiscyrillic=1246;e.Zeta=918;e.Zhearmenian=1338;e.Zhebrevecyrillic=1217;e.Zhecyrillic=1046;e.Zhedescendercyrillic=1174;e.Zhedieresiscyrillic=1244;e.Zlinebelow=7828;e.Zmonospace=65338;e.Zsmall=63354;e.Zstroke=437;e.a=97;e.aabengali=2438;e.aacute=225;e.aadeva=2310;e.aagujarati=2694;e.aagurmukhi=2566;e.aamatragurmukhi=2622;e.aarusquare=13059;e.aavowelsignbengali=2494;e.aavowelsigndeva=2366;e.aavowelsigngujarati=2750;e.abbreviationmarkarmenian=1375;e.abbreviationsigndeva=2416;e.abengali=2437;e.abopomofo=12570;e.abreve=259;e.abreveacute=7855;e.abrevecyrillic=1233;e.abrevedotbelow=7863;e.abrevegrave=7857;e.abrevehookabove=7859;e.abrevetilde=7861;e.acaron=462;e.acircle=9424;e.acircumflex=226;e.acircumflexacute=7845;e.acircumflexdotbelow=7853;e.acircumflexgrave=7847;e.acircumflexhookabove=7849;e.acircumflextilde=7851;e.acute=180;e.acutebelowcmb=791;e.acutecmb=769;e.acutecomb=769;e.acutedeva=2388;e.acutelowmod=719;e.acutetonecmb=833;e.acyrillic=1072;e.adblgrave=513;e.addakgurmukhi=2673;e.adeva=2309;e.adieresis=228;e.adieresiscyrillic=1235;e.adieresismacron=479;e.adotbelow=7841;e.adotmacron=481;e.ae=230;e.aeacute=509;e.aekorean=12624;e.aemacron=483;e.afii00208=8213;e.afii08941=8356;e.afii10017=1040;e.afii10018=1041;e.afii10019=1042;e.afii10020=1043;e.afii10021=1044;e.afii10022=1045;e.afii10023=1025;e.afii10024=1046;e.afii10025=1047;e.afii10026=1048;e.afii10027=1049;e.afii10028=1050;e.afii10029=1051;e.afii10030=1052;e.afii10031=1053;e.afii10032=1054;e.afii10033=1055;e.afii10034=1056;e.afii10035=1057;e.afii10036=1058;e.afii10037=1059;e.afii10038=1060;e.afii10039=1061;e.afii10040=1062;e.afii10041=1063;e.afii10042=1064;e.afii10043=1065;e.afii10044=1066;e.afii10045=1067;e.afii10046=1068;e.afii10047=1069;e.afii10048=1070;e.afii10049=1071;e.afii10050=1168;e.afii10051=1026;e.afii10052=1027;e.afii10053=1028;e.afii10054=1029;e.afii10055=1030;e.afii10056=1031;e.afii10057=1032;e.afii10058=1033;e.afii10059=1034;e.afii10060=1035;e.afii10061=1036;e.afii10062=1038;e.afii10063=63172;e.afii10064=63173;e.afii10065=1072;e.afii10066=1073;e.afii10067=1074;e.afii10068=1075;e.afii10069=1076;e.afii10070=1077;e.afii10071=1105;e.afii10072=1078;e.afii10073=1079;e.afii10074=1080;e.afii10075=1081;e.afii10076=1082;e.afii10077=1083;e.afii10078=1084;e.afii10079=1085;e.afii10080=1086;e.afii10081=1087;e.afii10082=1088;e.afii10083=1089;e.afii10084=1090;e.afii10085=1091;e.afii10086=1092;e.afii10087=1093;e.afii10088=1094;e.afii10089=1095;e.afii10090=1096;e.afii10091=1097;e.afii10092=1098;e.afii10093=1099;e.afii10094=1100;e.afii10095=1101;e.afii10096=1102;e.afii10097=1103;e.afii10098=1169;e.afii10099=1106;e.afii10100=1107;e.afii10101=1108;e.afii10102=1109;e.afii10103=1110;e.afii10104=1111;e.afii10105=1112;e.afii10106=1113;e.afii10107=1114;e.afii10108=1115;e.afii10109=1116;e.afii10110=1118;e.afii10145=1039;e.afii10146=1122;e.afii10147=1138;e.afii10148=1140;e.afii10192=63174;e.afii10193=1119;e.afii10194=1123;e.afii10195=1139;e.afii10196=1141;e.afii10831=63175;e.afii10832=63176;e.afii10846=1241;e.afii299=8206;e.afii300=8207;e.afii301=8205;e.afii57381=1642;e.afii57388=1548;e.afii57392=1632;e.afii57393=1633;e.afii57394=1634;e.afii57395=1635;e.afii57396=1636;e.afii57397=1637;e.afii57398=1638;e.afii57399=1639;e.afii57400=1640;e.afii57401=1641;e.afii57403=1563;e.afii57407=1567;e.afii57409=1569;e.afii57410=1570;e.afii57411=1571;e.afii57412=1572;e.afii57413=1573;e.afii57414=1574;e.afii57415=1575;e.afii57416=1576;e.afii57417=1577;e.afii57418=1578;e.afii57419=1579;e.afii57420=1580;e.afii57421=1581;e.afii57422=1582;e.afii57423=1583;e.afii57424=1584;e.afii57425=1585;e.afii57426=1586;e.afii57427=1587;e.afii57428=1588;e.afii57429=1589;e.afii57430=1590;e.afii57431=1591;e.afii57432=1592;e.afii57433=1593;e.afii57434=1594;e.afii57440=1600;e.afii57441=1601;e.afii57442=1602;e.afii57443=1603;e.afii57444=1604;e.afii57445=1605;e.afii57446=1606;e.afii57448=1608;e.afii57449=1609;e.afii57450=1610;e.afii57451=1611;e.afii57452=1612;e.afii57453=1613;e.afii57454=1614;e.afii57455=1615;e.afii57456=1616;e.afii57457=1617;e.afii57458=1618;e.afii57470=1607;e.afii57505=1700;e.afii57506=1662;e.afii57507=1670;e.afii57508=1688;e.afii57509=1711;e.afii57511=1657;e.afii57512=1672;e.afii57513=1681;e.afii57514=1722;e.afii57519=1746;e.afii57534=1749;e.afii57636=8362;e.afii57645=1470;e.afii57658=1475;e.afii57664=1488;e.afii57665=1489;e.afii57666=1490;e.afii57667=1491;e.afii57668=1492;e.afii57669=1493;e.afii57670=1494;e.afii57671=1495;e.afii57672=1496;e.afii57673=1497;e.afii57674=1498;e.afii57675=1499;e.afii57676=1500;e.afii57677=1501;e.afii57678=1502;e.afii57679=1503;e.afii57680=1504;e.afii57681=1505;e.afii57682=1506;e.afii57683=1507;e.afii57684=1508;e.afii57685=1509;e.afii57686=1510;e.afii57687=1511;e.afii57688=1512;e.afii57689=1513;e.afii57690=1514;e.afii57694=64298;e.afii57695=64299;e.afii57700=64331;e.afii57705=64287;e.afii57716=1520;e.afii57717=1521;e.afii57718=1522;e.afii57723=64309;e.afii57793=1460;e.afii57794=1461;e.afii57795=1462;e.afii57796=1467;e.afii57797=1464;e.afii57798=1463;e.afii57799=1456;e.afii57800=1458;e.afii57801=1457;e.afii57802=1459;e.afii57803=1474;e.afii57804=1473;e.afii57806=1465;e.afii57807=1468;e.afii57839=1469;e.afii57841=1471;e.afii57842=1472;e.afii57929=700;e.afii61248=8453;e.afii61289=8467;e.afii61352=8470;e.afii61573=8236;e.afii61574=8237;e.afii61575=8238;e.afii61664=8204;e.afii63167=1645;e.afii64937=701;e.agrave=224;e.agujarati=2693;e.agurmukhi=2565;e.ahiragana=12354;e.ahookabove=7843;e.aibengali=2448;e.aibopomofo=12574;e.aideva=2320;e.aiecyrillic=1237;e.aigujarati=2704;e.aigurmukhi=2576;e.aimatragurmukhi=2632;e.ainarabic=1593;e.ainfinalarabic=65226;e.aininitialarabic=65227;e.ainmedialarabic=65228;e.ainvertedbreve=515;e.aivowelsignbengali=2504;e.aivowelsigndeva=2376;e.aivowelsigngujarati=2760;e.akatakana=12450;e.akatakanahalfwidth=65393;e.akorean=12623;e.alef=1488;e.alefarabic=1575;e.alefdageshhebrew=64304;e.aleffinalarabic=65166;e.alefhamzaabovearabic=1571;e.alefhamzaabovefinalarabic=65156;e.alefhamzabelowarabic=1573;e.alefhamzabelowfinalarabic=65160;e.alefhebrew=1488;e.aleflamedhebrew=64335;e.alefmaddaabovearabic=1570;e.alefmaddaabovefinalarabic=65154;e.alefmaksuraarabic=1609;e.alefmaksurafinalarabic=65264;e.alefmaksurainitialarabic=65267;e.alefmaksuramedialarabic=65268;e.alefpatahhebrew=64302;e.alefqamatshebrew=64303;e.aleph=8501;e.allequal=8780;e.alpha=945;e.alphatonos=940;e.amacron=257;e.amonospace=65345;e.ampersand=38;e.ampersandmonospace=65286;e.ampersandsmall=63270;e.amsquare=13250;e.anbopomofo=12578;e.angbopomofo=12580;e.angbracketleft=12296;e.angbracketright=12297;e.angkhankhuthai=3674;e.angle=8736;e.anglebracketleft=12296;e.anglebracketleftvertical=65087;e.anglebracketright=12297;e.anglebracketrightvertical=65088;e.angleleft=9001;e.angleright=9002;e.angstrom=8491;e.anoteleia=903;e.anudattadeva=2386;e.anusvarabengali=2434;e.anusvaradeva=2306;e.anusvaragujarati=2690;e.aogonek=261;e.apaatosquare=13056;e.aparen=9372;e.apostrophearmenian=1370;e.apostrophemod=700;e.apple=63743;e.approaches=8784;e.approxequal=8776;e.approxequalorimage=8786;e.approximatelyequal=8773;e.araeaekorean=12686;e.araeakorean=12685;e.arc=8978;e.arighthalfring=7834;e.aring=229;e.aringacute=507;e.aringbelow=7681;e.arrowboth=8596;e.arrowdashdown=8675;e.arrowdashleft=8672;e.arrowdashright=8674;e.arrowdashup=8673;e.arrowdblboth=8660;e.arrowdbldown=8659;e.arrowdblleft=8656;e.arrowdblright=8658;e.arrowdblup=8657;e.arrowdown=8595;e.arrowdownleft=8601;e.arrowdownright=8600;e.arrowdownwhite=8681;e.arrowheaddownmod=709;e.arrowheadleftmod=706;e.arrowheadrightmod=707;e.arrowheadupmod=708;e.arrowhorizex=63719;e.arrowleft=8592;e.arrowleftdbl=8656;e.arrowleftdblstroke=8653;e.arrowleftoverright=8646;e.arrowleftwhite=8678;e.arrowright=8594;e.arrowrightdblstroke=8655;e.arrowrightheavy=10142;e.arrowrightoverleft=8644;e.arrowrightwhite=8680;e.arrowtableft=8676;e.arrowtabright=8677;e.arrowup=8593;e.arrowupdn=8597;e.arrowupdnbse=8616;e.arrowupdownbase=8616;e.arrowupleft=8598;e.arrowupleftofdown=8645;e.arrowupright=8599;e.arrowupwhite=8679;e.arrowvertex=63718;e.asciicircum=94;e.asciicircummonospace=65342;e.asciitilde=126;e.asciitildemonospace=65374;e.ascript=593;e.ascriptturned=594;e.asmallhiragana=12353;e.asmallkatakana=12449;e.asmallkatakanahalfwidth=65383;e.asterisk=42;e.asteriskaltonearabic=1645;e.asteriskarabic=1645;e.asteriskmath=8727;e.asteriskmonospace=65290;e.asterisksmall=65121;e.asterism=8258;e.asuperior=63209;e.asymptoticallyequal=8771;e.at=64;e.atilde=227;e.atmonospace=65312;e.atsmall=65131;e.aturned=592;e.aubengali=2452;e.aubopomofo=12576;e.audeva=2324;e.augujarati=2708;e.augurmukhi=2580;e.aulengthmarkbengali=2519;e.aumatragurmukhi=2636;e.auvowelsignbengali=2508;e.auvowelsigndeva=2380;e.auvowelsigngujarati=2764;e.avagrahadeva=2365;e.aybarmenian=1377;e.ayin=1506;e.ayinaltonehebrew=64288;e.ayinhebrew=1506;e.b=98;e.babengali=2476;e.backslash=92;e.backslashmonospace=65340;e.badeva=2348;e.bagujarati=2732;e.bagurmukhi=2604;e.bahiragana=12400;e.bahtthai=3647;e.bakatakana=12496;e.bar=124;e.barmonospace=65372;e.bbopomofo=12549;e.bcircle=9425;e.bdotaccent=7683;e.bdotbelow=7685;e.beamedsixteenthnotes=9836;e.because=8757;e.becyrillic=1073;e.beharabic=1576;e.behfinalarabic=65168;e.behinitialarabic=65169;e.behiragana=12409;e.behmedialarabic=65170;e.behmeeminitialarabic=64671;e.behmeemisolatedarabic=64520;e.behnoonfinalarabic=64621;e.bekatakana=12505;e.benarmenian=1378;e.bet=1489;e.beta=946;e.betasymbolgreek=976;e.betdagesh=64305;e.betdageshhebrew=64305;e.bethebrew=1489;e.betrafehebrew=64332;e.bhabengali=2477;e.bhadeva=2349;e.bhagujarati=2733;e.bhagurmukhi=2605;e.bhook=595;e.bihiragana=12403;e.bikatakana=12499;e.bilabialclick=664;e.bindigurmukhi=2562;e.birusquare=13105;e.blackcircle=9679;e.blackdiamond=9670;e.blackdownpointingtriangle=9660;e.blackleftpointingpointer=9668;e.blackleftpointingtriangle=9664;e.blacklenticularbracketleft=12304;e.blacklenticularbracketleftvertical=65083;e.blacklenticularbracketright=12305;e.blacklenticularbracketrightvertical=65084;e.blacklowerlefttriangle=9699;e.blacklowerrighttriangle=9698;e.blackrectangle=9644;e.blackrightpointingpointer=9658;e.blackrightpointingtriangle=9654;e.blacksmallsquare=9642;e.blacksmilingface=9787;e.blacksquare=9632;e.blackstar=9733;e.blackupperlefttriangle=9700;e.blackupperrighttriangle=9701;e.blackuppointingsmalltriangle=9652;e.blackuppointingtriangle=9650;e.blank=9251;e.blinebelow=7687;e.block=9608;e.bmonospace=65346;e.bobaimaithai=3610;e.bohiragana=12412;e.bokatakana=12508;e.bparen=9373;e.bqsquare=13251;e.braceex=63732;e.braceleft=123;e.braceleftbt=63731;e.braceleftmid=63730;e.braceleftmonospace=65371;e.braceleftsmall=65115;e.bracelefttp=63729;e.braceleftvertical=65079;e.braceright=125;e.bracerightbt=63742;e.bracerightmid=63741;e.bracerightmonospace=65373;e.bracerightsmall=65116;e.bracerighttp=63740;e.bracerightvertical=65080;e.bracketleft=91;e.bracketleftbt=63728;e.bracketleftex=63727;e.bracketleftmonospace=65339;e.bracketlefttp=63726;e.bracketright=93;e.bracketrightbt=63739;e.bracketrightex=63738;e.bracketrightmonospace=65341;e.bracketrighttp=63737;e.breve=728;e.brevebelowcmb=814;e.brevecmb=774;e.breveinvertedbelowcmb=815;e.breveinvertedcmb=785;e.breveinverteddoublecmb=865;e.bridgebelowcmb=810;e.bridgeinvertedbelowcmb=826;e.brokenbar=166;e.bstroke=384;e.bsuperior=63210;e.btopbar=387;e.buhiragana=12406;e.bukatakana=12502;e.bullet=8226;e.bulletinverse=9688;e.bulletoperator=8729;e.bullseye=9678;e.c=99;e.caarmenian=1390;e.cabengali=2458;e.cacute=263;e.cadeva=2330;e.cagujarati=2714;e.cagurmukhi=2586;e.calsquare=13192;e.candrabindubengali=2433;e.candrabinducmb=784;e.candrabindudeva=2305;e.candrabindugujarati=2689;e.capslock=8682;e.careof=8453;e.caron=711;e.caronbelowcmb=812;e.caroncmb=780;e.carriagereturn=8629;e.cbopomofo=12568;e.ccaron=269;e.ccedilla=231;e.ccedillaacute=7689;e.ccircle=9426;e.ccircumflex=265;e.ccurl=597;e.cdot=267;e.cdotaccent=267;e.cdsquare=13253;e.cedilla=184;e.cedillacmb=807;e.cent=162;e.centigrade=8451;e.centinferior=63199;e.centmonospace=65504;e.centoldstyle=63394;e.centsuperior=63200;e.chaarmenian=1401;e.chabengali=2459;e.chadeva=2331;e.chagujarati=2715;e.chagurmukhi=2587;e.chbopomofo=12564;e.cheabkhasiancyrillic=1213;e.checkmark=10003;e.checyrillic=1095;e.chedescenderabkhasiancyrillic=1215;e.chedescendercyrillic=1207;e.chedieresiscyrillic=1269;e.cheharmenian=1395;e.chekhakassiancyrillic=1228;e.cheverticalstrokecyrillic=1209;e.chi=967;e.chieuchacirclekorean=12919;e.chieuchaparenkorean=12823;e.chieuchcirclekorean=12905;e.chieuchkorean=12618;e.chieuchparenkorean=12809;e.chochangthai=3594;e.chochanthai=3592;e.chochingthai=3593;e.chochoethai=3596;e.chook=392;e.cieucacirclekorean=12918;e.cieucaparenkorean=12822;e.cieuccirclekorean=12904;e.cieuckorean=12616;e.cieucparenkorean=12808;e.cieucuparenkorean=12828;e.circle=9675;e.circlecopyrt=169;e.circlemultiply=8855;e.circleot=8857;e.circleplus=8853;e.circlepostalmark=12342;e.circlewithlefthalfblack=9680;e.circlewithrighthalfblack=9681;e.circumflex=710;e.circumflexbelowcmb=813;e.circumflexcmb=770;e.clear=8999;e.clickalveolar=450;e.clickdental=448;e.clicklateral=449;e.clickretroflex=451;e.club=9827;e.clubsuitblack=9827;e.clubsuitwhite=9831;e.cmcubedsquare=13220;e.cmonospace=65347;e.cmsquaredsquare=13216;e.coarmenian=1409;e.colon=58;e.colonmonetary=8353;e.colonmonospace=65306;e.colonsign=8353;e.colonsmall=65109;e.colontriangularhalfmod=721;e.colontriangularmod=720;e.comma=44;e.commaabovecmb=787;e.commaaboverightcmb=789;e.commaaccent=63171;e.commaarabic=1548;e.commaarmenian=1373;e.commainferior=63201;e.commamonospace=65292;e.commareversedabovecmb=788;e.commareversedmod=701;e.commasmall=65104;e.commasuperior=63202;e.commaturnedabovecmb=786;e.commaturnedmod=699;e.compass=9788;e.congruent=8773;e.contourintegral=8750;e.control=8963;e.controlACK=6;e.controlBEL=7;e.controlBS=8;e.controlCAN=24;e.controlCR=13;e.controlDC1=17;e.controlDC2=18;e.controlDC3=19;e.controlDC4=20;e.controlDEL=127;e.controlDLE=16;e.controlEM=25;e.controlENQ=5;e.controlEOT=4;e.controlESC=27;e.controlETB=23;e.controlETX=3;e.controlFF=12;e.controlFS=28;e.controlGS=29;e.controlHT=9;e.controlLF=10;e.controlNAK=21;e.controlNULL=0;e.controlRS=30;e.controlSI=15;e.controlSO=14;e.controlSOT=2;e.controlSTX=1;e.controlSUB=26;e.controlSYN=22;e.controlUS=31;e.controlVT=11;e.copyright=169;e.copyrightsans=63721;e.copyrightserif=63193;e.cornerbracketleft=12300;e.cornerbracketlefthalfwidth=65378;e.cornerbracketleftvertical=65089;e.cornerbracketright=12301;e.cornerbracketrighthalfwidth=65379;e.cornerbracketrightvertical=65090;e.corporationsquare=13183;e.cosquare=13255;e.coverkgsquare=13254;e.cparen=9374;e.cruzeiro=8354;e.cstretched=663;e.curlyand=8911;e.curlyor=8910;e.currency=164;e.cyrBreve=63185;e.cyrFlex=63186;e.cyrbreve=63188;e.cyrflex=63189;e.d=100;e.daarmenian=1380;e.dabengali=2470;e.dadarabic=1590;e.dadeva=2342;e.dadfinalarabic=65214;e.dadinitialarabic=65215;e.dadmedialarabic=65216;e.dagesh=1468;e.dageshhebrew=1468;e.dagger=8224;e.daggerdbl=8225;e.dagujarati=2726;e.dagurmukhi=2598;e.dahiragana=12384;e.dakatakana=12480;e.dalarabic=1583;e.dalet=1491;e.daletdagesh=64307;e.daletdageshhebrew=64307;e.dalethebrew=1491;e.dalfinalarabic=65194;e.dammaarabic=1615;e.dammalowarabic=1615;e.dammatanaltonearabic=1612;e.dammatanarabic=1612;e.danda=2404;e.dargahebrew=1447;e.dargalefthebrew=1447;e.dasiapneumatacyrilliccmb=1157;e.dblGrave=63187;e.dblanglebracketleft=12298;e.dblanglebracketleftvertical=65085;e.dblanglebracketright=12299;e.dblanglebracketrightvertical=65086;e.dblarchinvertedbelowcmb=811;e.dblarrowleft=8660;e.dblarrowright=8658;e.dbldanda=2405;e.dblgrave=63190;e.dblgravecmb=783;e.dblintegral=8748;e.dbllowline=8215;e.dbllowlinecmb=819;e.dbloverlinecmb=831;e.dblprimemod=698;e.dblverticalbar=8214;e.dblverticallineabovecmb=782;e.dbopomofo=12553;e.dbsquare=13256;e.dcaron=271;e.dcedilla=7697;e.dcircle=9427;e.dcircumflexbelow=7699;e.dcroat=273;e.ddabengali=2465;e.ddadeva=2337;e.ddagujarati=2721;e.ddagurmukhi=2593;e.ddalarabic=1672;e.ddalfinalarabic=64393;e.dddhadeva=2396;e.ddhabengali=2466;e.ddhadeva=2338;e.ddhagujarati=2722;e.ddhagurmukhi=2594;e.ddotaccent=7691;e.ddotbelow=7693;e.decimalseparatorarabic=1643;e.decimalseparatorpersian=1643;e.decyrillic=1076;e.degree=176;e.dehihebrew=1453;e.dehiragana=12391;e.deicoptic=1007;e.dekatakana=12487;e.deleteleft=9003;e.deleteright=8998;e.delta=948;e.deltaturned=397;e.denominatorminusonenumeratorbengali=2552;e.dezh=676;e.dhabengali=2471;e.dhadeva=2343;e.dhagujarati=2727;e.dhagurmukhi=2599;e.dhook=599;e.dialytikatonos=901;e.dialytikatonoscmb=836;e.diamond=9830;e.diamondsuitwhite=9826;e.dieresis=168;e.dieresisacute=63191;e.dieresisbelowcmb=804;e.dieresiscmb=776;e.dieresisgrave=63192;e.dieresistonos=901;e.dihiragana=12386;e.dikatakana=12482;e.dittomark=12291;e.divide=247;e.divides=8739;e.divisionslash=8725;e.djecyrillic=1106;e.dkshade=9619;e.dlinebelow=7695;e.dlsquare=13207;e.dmacron=273;e.dmonospace=65348;e.dnblock=9604;e.dochadathai=3598;e.dodekthai=3604;e.dohiragana=12393;e.dokatakana=12489;e.dollar=36;e.dollarinferior=63203;e.dollarmonospace=65284;e.dollaroldstyle=63268;e.dollarsmall=65129;e.dollarsuperior=63204;e.dong=8363;e.dorusquare=13094;e.dotaccent=729;e.dotaccentcmb=775;e.dotbelowcmb=803;e.dotbelowcomb=803;e.dotkatakana=12539;e.dotlessi=305;e.dotlessj=63166;e.dotlessjstrokehook=644;e.dotmath=8901;e.dottedcircle=9676;e.doubleyodpatah=64287;e.doubleyodpatahhebrew=64287;e.downtackbelowcmb=798;e.downtackmod=725;e.dparen=9375;e.dsuperior=63211;e.dtail=598;e.dtopbar=396;e.duhiragana=12389;e.dukatakana=12485;e.dz=499;e.dzaltone=675;e.dzcaron=454;e.dzcurl=677;e.dzeabkhasiancyrillic=1249;e.dzecyrillic=1109;e.dzhecyrillic=1119;e.e=101;e.eacute=233;e.earth=9793;e.ebengali=2447;e.ebopomofo=12572;e.ebreve=277;e.ecandradeva=2317;e.ecandragujarati=2701;e.ecandravowelsigndeva=2373;e.ecandravowelsigngujarati=2757;e.ecaron=283;e.ecedillabreve=7709;e.echarmenian=1381;e.echyiwnarmenian=1415;e.ecircle=9428;e.ecircumflex=234;e.ecircumflexacute=7871;e.ecircumflexbelow=7705;e.ecircumflexdotbelow=7879;e.ecircumflexgrave=7873;e.ecircumflexhookabove=7875;e.ecircumflextilde=7877;e.ecyrillic=1108;e.edblgrave=517;e.edeva=2319;e.edieresis=235;e.edot=279;e.edotaccent=279;e.edotbelow=7865;e.eegurmukhi=2575;e.eematragurmukhi=2631;e.efcyrillic=1092;e.egrave=232;e.egujarati=2703;e.eharmenian=1383;e.ehbopomofo=12573;e.ehiragana=12360;e.ehookabove=7867;e.eibopomofo=12575;e.eight=56;e.eightarabic=1640;e.eightbengali=2542;e.eightcircle=9319;e.eightcircleinversesansserif=10129;e.eightdeva=2414;e.eighteencircle=9329;e.eighteenparen=9349;e.eighteenperiod=9369;e.eightgujarati=2798;e.eightgurmukhi=2670;e.eighthackarabic=1640;e.eighthangzhou=12328;e.eighthnotebeamed=9835;e.eightideographicparen=12839;e.eightinferior=8328;e.eightmonospace=65304;e.eightoldstyle=63288;e.eightparen=9339;e.eightperiod=9359;e.eightpersian=1784;e.eightroman=8567;e.eightsuperior=8312;e.eightthai=3672;e.einvertedbreve=519;e.eiotifiedcyrillic=1125;e.ekatakana=12456;e.ekatakanahalfwidth=65396;e.ekonkargurmukhi=2676;e.ekorean=12628;e.elcyrillic=1083;e.element=8712;e.elevencircle=9322;e.elevenparen=9342;e.elevenperiod=9362;e.elevenroman=8570;e.ellipsis=8230;e.ellipsisvertical=8942;e.emacron=275;e.emacronacute=7703;e.emacrongrave=7701;e.emcyrillic=1084;e.emdash=8212;e.emdashvertical=65073;e.emonospace=65349;e.emphasismarkarmenian=1371;e.emptyset=8709;e.enbopomofo=12579;e.encyrillic=1085;e.endash=8211;e.endashvertical=65074;e.endescendercyrillic=1187;e.eng=331;e.engbopomofo=12581;e.enghecyrillic=1189;e.enhookcyrillic=1224;e.enspace=8194;e.eogonek=281;e.eokorean=12627;e.eopen=603;e.eopenclosed=666;e.eopenreversed=604;e.eopenreversedclosed=606;e.eopenreversedhook=605;e.eparen=9376;e.epsilon=949;e.epsilontonos=941;e.equal=61;e.equalmonospace=65309;e.equalsmall=65126;e.equalsuperior=8316;e.equivalence=8801;e.erbopomofo=12582;e.ercyrillic=1088;e.ereversed=600;e.ereversedcyrillic=1101;e.escyrillic=1089;e.esdescendercyrillic=1195;e.esh=643;e.eshcurl=646;e.eshortdeva=2318;e.eshortvowelsigndeva=2374;e.eshreversedloop=426;e.eshsquatreversed=645;e.esmallhiragana=12359;e.esmallkatakana=12455;e.esmallkatakanahalfwidth=65386;e.estimated=8494;e.esuperior=63212;e.eta=951;e.etarmenian=1384;e.etatonos=942;e.eth=240;e.etilde=7869;e.etildebelow=7707;e.etnahtafoukhhebrew=1425;e.etnahtafoukhlefthebrew=1425;e.etnahtahebrew=1425;e.etnahtalefthebrew=1425;e.eturned=477;e.eukorean=12641;e.euro=8364;e.evowelsignbengali=2503;e.evowelsigndeva=2375;e.evowelsigngujarati=2759;e.exclam=33;e.exclamarmenian=1372;e.exclamdbl=8252;e.exclamdown=161;e.exclamdownsmall=63393;e.exclammonospace=65281;e.exclamsmall=63265;e.existential=8707;e.ezh=658;e.ezhcaron=495;e.ezhcurl=659;e.ezhreversed=441;e.ezhtail=442;e.f=102;e.fadeva=2398;e.fagurmukhi=2654;e.fahrenheit=8457;e.fathaarabic=1614;e.fathalowarabic=1614;e.fathatanarabic=1611;e.fbopomofo=12552;e.fcircle=9429;e.fdotaccent=7711;e.feharabic=1601;e.feharmenian=1414;e.fehfinalarabic=65234;e.fehinitialarabic=65235;e.fehmedialarabic=65236;e.feicoptic=997;e.female=9792;e.ff=64256;e.f_f=64256;e.ffi=64259;e.f_f_i=64259;e.ffl=64260;e.f_f_l=64260;e.fi=64257;e.f_i=64257;e.fifteencircle=9326;e.fifteenparen=9346;e.fifteenperiod=9366;e.figuredash=8210;e.filledbox=9632;e.filledrect=9644;e.finalkaf=1498;e.finalkafdagesh=64314;e.finalkafdageshhebrew=64314;e.finalkafhebrew=1498;e.finalmem=1501;e.finalmemhebrew=1501;e.finalnun=1503;e.finalnunhebrew=1503;e.finalpe=1507;e.finalpehebrew=1507;e.finaltsadi=1509;e.finaltsadihebrew=1509;e.firsttonechinese=713;e.fisheye=9673;e.fitacyrillic=1139;e.five=53;e.fivearabic=1637;e.fivebengali=2539;e.fivecircle=9316;e.fivecircleinversesansserif=10126;e.fivedeva=2411;e.fiveeighths=8541;e.fivegujarati=2795;e.fivegurmukhi=2667;e.fivehackarabic=1637;e.fivehangzhou=12325;e.fiveideographicparen=12836;e.fiveinferior=8325;e.fivemonospace=65301;e.fiveoldstyle=63285;e.fiveparen=9336;e.fiveperiod=9356;e.fivepersian=1781;e.fiveroman=8564;e.fivesuperior=8309;e.fivethai=3669;e.fl=64258;e.f_l=64258;e.florin=402;e.fmonospace=65350;e.fmsquare=13209;e.fofanthai=3615;e.fofathai=3613;e.fongmanthai=3663;e.forall=8704;e.four=52;e.fourarabic=1636;e.fourbengali=2538;e.fourcircle=9315;e.fourcircleinversesansserif=10125;e.fourdeva=2410;e.fourgujarati=2794;e.fourgurmukhi=2666;e.fourhackarabic=1636;e.fourhangzhou=12324;e.fourideographicparen=12835;e.fourinferior=8324;e.fourmonospace=65300;e.fournumeratorbengali=2551;e.fouroldstyle=63284;e.fourparen=9335;e.fourperiod=9355;e.fourpersian=1780;e.fourroman=8563;e.foursuperior=8308;e.fourteencircle=9325;e.fourteenparen=9345;e.fourteenperiod=9365;e.fourthai=3668;e.fourthtonechinese=715;e.fparen=9377;e.fraction=8260;e.franc=8355;e.g=103;e.gabengali=2455;e.gacute=501;e.gadeva=2327;e.gafarabic=1711;e.gaffinalarabic=64403;e.gafinitialarabic=64404;e.gafmedialarabic=64405;e.gagujarati=2711;e.gagurmukhi=2583;e.gahiragana=12364;e.gakatakana=12460;e.gamma=947;e.gammalatinsmall=611;e.gammasuperior=736;e.gangiacoptic=1003;e.gbopomofo=12557;e.gbreve=287;e.gcaron=487;e.gcedilla=291;e.gcircle=9430;e.gcircumflex=285;e.gcommaaccent=291;e.gdot=289;e.gdotaccent=289;e.gecyrillic=1075;e.gehiragana=12370;e.gekatakana=12466;e.geometricallyequal=8785;e.gereshaccenthebrew=1436;e.gereshhebrew=1523;e.gereshmuqdamhebrew=1437;e.germandbls=223;e.gershayimaccenthebrew=1438;e.gershayimhebrew=1524;e.getamark=12307;e.ghabengali=2456;e.ghadarmenian=1394;e.ghadeva=2328;e.ghagujarati=2712;e.ghagurmukhi=2584;e.ghainarabic=1594;e.ghainfinalarabic=65230;e.ghaininitialarabic=65231;e.ghainmedialarabic=65232;e.ghemiddlehookcyrillic=1173;e.ghestrokecyrillic=1171;e.gheupturncyrillic=1169;e.ghhadeva=2394;e.ghhagurmukhi=2650;e.ghook=608;e.ghzsquare=13203;e.gihiragana=12366;e.gikatakana=12462;e.gimarmenian=1379;e.gimel=1490;e.gimeldagesh=64306;e.gimeldageshhebrew=64306;e.gimelhebrew=1490;e.gjecyrillic=1107;e.glottalinvertedstroke=446;e.glottalstop=660;e.glottalstopinverted=662;e.glottalstopmod=704;e.glottalstopreversed=661;e.glottalstopreversedmod=705;e.glottalstopreversedsuperior=740;e.glottalstopstroke=673;e.glottalstopstrokereversed=674;e.gmacron=7713;e.gmonospace=65351;e.gohiragana=12372;e.gokatakana=12468;e.gparen=9378;e.gpasquare=13228;e.gradient=8711;e.grave=96;e.gravebelowcmb=790;e.gravecmb=768;e.gravecomb=768;e.gravedeva=2387;e.gravelowmod=718;e.gravemonospace=65344;e.gravetonecmb=832;e.greater=62;e.greaterequal=8805;e.greaterequalorless=8923;e.greatermonospace=65310;e.greaterorequivalent=8819;e.greaterorless=8823;e.greateroverequal=8807;e.greatersmall=65125;e.gscript=609;e.gstroke=485;e.guhiragana=12368;e.guillemotleft=171;e.guillemotright=187;e.guilsinglleft=8249;e.guilsinglright=8250;e.gukatakana=12464;e.guramusquare=13080;e.gysquare=13257;e.h=104;e.haabkhasiancyrillic=1193;e.haaltonearabic=1729;e.habengali=2489;e.hadescendercyrillic=1203;e.hadeva=2361;e.hagujarati=2745;e.hagurmukhi=2617;e.haharabic=1581;e.hahfinalarabic=65186;e.hahinitialarabic=65187;e.hahiragana=12399;e.hahmedialarabic=65188;e.haitusquare=13098;e.hakatakana=12495;e.hakatakanahalfwidth=65418;e.halantgurmukhi=2637;e.hamzaarabic=1569;e.hamzalowarabic=1569;e.hangulfiller=12644;e.hardsigncyrillic=1098;e.harpoonleftbarbup=8636;e.harpoonrightbarbup=8640;e.hasquare=13258;e.hatafpatah=1458;e.hatafpatah16=1458;e.hatafpatah23=1458;e.hatafpatah2f=1458;e.hatafpatahhebrew=1458;e.hatafpatahnarrowhebrew=1458;e.hatafpatahquarterhebrew=1458;e.hatafpatahwidehebrew=1458;e.hatafqamats=1459;e.hatafqamats1b=1459;e.hatafqamats28=1459;e.hatafqamats34=1459;e.hatafqamatshebrew=1459;e.hatafqamatsnarrowhebrew=1459;e.hatafqamatsquarterhebrew=1459;e.hatafqamatswidehebrew=1459;e.hatafsegol=1457;e.hatafsegol17=1457;e.hatafsegol24=1457;e.hatafsegol30=1457;e.hatafsegolhebrew=1457;e.hatafsegolnarrowhebrew=1457;e.hatafsegolquarterhebrew=1457;e.hatafsegolwidehebrew=1457;e.hbar=295;e.hbopomofo=12559;e.hbrevebelow=7723;e.hcedilla=7721;e.hcircle=9431;e.hcircumflex=293;e.hdieresis=7719;e.hdotaccent=7715;e.hdotbelow=7717;e.he=1492;e.heart=9829;e.heartsuitblack=9829;e.heartsuitwhite=9825;e.hedagesh=64308;e.hedageshhebrew=64308;e.hehaltonearabic=1729;e.heharabic=1607;e.hehebrew=1492;e.hehfinalaltonearabic=64423;e.hehfinalalttwoarabic=65258;e.hehfinalarabic=65258;e.hehhamzaabovefinalarabic=64421;e.hehhamzaaboveisolatedarabic=64420;e.hehinitialaltonearabic=64424;e.hehinitialarabic=65259;e.hehiragana=12408;e.hehmedialaltonearabic=64425;e.hehmedialarabic=65260;e.heiseierasquare=13179;e.hekatakana=12504;e.hekatakanahalfwidth=65421;e.hekutaarusquare=13110;e.henghook=615;e.herutusquare=13113;e.het=1495;e.hethebrew=1495;e.hhook=614;e.hhooksuperior=689;e.hieuhacirclekorean=12923;e.hieuhaparenkorean=12827;e.hieuhcirclekorean=12909;e.hieuhkorean=12622;e.hieuhparenkorean=12813;e.hihiragana=12402;e.hikatakana=12498;e.hikatakanahalfwidth=65419;e.hiriq=1460;e.hiriq14=1460;e.hiriq21=1460;e.hiriq2d=1460;e.hiriqhebrew=1460;e.hiriqnarrowhebrew=1460;e.hiriqquarterhebrew=1460;e.hiriqwidehebrew=1460;e.hlinebelow=7830;e.hmonospace=65352;e.hoarmenian=1392;e.hohipthai=3627;e.hohiragana=12411;e.hokatakana=12507;e.hokatakanahalfwidth=65422;e.holam=1465;e.holam19=1465;e.holam26=1465;e.holam32=1465;e.holamhebrew=1465;e.holamnarrowhebrew=1465;e.holamquarterhebrew=1465;e.holamwidehebrew=1465;e.honokhukthai=3630;e.hookabovecomb=777;e.hookcmb=777;e.hookpalatalizedbelowcmb=801;e.hookretroflexbelowcmb=802;e.hoonsquare=13122;e.horicoptic=1001;e.horizontalbar=8213;e.horncmb=795;e.hotsprings=9832;e.house=8962;e.hparen=9379;e.hsuperior=688;e.hturned=613;e.huhiragana=12405;e.huiitosquare=13107;e.hukatakana=12501;e.hukatakanahalfwidth=65420;e.hungarumlaut=733;e.hungarumlautcmb=779;e.hv=405;e.hyphen=45;e.hypheninferior=63205;e.hyphenmonospace=65293;e.hyphensmall=65123;e.hyphensuperior=63206;e.hyphentwo=8208;e.i=105;e.iacute=237;e.iacyrillic=1103;e.ibengali=2439;e.ibopomofo=12583;e.ibreve=301;e.icaron=464;e.icircle=9432;e.icircumflex=238;e.icyrillic=1110;e.idblgrave=521;e.ideographearthcircle=12943;e.ideographfirecircle=12939;e.ideographicallianceparen=12863;e.ideographiccallparen=12858;e.ideographiccentrecircle=12965;e.ideographicclose=12294;e.ideographiccomma=12289;e.ideographiccommaleft=65380;e.ideographiccongratulationparen=12855;e.ideographiccorrectcircle=12963;e.ideographicearthparen=12847;e.ideographicenterpriseparen=12861;e.ideographicexcellentcircle=12957;e.ideographicfestivalparen=12864;e.ideographicfinancialcircle=12950;e.ideographicfinancialparen=12854;e.ideographicfireparen=12843;e.ideographichaveparen=12850;e.ideographichighcircle=12964;e.ideographiciterationmark=12293;e.ideographiclaborcircle=12952;e.ideographiclaborparen=12856;e.ideographicleftcircle=12967;e.ideographiclowcircle=12966;e.ideographicmedicinecircle=12969;e.ideographicmetalparen=12846;e.ideographicmoonparen=12842;e.ideographicnameparen=12852;e.ideographicperiod=12290;e.ideographicprintcircle=12958;e.ideographicreachparen=12867;e.ideographicrepresentparen=12857;e.ideographicresourceparen=12862;e.ideographicrightcircle=12968;e.ideographicsecretcircle=12953;e.ideographicselfparen=12866;e.ideographicsocietyparen=12851;e.ideographicspace=12288;e.ideographicspecialparen=12853;e.ideographicstockparen=12849;e.ideographicstudyparen=12859;e.ideographicsunparen=12848;e.ideographicsuperviseparen=12860;e.ideographicwaterparen=12844;e.ideographicwoodparen=12845;e.ideographiczero=12295;e.ideographmetalcircle=12942;e.ideographmooncircle=12938;e.ideographnamecircle=12948;e.ideographsuncircle=12944;e.ideographwatercircle=12940;e.ideographwoodcircle=12941;e.ideva=2311;e.idieresis=239;e.idieresisacute=7727;e.idieresiscyrillic=1253;e.idotbelow=7883;e.iebrevecyrillic=1239;e.iecyrillic=1077;e.ieungacirclekorean=12917;e.ieungaparenkorean=12821;e.ieungcirclekorean=12903;e.ieungkorean=12615;e.ieungparenkorean=12807;e.igrave=236;e.igujarati=2695;e.igurmukhi=2567;e.ihiragana=12356;e.ihookabove=7881;e.iibengali=2440;e.iicyrillic=1080;e.iideva=2312;e.iigujarati=2696;e.iigurmukhi=2568;e.iimatragurmukhi=2624;e.iinvertedbreve=523;e.iishortcyrillic=1081;e.iivowelsignbengali=2496;e.iivowelsigndeva=2368;e.iivowelsigngujarati=2752;e.ij=307;e.ikatakana=12452;e.ikatakanahalfwidth=65394;e.ikorean=12643;e.ilde=732;e.iluyhebrew=1452;e.imacron=299;e.imacroncyrillic=1251;e.imageorapproximatelyequal=8787;e.imatragurmukhi=2623;e.imonospace=65353;e.increment=8710;e.infinity=8734;e.iniarmenian=1387;e.integral=8747;e.integralbottom=8993;e.integralbt=8993;e.integralex=63733;e.integraltop=8992;e.integraltp=8992;e.intersection=8745;e.intisquare=13061;e.invbullet=9688;e.invcircle=9689;e.invsmileface=9787;e.iocyrillic=1105;e.iogonek=303;e.iota=953;e.iotadieresis=970;e.iotadieresistonos=912;e.iotalatin=617;e.iotatonos=943;e.iparen=9380;e.irigurmukhi=2674;e.ismallhiragana=12355;e.ismallkatakana=12451;e.ismallkatakanahalfwidth=65384;e.issharbengali=2554;e.istroke=616;e.isuperior=63213;e.iterationhiragana=12445;e.iterationkatakana=12541;e.itilde=297;e.itildebelow=7725;e.iubopomofo=12585;e.iucyrillic=1102;e.ivowelsignbengali=2495;e.ivowelsigndeva=2367;e.ivowelsigngujarati=2751;e.izhitsacyrillic=1141;e.izhitsadblgravecyrillic=1143;e.j=106;e.jaarmenian=1393;e.jabengali=2460;e.jadeva=2332;e.jagujarati=2716;e.jagurmukhi=2588;e.jbopomofo=12560;e.jcaron=496;e.jcircle=9433;e.jcircumflex=309;e.jcrossedtail=669;e.jdotlessstroke=607;e.jecyrillic=1112;e.jeemarabic=1580;e.jeemfinalarabic=65182;e.jeeminitialarabic=65183;e.jeemmedialarabic=65184;e.jeharabic=1688;e.jehfinalarabic=64395;e.jhabengali=2461;e.jhadeva=2333;e.jhagujarati=2717;e.jhagurmukhi=2589;e.jheharmenian=1403;e.jis=12292;e.jmonospace=65354;e.jparen=9381;e.jsuperior=690;e.k=107;e.kabashkircyrillic=1185;e.kabengali=2453;e.kacute=7729;e.kacyrillic=1082;e.kadescendercyrillic=1179;e.kadeva=2325;e.kaf=1499;e.kafarabic=1603;e.kafdagesh=64315;e.kafdageshhebrew=64315;e.kaffinalarabic=65242;e.kafhebrew=1499;e.kafinitialarabic=65243;e.kafmedialarabic=65244;e.kafrafehebrew=64333;e.kagujarati=2709;e.kagurmukhi=2581;e.kahiragana=12363;e.kahookcyrillic=1220;e.kakatakana=12459;e.kakatakanahalfwidth=65398;e.kappa=954;e.kappasymbolgreek=1008;e.kapyeounmieumkorean=12657;e.kapyeounphieuphkorean=12676;e.kapyeounpieupkorean=12664;e.kapyeounssangpieupkorean=12665;e.karoriisquare=13069;e.kashidaautoarabic=1600;e.kashidaautonosidebearingarabic=1600;e.kasmallkatakana=12533;e.kasquare=13188;e.kasraarabic=1616;e.kasratanarabic=1613;e.kastrokecyrillic=1183;e.katahiraprolongmarkhalfwidth=65392;e.kaverticalstrokecyrillic=1181;e.kbopomofo=12558;e.kcalsquare=13193;e.kcaron=489;e.kcedilla=311;e.kcircle=9434;e.kcommaaccent=311;e.kdotbelow=7731;e.keharmenian=1412;e.kehiragana=12369;e.kekatakana=12465;e.kekatakanahalfwidth=65401;e.kenarmenian=1391;e.kesmallkatakana=12534;e.kgreenlandic=312;e.khabengali=2454;e.khacyrillic=1093;e.khadeva=2326;e.khagujarati=2710;e.khagurmukhi=2582;e.khaharabic=1582;e.khahfinalarabic=65190;e.khahinitialarabic=65191;e.khahmedialarabic=65192;e.kheicoptic=999;e.khhadeva=2393;e.khhagurmukhi=2649;e.khieukhacirclekorean=12920;e.khieukhaparenkorean=12824;e.khieukhcirclekorean=12906;e.khieukhkorean=12619;e.khieukhparenkorean=12810;e.khokhaithai=3586;e.khokhonthai=3589;e.khokhuatthai=3587;e.khokhwaithai=3588;e.khomutthai=3675;e.khook=409;e.khorakhangthai=3590;e.khzsquare=13201;e.kihiragana=12365;e.kikatakana=12461;e.kikatakanahalfwidth=65399;e.kiroguramusquare=13077;e.kiromeetorusquare=13078;e.kirosquare=13076;e.kiyeokacirclekorean=12910;e.kiyeokaparenkorean=12814;e.kiyeokcirclekorean=12896;e.kiyeokkorean=12593;e.kiyeokparenkorean=12800;e.kiyeoksioskorean=12595;e.kjecyrillic=1116;e.klinebelow=7733;e.klsquare=13208;e.kmcubedsquare=13222;e.kmonospace=65355;e.kmsquaredsquare=13218;e.kohiragana=12371;e.kohmsquare=13248;e.kokaithai=3585;e.kokatakana=12467;e.kokatakanahalfwidth=65402;e.kooposquare=13086;e.koppacyrillic=1153;e.koreanstandardsymbol=12927;e.koroniscmb=835;e.kparen=9382;e.kpasquare=13226;e.ksicyrillic=1135;e.ktsquare=13263;e.kturned=670;e.kuhiragana=12367;e.kukatakana=12463;e.kukatakanahalfwidth=65400;e.kvsquare=13240;e.kwsquare=13246;e.l=108;e.labengali=2482;e.lacute=314;e.ladeva=2354;e.lagujarati=2738;e.lagurmukhi=2610;e.lakkhangyaothai=3653;e.lamaleffinalarabic=65276;e.lamalefhamzaabovefinalarabic=65272;e.lamalefhamzaaboveisolatedarabic=65271;e.lamalefhamzabelowfinalarabic=65274;e.lamalefhamzabelowisolatedarabic=65273;e.lamalefisolatedarabic=65275;e.lamalefmaddaabovefinalarabic=65270;e.lamalefmaddaaboveisolatedarabic=65269;e.lamarabic=1604;e.lambda=955;e.lambdastroke=411;e.lamed=1500;e.lameddagesh=64316;e.lameddageshhebrew=64316;e.lamedhebrew=1500;e.lamfinalarabic=65246;e.lamhahinitialarabic=64714;e.laminitialarabic=65247;e.lamjeeminitialarabic=64713;e.lamkhahinitialarabic=64715;e.lamlamhehisolatedarabic=65010;e.lammedialarabic=65248;e.lammeemhahinitialarabic=64904;e.lammeeminitialarabic=64716;e.largecircle=9711;e.lbar=410;e.lbelt=620;e.lbopomofo=12556;e.lcaron=318;e.lcedilla=316;e.lcircle=9435;e.lcircumflexbelow=7741;e.lcommaaccent=316;e.ldot=320;e.ldotaccent=320;e.ldotbelow=7735;e.ldotbelowmacron=7737;e.leftangleabovecmb=794;e.lefttackbelowcmb=792;e.less=60;e.lessequal=8804;e.lessequalorgreater=8922;e.lessmonospace=65308;e.lessorequivalent=8818;e.lessorgreater=8822;e.lessoverequal=8806;e.lesssmall=65124;e.lezh=622;e.lfblock=9612;e.lhookretroflex=621;e.lira=8356;e.liwnarmenian=1388;e.lj=457;e.ljecyrillic=1113;e.ll=63168;e.lladeva=2355;e.llagujarati=2739;e.llinebelow=7739;e.llladeva=2356;e.llvocalicbengali=2529;e.llvocalicdeva=2401;e.llvocalicvowelsignbengali=2531;e.llvocalicvowelsigndeva=2403;e.lmiddletilde=619;e.lmonospace=65356;e.lmsquare=13264;e.lochulathai=3628;e.logicaland=8743;e.logicalnot=172;e.logicalnotreversed=8976;e.logicalor=8744;e.lolingthai=3621;e.longs=383;e.lowlinecenterline=65102;e.lowlinecmb=818;e.lowlinedashed=65101;e.lozenge=9674;e.lparen=9383;e.lslash=322;e.lsquare=8467;e.lsuperior=63214;e.ltshade=9617;e.luthai=3622;e.lvocalicbengali=2444;e.lvocalicdeva=2316;e.lvocalicvowelsignbengali=2530;e.lvocalicvowelsigndeva=2402;e.lxsquare=13267;e.m=109;e.mabengali=2478;e.macron=175;e.macronbelowcmb=817;e.macroncmb=772;e.macronlowmod=717;e.macronmonospace=65507;e.macute=7743;e.madeva=2350;e.magujarati=2734;e.magurmukhi=2606;e.mahapakhhebrew=1444;e.mahapakhlefthebrew=1444;e.mahiragana=12414;e.maichattawalowleftthai=63637;e.maichattawalowrightthai=63636;e.maichattawathai=3659;e.maichattawaupperleftthai=63635;e.maieklowleftthai=63628;e.maieklowrightthai=63627;e.maiekthai=3656;e.maiekupperleftthai=63626;e.maihanakatleftthai=63620;e.maihanakatthai=3633;e.maitaikhuleftthai=63625;e.maitaikhuthai=3655;e.maitholowleftthai=63631;e.maitholowrightthai=63630;e.maithothai=3657;e.maithoupperleftthai=63629;e.maitrilowleftthai=63634;e.maitrilowrightthai=63633;e.maitrithai=3658;e.maitriupperleftthai=63632;e.maiyamokthai=3654;e.makatakana=12510;e.makatakanahalfwidth=65423;e.male=9794;e.mansyonsquare=13127;e.maqafhebrew=1470;e.mars=9794;e.masoracirclehebrew=1455;e.masquare=13187;e.mbopomofo=12551;e.mbsquare=13268;e.mcircle=9436;e.mcubedsquare=13221;e.mdotaccent=7745;e.mdotbelow=7747;e.meemarabic=1605;e.meemfinalarabic=65250;e.meeminitialarabic=65251;e.meemmedialarabic=65252;e.meemmeeminitialarabic=64721;e.meemmeemisolatedarabic=64584;e.meetorusquare=13133;e.mehiragana=12417;e.meizierasquare=13182;e.mekatakana=12513;e.mekatakanahalfwidth=65426;e.mem=1502;e.memdagesh=64318;e.memdageshhebrew=64318;e.memhebrew=1502;e.menarmenian=1396;e.merkhahebrew=1445;e.merkhakefulahebrew=1446;e.merkhakefulalefthebrew=1446;e.merkhalefthebrew=1445;e.mhook=625;e.mhzsquare=13202;e.middledotkatakanahalfwidth=65381;e.middot=183;e.mieumacirclekorean=12914;e.mieumaparenkorean=12818;e.mieumcirclekorean=12900;e.mieumkorean=12609;e.mieumpansioskorean=12656;e.mieumparenkorean=12804;e.mieumpieupkorean=12654;e.mieumsioskorean=12655;e.mihiragana=12415;e.mikatakana=12511;e.mikatakanahalfwidth=65424;e.minus=8722;e.minusbelowcmb=800;e.minuscircle=8854;e.minusmod=727;e.minusplus=8723;e.minute=8242;e.miribaarusquare=13130;e.mirisquare=13129;e.mlonglegturned=624;e.mlsquare=13206;e.mmcubedsquare=13219;e.mmonospace=65357;e.mmsquaredsquare=13215;e.mohiragana=12418;e.mohmsquare=13249;e.mokatakana=12514;e.mokatakanahalfwidth=65427;e.molsquare=13270;e.momathai=3617;e.moverssquare=13223;e.moverssquaredsquare=13224;e.mparen=9384;e.mpasquare=13227;e.mssquare=13235;e.msuperior=63215;e.mturned=623;e.mu=181;e.mu1=181;e.muasquare=13186;e.muchgreater=8811;e.muchless=8810;e.mufsquare=13196;e.mugreek=956;e.mugsquare=13197;e.muhiragana=12416;e.mukatakana=12512;e.mukatakanahalfwidth=65425;e.mulsquare=13205;e.multiply=215;e.mumsquare=13211;e.munahhebrew=1443;e.munahlefthebrew=1443;e.musicalnote=9834;e.musicalnotedbl=9835;e.musicflatsign=9837;e.musicsharpsign=9839;e.mussquare=13234;e.muvsquare=13238;e.muwsquare=13244;e.mvmegasquare=13241;e.mvsquare=13239;e.mwmegasquare=13247;e.mwsquare=13245;e.n=110;e.nabengali=2472;e.nabla=8711;e.nacute=324;e.nadeva=2344;e.nagujarati=2728;e.nagurmukhi=2600;e.nahiragana=12394;e.nakatakana=12490;e.nakatakanahalfwidth=65413;e.napostrophe=329;e.nasquare=13185;e.nbopomofo=12555;e.nbspace=160;e.ncaron=328;e.ncedilla=326;e.ncircle=9437;e.ncircumflexbelow=7755;e.ncommaaccent=326;e.ndotaccent=7749;e.ndotbelow=7751;e.nehiragana=12397;e.nekatakana=12493;e.nekatakanahalfwidth=65416;e.newsheqelsign=8362;e.nfsquare=13195;e.ngabengali=2457;e.ngadeva=2329;e.ngagujarati=2713;e.ngagurmukhi=2585;e.ngonguthai=3591;e.nhiragana=12435;e.nhookleft=626;e.nhookretroflex=627;e.nieunacirclekorean=12911;e.nieunaparenkorean=12815;e.nieuncieuckorean=12597;e.nieuncirclekorean=12897;e.nieunhieuhkorean=12598;e.nieunkorean=12596;e.nieunpansioskorean=12648;e.nieunparenkorean=12801;e.nieunsioskorean=12647;e.nieuntikeutkorean=12646;e.nihiragana=12395;e.nikatakana=12491;e.nikatakanahalfwidth=65414;e.nikhahitleftthai=63641;e.nikhahitthai=3661;e.nine=57;e.ninearabic=1641;e.ninebengali=2543;e.ninecircle=9320;e.ninecircleinversesansserif=10130;e.ninedeva=2415;e.ninegujarati=2799;e.ninegurmukhi=2671;e.ninehackarabic=1641;e.ninehangzhou=12329;e.nineideographicparen=12840;e.nineinferior=8329;e.ninemonospace=65305;e.nineoldstyle=63289;e.nineparen=9340;e.nineperiod=9360;e.ninepersian=1785;e.nineroman=8568;e.ninesuperior=8313;e.nineteencircle=9330;e.nineteenparen=9350;e.nineteenperiod=9370;e.ninethai=3673;e.nj=460;e.njecyrillic=1114;e.nkatakana=12531;e.nkatakanahalfwidth=65437;e.nlegrightlong=414;e.nlinebelow=7753;e.nmonospace=65358;e.nmsquare=13210;e.nnabengali=2467;e.nnadeva=2339;e.nnagujarati=2723;e.nnagurmukhi=2595;e.nnnadeva=2345;e.nohiragana=12398;e.nokatakana=12494;e.nokatakanahalfwidth=65417;e.nonbreakingspace=160;e.nonenthai=3603;e.nonuthai=3609;e.noonarabic=1606;e.noonfinalarabic=65254;e.noonghunnaarabic=1722;e.noonghunnafinalarabic=64415;e.nooninitialarabic=65255;e.noonjeeminitialarabic=64722;e.noonjeemisolatedarabic=64587;e.noonmedialarabic=65256;e.noonmeeminitialarabic=64725;e.noonmeemisolatedarabic=64590;e.noonnoonfinalarabic=64653;e.notcontains=8716;e.notelement=8713;e.notelementof=8713;e.notequal=8800;e.notgreater=8815;e.notgreaternorequal=8817;e.notgreaternorless=8825;e.notidentical=8802;e.notless=8814;e.notlessnorequal=8816;e.notparallel=8742;e.notprecedes=8832;e.notsubset=8836;e.notsucceeds=8833;e.notsuperset=8837;e.nowarmenian=1398;e.nparen=9385;e.nssquare=13233;e.nsuperior=8319;e.ntilde=241;e.nu=957;e.nuhiragana=12396;e.nukatakana=12492;e.nukatakanahalfwidth=65415;e.nuktabengali=2492;e.nuktadeva=2364;e.nuktagujarati=2748;e.nuktagurmukhi=2620;e.numbersign=35;e.numbersignmonospace=65283;e.numbersignsmall=65119;e.numeralsigngreek=884;e.numeralsignlowergreek=885;e.numero=8470;e.nun=1504;e.nundagesh=64320;e.nundageshhebrew=64320;e.nunhebrew=1504;e.nvsquare=13237;e.nwsquare=13243;e.nyabengali=2462;e.nyadeva=2334;e.nyagujarati=2718;e.nyagurmukhi=2590;e.o=111;e.oacute=243;e.oangthai=3629;e.obarred=629;e.obarredcyrillic=1257;e.obarreddieresiscyrillic=1259;e.obengali=2451;e.obopomofo=12571;e.obreve=335;e.ocandradeva=2321;e.ocandragujarati=2705;e.ocandravowelsigndeva=2377;e.ocandravowelsigngujarati=2761;e.ocaron=466;e.ocircle=9438;e.ocircumflex=244;e.ocircumflexacute=7889;e.ocircumflexdotbelow=7897;e.ocircumflexgrave=7891;e.ocircumflexhookabove=7893;e.ocircumflextilde=7895;e.ocyrillic=1086;e.odblacute=337;e.odblgrave=525;e.odeva=2323;e.odieresis=246;e.odieresiscyrillic=1255;e.odotbelow=7885;e.oe=339;e.oekorean=12634;e.ogonek=731;e.ogonekcmb=808;e.ograve=242;e.ogujarati=2707;e.oharmenian=1413;e.ohiragana=12362;e.ohookabove=7887;e.ohorn=417;e.ohornacute=7899;e.ohorndotbelow=7907;e.ohorngrave=7901;e.ohornhookabove=7903;e.ohorntilde=7905;e.ohungarumlaut=337;e.oi=419;e.oinvertedbreve=527;e.okatakana=12458;e.okatakanahalfwidth=65397;e.okorean=12631;e.olehebrew=1451;e.omacron=333;e.omacronacute=7763;e.omacrongrave=7761;e.omdeva=2384;e.omega=969;e.omega1=982;e.omegacyrillic=1121;e.omegalatinclosed=631;e.omegaroundcyrillic=1147;e.omegatitlocyrillic=1149;e.omegatonos=974;e.omgujarati=2768;e.omicron=959;e.omicrontonos=972;e.omonospace=65359;e.one=49;e.onearabic=1633;e.onebengali=2535;e.onecircle=9312;e.onecircleinversesansserif=10122;e.onedeva=2407;e.onedotenleader=8228;e.oneeighth=8539;e.onefitted=63196;e.onegujarati=2791;e.onegurmukhi=2663;e.onehackarabic=1633;e.onehalf=189;e.onehangzhou=12321;e.oneideographicparen=12832;e.oneinferior=8321;e.onemonospace=65297;e.onenumeratorbengali=2548;e.oneoldstyle=63281;e.oneparen=9332;e.oneperiod=9352;e.onepersian=1777;e.onequarter=188;e.oneroman=8560;e.onesuperior=185;e.onethai=3665;e.onethird=8531;e.oogonek=491;e.oogonekmacron=493;e.oogurmukhi=2579;e.oomatragurmukhi=2635;e.oopen=596;e.oparen=9386;e.openbullet=9702;e.option=8997;e.ordfeminine=170;e.ordmasculine=186;e.orthogonal=8735;e.oshortdeva=2322;e.oshortvowelsigndeva=2378;e.oslash=248;e.oslashacute=511;e.osmallhiragana=12361;e.osmallkatakana=12457;e.osmallkatakanahalfwidth=65387;e.ostrokeacute=511;e.osuperior=63216;e.otcyrillic=1151;e.otilde=245;e.otildeacute=7757;e.otildedieresis=7759;e.oubopomofo=12577;e.overline=8254;e.overlinecenterline=65098;e.overlinecmb=773;e.overlinedashed=65097;e.overlinedblwavy=65100;e.overlinewavy=65099;e.overscore=175;e.ovowelsignbengali=2507;e.ovowelsigndeva=2379;e.ovowelsigngujarati=2763;e.p=112;e.paampssquare=13184;e.paasentosquare=13099;e.pabengali=2474;e.pacute=7765;e.padeva=2346;e.pagedown=8671;e.pageup=8670;e.pagujarati=2730;e.pagurmukhi=2602;e.pahiragana=12401;e.paiyannoithai=3631;e.pakatakana=12497;e.palatalizationcyrilliccmb=1156;e.palochkacyrillic=1216;e.pansioskorean=12671;e.paragraph=182;e.parallel=8741;e.parenleft=40;e.parenleftaltonearabic=64830;e.parenleftbt=63725;e.parenleftex=63724;e.parenleftinferior=8333;e.parenleftmonospace=65288;e.parenleftsmall=65113;e.parenleftsuperior=8317;e.parenlefttp=63723;e.parenleftvertical=65077;e.parenright=41;e.parenrightaltonearabic=64831;e.parenrightbt=63736;e.parenrightex=63735;e.parenrightinferior=8334;e.parenrightmonospace=65289;e.parenrightsmall=65114;e.parenrightsuperior=8318;e.parenrighttp=63734;e.parenrightvertical=65078;e.partialdiff=8706;e.paseqhebrew=1472;e.pashtahebrew=1433;e.pasquare=13225;e.patah=1463;e.patah11=1463;e.patah1d=1463;e.patah2a=1463;e.patahhebrew=1463;e.patahnarrowhebrew=1463;e.patahquarterhebrew=1463;e.patahwidehebrew=1463;e.pazerhebrew=1441;e.pbopomofo=12550;e.pcircle=9439;e.pdotaccent=7767;e.pe=1508;e.pecyrillic=1087;e.pedagesh=64324;e.pedageshhebrew=64324;e.peezisquare=13115;e.pefinaldageshhebrew=64323;e.peharabic=1662;e.peharmenian=1402;e.pehebrew=1508;e.pehfinalarabic=64343;e.pehinitialarabic=64344;e.pehiragana=12410;e.pehmedialarabic=64345;e.pekatakana=12506;e.pemiddlehookcyrillic=1191;e.perafehebrew=64334;e.percent=37;e.percentarabic=1642;e.percentmonospace=65285;e.percentsmall=65130;e.period=46;e.periodarmenian=1417;e.periodcentered=183;e.periodhalfwidth=65377;e.periodinferior=63207;e.periodmonospace=65294;e.periodsmall=65106;e.periodsuperior=63208;e.perispomenigreekcmb=834;e.perpendicular=8869;e.perthousand=8240;e.peseta=8359;e.pfsquare=13194;e.phabengali=2475;e.phadeva=2347;e.phagujarati=2731;e.phagurmukhi=2603;e.phi=966;e.phi1=981;e.phieuphacirclekorean=12922;e.phieuphaparenkorean=12826;e.phieuphcirclekorean=12908;e.phieuphkorean=12621;e.phieuphparenkorean=12812;e.philatin=632;e.phinthuthai=3642;e.phisymbolgreek=981;e.phook=421;e.phophanthai=3614;e.phophungthai=3612;e.phosamphaothai=3616;e.pi=960;e.pieupacirclekorean=12915;e.pieupaparenkorean=12819;e.pieupcieuckorean=12662;e.pieupcirclekorean=12901;e.pieupkiyeokkorean=12658;e.pieupkorean=12610;e.pieupparenkorean=12805;e.pieupsioskiyeokkorean=12660;e.pieupsioskorean=12612;e.pieupsiostikeutkorean=12661;e.pieupthieuthkorean=12663;e.pieuptikeutkorean=12659;e.pihiragana=12404;e.pikatakana=12500;e.pisymbolgreek=982;e.piwrarmenian=1411;e.planckover2pi=8463;e.planckover2pi1=8463;e.plus=43;e.plusbelowcmb=799;e.pluscircle=8853;e.plusminus=177;e.plusmod=726;e.plusmonospace=65291;e.plussmall=65122;e.plussuperior=8314;e.pmonospace=65360;e.pmsquare=13272;e.pohiragana=12413;e.pointingindexdownwhite=9759;e.pointingindexleftwhite=9756;e.pointingindexrightwhite=9758;e.pointingindexupwhite=9757;e.pokatakana=12509;e.poplathai=3611;e.postalmark=12306;e.postalmarkface=12320;e.pparen=9387;e.precedes=8826;e.prescription=8478;e.primemod=697;e.primereversed=8245;e.product=8719;e.projective=8965;e.prolongedkana=12540;e.propellor=8984;e.propersubset=8834;e.propersuperset=8835;e.proportion=8759;e.proportional=8733;e.psi=968;e.psicyrillic=1137;e.psilipneumatacyrilliccmb=1158;e.pssquare=13232;e.puhiragana=12407;e.pukatakana=12503;e.pvsquare=13236;e.pwsquare=13242;e.q=113;e.qadeva=2392;e.qadmahebrew=1448;e.qafarabic=1602;e.qaffinalarabic=65238;e.qafinitialarabic=65239;e.qafmedialarabic=65240;e.qamats=1464;e.qamats10=1464;e.qamats1a=1464;e.qamats1c=1464;e.qamats27=1464;e.qamats29=1464;e.qamats33=1464;e.qamatsde=1464;e.qamatshebrew=1464;e.qamatsnarrowhebrew=1464;e.qamatsqatanhebrew=1464;e.qamatsqatannarrowhebrew=1464;e.qamatsqatanquarterhebrew=1464;e.qamatsqatanwidehebrew=1464;e.qamatsquarterhebrew=1464;e.qamatswidehebrew=1464;e.qarneyparahebrew=1439;e.qbopomofo=12561;e.qcircle=9440;e.qhook=672;e.qmonospace=65361;e.qof=1511;e.qofdagesh=64327;e.qofdageshhebrew=64327;e.qofhebrew=1511;e.qparen=9388;e.quarternote=9833;e.qubuts=1467;e.qubuts18=1467;e.qubuts25=1467;e.qubuts31=1467;e.qubutshebrew=1467;e.qubutsnarrowhebrew=1467;e.qubutsquarterhebrew=1467;e.qubutswidehebrew=1467;e.question=63;e.questionarabic=1567;e.questionarmenian=1374;e.questiondown=191;e.questiondownsmall=63423;e.questiongreek=894;e.questionmonospace=65311;e.questionsmall=63295;e.quotedbl=34;e.quotedblbase=8222;e.quotedblleft=8220;e.quotedblmonospace=65282;e.quotedblprime=12318;e.quotedblprimereversed=12317;e.quotedblright=8221;e.quoteleft=8216;e.quoteleftreversed=8219;e.quotereversed=8219;e.quoteright=8217;e.quoterightn=329;e.quotesinglbase=8218;e.quotesingle=39;e.quotesinglemonospace=65287;e.r=114;e.raarmenian=1404;e.rabengali=2480;e.racute=341;e.radeva=2352;e.radical=8730;e.radicalex=63717;e.radoverssquare=13230;e.radoverssquaredsquare=13231;e.radsquare=13229;e.rafe=1471;e.rafehebrew=1471;e.ragujarati=2736;e.ragurmukhi=2608;e.rahiragana=12425;e.rakatakana=12521;e.rakatakanahalfwidth=65431;e.ralowerdiagonalbengali=2545;e.ramiddlediagonalbengali=2544;e.ramshorn=612;e.ratio=8758;e.rbopomofo=12566;e.rcaron=345;e.rcedilla=343;e.rcircle=9441;e.rcommaaccent=343;e.rdblgrave=529;e.rdotaccent=7769;e.rdotbelow=7771;e.rdotbelowmacron=7773;e.referencemark=8251;e.reflexsubset=8838;e.reflexsuperset=8839;e.registered=174;e.registersans=63720;e.registerserif=63194;e.reharabic=1585;e.reharmenian=1408;e.rehfinalarabic=65198;e.rehiragana=12428;e.rekatakana=12524;e.rekatakanahalfwidth=65434;e.resh=1512;e.reshdageshhebrew=64328;e.reshhebrew=1512;e.reversedtilde=8765;e.reviahebrew=1431;e.reviamugrashhebrew=1431;e.revlogicalnot=8976;e.rfishhook=638;e.rfishhookreversed=639;e.rhabengali=2525;e.rhadeva=2397;e.rho=961;e.rhook=637;e.rhookturned=635;e.rhookturnedsuperior=693;e.rhosymbolgreek=1009;e.rhotichookmod=734;e.rieulacirclekorean=12913;e.rieulaparenkorean=12817;e.rieulcirclekorean=12899;e.rieulhieuhkorean=12608;e.rieulkiyeokkorean=12602;e.rieulkiyeoksioskorean=12649;e.rieulkorean=12601;e.rieulmieumkorean=12603;e.rieulpansioskorean=12652;e.rieulparenkorean=12803;e.rieulphieuphkorean=12607;e.rieulpieupkorean=12604;e.rieulpieupsioskorean=12651;e.rieulsioskorean=12605;e.rieulthieuthkorean=12606;e.rieultikeutkorean=12650;e.rieulyeorinhieuhkorean=12653;e.rightangle=8735;e.righttackbelowcmb=793;e.righttriangle=8895;e.rihiragana=12426;e.rikatakana=12522;e.rikatakanahalfwidth=65432;e.ring=730;e.ringbelowcmb=805;e.ringcmb=778;e.ringhalfleft=703;e.ringhalfleftarmenian=1369;e.ringhalfleftbelowcmb=796;e.ringhalfleftcentered=723;e.ringhalfright=702;e.ringhalfrightbelowcmb=825;e.ringhalfrightcentered=722;e.rinvertedbreve=531;e.rittorusquare=13137;e.rlinebelow=7775;e.rlongleg=636;e.rlonglegturned=634;e.rmonospace=65362;e.rohiragana=12429;e.rokatakana=12525;e.rokatakanahalfwidth=65435;e.roruathai=3619;e.rparen=9389;e.rrabengali=2524;e.rradeva=2353;e.rragurmukhi=2652;e.rreharabic=1681;e.rrehfinalarabic=64397;e.rrvocalicbengali=2528;e.rrvocalicdeva=2400;e.rrvocalicgujarati=2784;e.rrvocalicvowelsignbengali=2500;e.rrvocalicvowelsigndeva=2372;e.rrvocalicvowelsigngujarati=2756;e.rsuperior=63217;e.rtblock=9616;e.rturned=633;e.rturnedsuperior=692;e.ruhiragana=12427;e.rukatakana=12523;e.rukatakanahalfwidth=65433;e.rupeemarkbengali=2546;e.rupeesignbengali=2547;e.rupiah=63197;e.ruthai=3620;e.rvocalicbengali=2443;e.rvocalicdeva=2315;e.rvocalicgujarati=2699;e.rvocalicvowelsignbengali=2499;e.rvocalicvowelsigndeva=2371;e.rvocalicvowelsigngujarati=2755;e.s=115;e.sabengali=2488;e.sacute=347;e.sacutedotaccent=7781;e.sadarabic=1589;e.sadeva=2360;e.sadfinalarabic=65210;e.sadinitialarabic=65211;e.sadmedialarabic=65212;e.sagujarati=2744;e.sagurmukhi=2616;e.sahiragana=12373;e.sakatakana=12469;e.sakatakanahalfwidth=65403;e.sallallahoualayhewasallamarabic=65018;e.samekh=1505;e.samekhdagesh=64321;e.samekhdageshhebrew=64321;e.samekhhebrew=1505;e.saraaathai=3634;e.saraaethai=3649;e.saraaimaimalaithai=3652;e.saraaimaimuanthai=3651;e.saraamthai=3635;e.saraathai=3632;e.saraethai=3648;e.saraiileftthai=63622;e.saraiithai=3637;e.saraileftthai=63621;e.saraithai=3636;e.saraothai=3650;e.saraueeleftthai=63624;e.saraueethai=3639;e.saraueleftthai=63623;e.sarauethai=3638;e.sarauthai=3640;e.sarauuthai=3641;e.sbopomofo=12569;e.scaron=353;e.scarondotaccent=7783;e.scedilla=351;e.schwa=601;e.schwacyrillic=1241;e.schwadieresiscyrillic=1243;e.schwahook=602;e.scircle=9442;e.scircumflex=349;e.scommaaccent=537;e.sdotaccent=7777;e.sdotbelow=7779;e.sdotbelowdotaccent=7785;e.seagullbelowcmb=828;e.second=8243;e.secondtonechinese=714;e.section=167;e.seenarabic=1587;e.seenfinalarabic=65202;e.seeninitialarabic=65203;e.seenmedialarabic=65204;e.segol=1462;e.segol13=1462;e.segol1f=1462;e.segol2c=1462;e.segolhebrew=1462;e.segolnarrowhebrew=1462;e.segolquarterhebrew=1462;e.segoltahebrew=1426;e.segolwidehebrew=1462;e.seharmenian=1405;e.sehiragana=12379;e.sekatakana=12475;e.sekatakanahalfwidth=65406;e.semicolon=59;e.semicolonarabic=1563;e.semicolonmonospace=65307;e.semicolonsmall=65108;e.semivoicedmarkkana=12444;e.semivoicedmarkkanahalfwidth=65439;e.sentisquare=13090;e.sentosquare=13091;e.seven=55;e.sevenarabic=1639;e.sevenbengali=2541;e.sevencircle=9318;e.sevencircleinversesansserif=10128;e.sevendeva=2413;e.seveneighths=8542;e.sevengujarati=2797;e.sevengurmukhi=2669;e.sevenhackarabic=1639;e.sevenhangzhou=12327;e.sevenideographicparen=12838;e.seveninferior=8327;e.sevenmonospace=65303;e.sevenoldstyle=63287;e.sevenparen=9338;e.sevenperiod=9358;e.sevenpersian=1783;e.sevenroman=8566;e.sevensuperior=8311;e.seventeencircle=9328;e.seventeenparen=9348;e.seventeenperiod=9368;e.seventhai=3671;e.sfthyphen=173;e.shaarmenian=1399;e.shabengali=2486;e.shacyrillic=1096;e.shaddaarabic=1617;e.shaddadammaarabic=64609;e.shaddadammatanarabic=64606;e.shaddafathaarabic=64608;e.shaddakasraarabic=64610;e.shaddakasratanarabic=64607;e.shade=9618;e.shadedark=9619;e.shadelight=9617;e.shademedium=9618;e.shadeva=2358;e.shagujarati=2742;e.shagurmukhi=2614;e.shalshelethebrew=1427;e.shbopomofo=12565;e.shchacyrillic=1097;e.sheenarabic=1588;e.sheenfinalarabic=65206;e.sheeninitialarabic=65207;e.sheenmedialarabic=65208;e.sheicoptic=995;e.sheqel=8362;e.sheqelhebrew=8362;e.sheva=1456;e.sheva115=1456;e.sheva15=1456;e.sheva22=1456;e.sheva2e=1456;e.shevahebrew=1456;e.shevanarrowhebrew=1456;e.shevaquarterhebrew=1456;e.shevawidehebrew=1456;e.shhacyrillic=1211;e.shimacoptic=1005;e.shin=1513;e.shindagesh=64329;e.shindageshhebrew=64329;e.shindageshshindot=64300;e.shindageshshindothebrew=64300;e.shindageshsindot=64301;e.shindageshsindothebrew=64301;e.shindothebrew=1473;e.shinhebrew=1513;e.shinshindot=64298;e.shinshindothebrew=64298;e.shinsindot=64299;e.shinsindothebrew=64299;e.shook=642;e.sigma=963;e.sigma1=962;e.sigmafinal=962;e.sigmalunatesymbolgreek=1010;e.sihiragana=12375;e.sikatakana=12471;e.sikatakanahalfwidth=65404;e.siluqhebrew=1469;e.siluqlefthebrew=1469;e.similar=8764;e.sindothebrew=1474;e.siosacirclekorean=12916;e.siosaparenkorean=12820;e.sioscieuckorean=12670;e.sioscirclekorean=12902;e.sioskiyeokkorean=12666;e.sioskorean=12613;e.siosnieunkorean=12667;e.siosparenkorean=12806;e.siospieupkorean=12669;e.siostikeutkorean=12668;e.six=54;e.sixarabic=1638;e.sixbengali=2540;e.sixcircle=9317;e.sixcircleinversesansserif=10127;e.sixdeva=2412;e.sixgujarati=2796;e.sixgurmukhi=2668;e.sixhackarabic=1638;e.sixhangzhou=12326;e.sixideographicparen=12837;e.sixinferior=8326;e.sixmonospace=65302;e.sixoldstyle=63286;e.sixparen=9337;e.sixperiod=9357;e.sixpersian=1782;e.sixroman=8565;e.sixsuperior=8310;e.sixteencircle=9327;e.sixteencurrencydenominatorbengali=2553;e.sixteenparen=9347;e.sixteenperiod=9367;e.sixthai=3670;e.slash=47;e.slashmonospace=65295;e.slong=383;e.slongdotaccent=7835;e.smileface=9786;e.smonospace=65363;e.sofpasuqhebrew=1475;e.softhyphen=173;e.softsigncyrillic=1100;e.sohiragana=12381;e.sokatakana=12477;e.sokatakanahalfwidth=65407;e.soliduslongoverlaycmb=824;e.solidusshortoverlaycmb=823;e.sorusithai=3625;e.sosalathai=3624;e.sosothai=3595;e.sosuathai=3626;e.space=32;e.spacehackarabic=32;e.spade=9824;e.spadesuitblack=9824;e.spadesuitwhite=9828;e.sparen=9390;e.squarebelowcmb=827;e.squarecc=13252;e.squarecm=13213;e.squarediagonalcrosshatchfill=9641;e.squarehorizontalfill=9636;e.squarekg=13199;e.squarekm=13214;e.squarekmcapital=13262;e.squareln=13265;e.squarelog=13266;e.squaremg=13198;e.squaremil=13269;e.squaremm=13212;e.squaremsquared=13217;e.squareorthogonalcrosshatchfill=9638;e.squareupperlefttolowerrightfill=9639;e.squareupperrighttolowerleftfill=9640;e.squareverticalfill=9637;e.squarewhitewithsmallblack=9635;e.srsquare=13275;e.ssabengali=2487;e.ssadeva=2359;e.ssagujarati=2743;e.ssangcieuckorean=12617;e.ssanghieuhkorean=12677;e.ssangieungkorean=12672;e.ssangkiyeokkorean=12594;e.ssangnieunkorean=12645;e.ssangpieupkorean=12611;e.ssangsioskorean=12614;e.ssangtikeutkorean=12600;e.ssuperior=63218;e.sterling=163;e.sterlingmonospace=65505;e.strokelongoverlaycmb=822;e.strokeshortoverlaycmb=821;e.subset=8834;e.subsetnotequal=8842;e.subsetorequal=8838;e.succeeds=8827;e.suchthat=8715;e.suhiragana=12377;e.sukatakana=12473;e.sukatakanahalfwidth=65405;e.sukunarabic=1618;e.summation=8721;e.sun=9788;e.superset=8835;e.supersetnotequal=8843;e.supersetorequal=8839;e.svsquare=13276;e.syouwaerasquare=13180;e.t=116;e.tabengali=2468;e.tackdown=8868;e.tackleft=8867;e.tadeva=2340;e.tagujarati=2724;e.tagurmukhi=2596;e.taharabic=1591;e.tahfinalarabic=65218;e.tahinitialarabic=65219;e.tahiragana=12383;e.tahmedialarabic=65220;e.taisyouerasquare=13181;e.takatakana=12479;e.takatakanahalfwidth=65408;e.tatweelarabic=1600;e.tau=964;e.tav=1514;e.tavdages=64330;e.tavdagesh=64330;e.tavdageshhebrew=64330;e.tavhebrew=1514;e.tbar=359;e.tbopomofo=12554;e.tcaron=357;e.tccurl=680;e.tcedilla=355;e.tcheharabic=1670;e.tchehfinalarabic=64379;e.tchehinitialarabic=64380;e.tchehmedialarabic=64381;e.tcircle=9443;e.tcircumflexbelow=7793;e.tcommaaccent=355;e.tdieresis=7831;e.tdotaccent=7787;e.tdotbelow=7789;e.tecyrillic=1090;e.tedescendercyrillic=1197;e.teharabic=1578;e.tehfinalarabic=65174;e.tehhahinitialarabic=64674;e.tehhahisolatedarabic=64524;e.tehinitialarabic=65175;e.tehiragana=12390;e.tehjeeminitialarabic=64673;e.tehjeemisolatedarabic=64523;e.tehmarbutaarabic=1577;e.tehmarbutafinalarabic=65172;e.tehmedialarabic=65176;e.tehmeeminitialarabic=64676;e.tehmeemisolatedarabic=64526;e.tehnoonfinalarabic=64627;e.tekatakana=12486;e.tekatakanahalfwidth=65411;e.telephone=8481;e.telephoneblack=9742;e.telishagedolahebrew=1440;e.telishaqetanahebrew=1449;e.tencircle=9321;e.tenideographicparen=12841;e.tenparen=9341;e.tenperiod=9361;e.tenroman=8569;e.tesh=679;e.tet=1496;e.tetdagesh=64312;e.tetdageshhebrew=64312;e.tethebrew=1496;e.tetsecyrillic=1205;e.tevirhebrew=1435;e.tevirlefthebrew=1435;e.thabengali=2469;e.thadeva=2341;e.thagujarati=2725;e.thagurmukhi=2597;e.thalarabic=1584;e.thalfinalarabic=65196;e.thanthakhatlowleftthai=63640;e.thanthakhatlowrightthai=63639;e.thanthakhatthai=3660;e.thanthakhatupperleftthai=63638;e.theharabic=1579;e.thehfinalarabic=65178;e.thehinitialarabic=65179;e.thehmedialarabic=65180;e.thereexists=8707;e.therefore=8756;e.theta=952;e.theta1=977;e.thetasymbolgreek=977;e.thieuthacirclekorean=12921;e.thieuthaparenkorean=12825;e.thieuthcirclekorean=12907;e.thieuthkorean=12620;e.thieuthparenkorean=12811;e.thirteencircle=9324;e.thirteenparen=9344;e.thirteenperiod=9364;e.thonangmonthothai=3601;e.thook=429;e.thophuthaothai=3602;e.thorn=254;e.thothahanthai=3607;e.thothanthai=3600;e.thothongthai=3608;e.thothungthai=3606;e.thousandcyrillic=1154;e.thousandsseparatorarabic=1644;e.thousandsseparatorpersian=1644;e.three=51;e.threearabic=1635;e.threebengali=2537;e.threecircle=9314;e.threecircleinversesansserif=10124;e.threedeva=2409;e.threeeighths=8540;e.threegujarati=2793;e.threegurmukhi=2665;e.threehackarabic=1635;e.threehangzhou=12323;e.threeideographicparen=12834;e.threeinferior=8323;e.threemonospace=65299;e.threenumeratorbengali=2550;e.threeoldstyle=63283;e.threeparen=9334;e.threeperiod=9354;e.threepersian=1779;e.threequarters=190;e.threequartersemdash=63198;e.threeroman=8562;e.threesuperior=179;e.threethai=3667;e.thzsquare=13204;e.tihiragana=12385;e.tikatakana=12481;e.tikatakanahalfwidth=65409;e.tikeutacirclekorean=12912;e.tikeutaparenkorean=12816;e.tikeutcirclekorean=12898;e.tikeutkorean=12599;e.tikeutparenkorean=12802;e.tilde=732;e.tildebelowcmb=816;e.tildecmb=771;e.tildecomb=771;e.tildedoublecmb=864;e.tildeoperator=8764;e.tildeoverlaycmb=820;e.tildeverticalcmb=830;e.timescircle=8855;e.tipehahebrew=1430;e.tipehalefthebrew=1430;e.tippigurmukhi=2672;e.titlocyrilliccmb=1155;e.tiwnarmenian=1407;e.tlinebelow=7791;e.tmonospace=65364;e.toarmenian=1385;e.tohiragana=12392;e.tokatakana=12488;e.tokatakanahalfwidth=65412;e.tonebarextrahighmod=741;e.tonebarextralowmod=745;e.tonebarhighmod=742;e.tonebarlowmod=744;e.tonebarmidmod=743;e.tonefive=445;e.tonesix=389;e.tonetwo=424;e.tonos=900;e.tonsquare=13095;e.topatakthai=3599;e.tortoiseshellbracketleft=12308;e.tortoiseshellbracketleftsmall=65117;e.tortoiseshellbracketleftvertical=65081;e.tortoiseshellbracketright=12309;e.tortoiseshellbracketrightsmall=65118;e.tortoiseshellbracketrightvertical=65082;e.totaothai=3605;e.tpalatalhook=427;e.tparen=9391;e.trademark=8482;e.trademarksans=63722;e.trademarkserif=63195;e.tretroflexhook=648;e.triagdn=9660;e.triaglf=9668;e.triagrt=9658;e.triagup=9650;e.ts=678;e.tsadi=1510;e.tsadidagesh=64326;e.tsadidageshhebrew=64326;e.tsadihebrew=1510;e.tsecyrillic=1094;e.tsere=1461;e.tsere12=1461;e.tsere1e=1461;e.tsere2b=1461;e.tserehebrew=1461;e.tserenarrowhebrew=1461;e.tserequarterhebrew=1461;e.tserewidehebrew=1461;e.tshecyrillic=1115;e.tsuperior=63219;e.ttabengali=2463;e.ttadeva=2335;e.ttagujarati=2719;e.ttagurmukhi=2591;e.tteharabic=1657;e.ttehfinalarabic=64359;e.ttehinitialarabic=64360;e.ttehmedialarabic=64361;e.tthabengali=2464;e.tthadeva=2336;e.tthagujarati=2720;e.tthagurmukhi=2592;e.tturned=647;e.tuhiragana=12388;e.tukatakana=12484;e.tukatakanahalfwidth=65410;e.tusmallhiragana=12387;e.tusmallkatakana=12483;e.tusmallkatakanahalfwidth=65391;e.twelvecircle=9323;e.twelveparen=9343;e.twelveperiod=9363;e.twelveroman=8571;e.twentycircle=9331;e.twentyhangzhou=21316;e.twentyparen=9351;e.twentyperiod=9371;e.two=50;e.twoarabic=1634;e.twobengali=2536;e.twocircle=9313;e.twocircleinversesansserif=10123;e.twodeva=2408;e.twodotenleader=8229;e.twodotleader=8229;e.twodotleadervertical=65072;e.twogujarati=2792;e.twogurmukhi=2664;e.twohackarabic=1634;e.twohangzhou=12322;e.twoideographicparen=12833;e.twoinferior=8322;e.twomonospace=65298;e.twonumeratorbengali=2549;e.twooldstyle=63282;e.twoparen=9333;e.twoperiod=9353;e.twopersian=1778;e.tworoman=8561;e.twostroke=443;e.twosuperior=178;e.twothai=3666;e.twothirds=8532;e.u=117;e.uacute=250;e.ubar=649;e.ubengali=2441;e.ubopomofo=12584;e.ubreve=365;e.ucaron=468;e.ucircle=9444;e.ucircumflex=251;e.ucircumflexbelow=7799;e.ucyrillic=1091;e.udattadeva=2385;e.udblacute=369;e.udblgrave=533;e.udeva=2313;e.udieresis=252;e.udieresisacute=472;e.udieresisbelow=7795;e.udieresiscaron=474;e.udieresiscyrillic=1265;e.udieresisgrave=476;e.udieresismacron=470;e.udotbelow=7909;e.ugrave=249;e.ugujarati=2697;e.ugurmukhi=2569;e.uhiragana=12358;e.uhookabove=7911;e.uhorn=432;e.uhornacute=7913;e.uhorndotbelow=7921;e.uhorngrave=7915;e.uhornhookabove=7917;e.uhorntilde=7919;e.uhungarumlaut=369;e.uhungarumlautcyrillic=1267;e.uinvertedbreve=535;e.ukatakana=12454;e.ukatakanahalfwidth=65395;e.ukcyrillic=1145;e.ukorean=12636;e.umacron=363;e.umacroncyrillic=1263;e.umacrondieresis=7803;e.umatragurmukhi=2625;e.umonospace=65365;e.underscore=95;e.underscoredbl=8215;e.underscoremonospace=65343;e.underscorevertical=65075;e.underscorewavy=65103;e.union=8746;e.universal=8704;e.uogonek=371;e.uparen=9392;e.upblock=9600;e.upperdothebrew=1476;e.upsilon=965;e.upsilondieresis=971;e.upsilondieresistonos=944;e.upsilonlatin=650;e.upsilontonos=973;e.uptackbelowcmb=797;e.uptackmod=724;e.uragurmukhi=2675;e.uring=367;e.ushortcyrillic=1118;e.usmallhiragana=12357;e.usmallkatakana=12453;e.usmallkatakanahalfwidth=65385;e.ustraightcyrillic=1199;e.ustraightstrokecyrillic=1201;e.utilde=361;e.utildeacute=7801;e.utildebelow=7797;e.uubengali=2442;e.uudeva=2314;e.uugujarati=2698;e.uugurmukhi=2570;e.uumatragurmukhi=2626;e.uuvowelsignbengali=2498;e.uuvowelsigndeva=2370;e.uuvowelsigngujarati=2754;e.uvowelsignbengali=2497;e.uvowelsigndeva=2369;e.uvowelsigngujarati=2753;e.v=118;e.vadeva=2357;e.vagujarati=2741;e.vagurmukhi=2613;e.vakatakana=12535;e.vav=1493;e.vavdagesh=64309;e.vavdagesh65=64309;e.vavdageshhebrew=64309;e.vavhebrew=1493;e.vavholam=64331;e.vavholamhebrew=64331;e.vavvavhebrew=1520;e.vavyodhebrew=1521;e.vcircle=9445;e.vdotbelow=7807;e.vecyrillic=1074;e.veharabic=1700;e.vehfinalarabic=64363;e.vehinitialarabic=64364;e.vehmedialarabic=64365;e.vekatakana=12537;e.venus=9792;e.verticalbar=124;e.verticallineabovecmb=781;e.verticallinebelowcmb=809;e.verticallinelowmod=716;e.verticallinemod=712;e.vewarmenian=1406;e.vhook=651;e.vikatakana=12536;e.viramabengali=2509;e.viramadeva=2381;e.viramagujarati=2765;e.visargabengali=2435;e.visargadeva=2307;e.visargagujarati=2691;e.vmonospace=65366;e.voarmenian=1400;e.voicediterationhiragana=12446;e.voicediterationkatakana=12542;e.voicedmarkkana=12443;e.voicedmarkkanahalfwidth=65438;e.vokatakana=12538;e.vparen=9393;e.vtilde=7805;e.vturned=652;e.vuhiragana=12436;e.vukatakana=12532;e.w=119;e.wacute=7811;e.waekorean=12633;e.wahiragana=12431;e.wakatakana=12527;e.wakatakanahalfwidth=65436;e.wakorean=12632;e.wasmallhiragana=12430;e.wasmallkatakana=12526;e.wattosquare=13143;e.wavedash=12316;e.wavyunderscorevertical=65076;e.wawarabic=1608;e.wawfinalarabic=65262;e.wawhamzaabovearabic=1572;e.wawhamzaabovefinalarabic=65158;e.wbsquare=13277;e.wcircle=9446;e.wcircumflex=373;e.wdieresis=7813;e.wdotaccent=7815;e.wdotbelow=7817;e.wehiragana=12433;e.weierstrass=8472;e.wekatakana=12529;e.wekorean=12638;e.weokorean=12637;e.wgrave=7809;e.whitebullet=9702;e.whitecircle=9675;e.whitecircleinverse=9689;e.whitecornerbracketleft=12302;e.whitecornerbracketleftvertical=65091;e.whitecornerbracketright=12303;e.whitecornerbracketrightvertical=65092;e.whitediamond=9671;e.whitediamondcontainingblacksmalldiamond=9672;e.whitedownpointingsmalltriangle=9663;e.whitedownpointingtriangle=9661;e.whiteleftpointingsmalltriangle=9667;e.whiteleftpointingtriangle=9665;e.whitelenticularbracketleft=12310;e.whitelenticularbracketright=12311;e.whiterightpointingsmalltriangle=9657;e.whiterightpointingtriangle=9655;e.whitesmallsquare=9643;e.whitesmilingface=9786;e.whitesquare=9633;e.whitestar=9734;e.whitetelephone=9743;e.whitetortoiseshellbracketleft=12312;e.whitetortoiseshellbracketright=12313;e.whiteuppointingsmalltriangle=9653;e.whiteuppointingtriangle=9651;e.wihiragana=12432;e.wikatakana=12528;e.wikorean=12639;e.wmonospace=65367;e.wohiragana=12434;e.wokatakana=12530;e.wokatakanahalfwidth=65382;e.won=8361;e.wonmonospace=65510;e.wowaenthai=3623;e.wparen=9394;e.wring=7832;e.wsuperior=695;e.wturned=653;e.wynn=447;e.x=120;e.xabovecmb=829;e.xbopomofo=12562;e.xcircle=9447;e.xdieresis=7821;e.xdotaccent=7819;e.xeharmenian=1389;e.xi=958;e.xmonospace=65368;e.xparen=9395;e.xsuperior=739;e.y=121;e.yaadosquare=13134;e.yabengali=2479;e.yacute=253;e.yadeva=2351;e.yaekorean=12626;e.yagujarati=2735;e.yagurmukhi=2607;e.yahiragana=12420;e.yakatakana=12516;e.yakatakanahalfwidth=65428;e.yakorean=12625;e.yamakkanthai=3662;e.yasmallhiragana=12419;e.yasmallkatakana=12515;e.yasmallkatakanahalfwidth=65388;e.yatcyrillic=1123;e.ycircle=9448;e.ycircumflex=375;e.ydieresis=255;e.ydotaccent=7823;e.ydotbelow=7925;e.yeharabic=1610;e.yehbarreearabic=1746;e.yehbarreefinalarabic=64431;e.yehfinalarabic=65266;e.yehhamzaabovearabic=1574;e.yehhamzaabovefinalarabic=65162;e.yehhamzaaboveinitialarabic=65163;e.yehhamzaabovemedialarabic=65164;e.yehinitialarabic=65267;e.yehmedialarabic=65268;e.yehmeeminitialarabic=64733;e.yehmeemisolatedarabic=64600;e.yehnoonfinalarabic=64660;e.yehthreedotsbelowarabic=1745;e.yekorean=12630;e.yen=165;e.yenmonospace=65509;e.yeokorean=12629;e.yeorinhieuhkorean=12678;e.yerahbenyomohebrew=1450;e.yerahbenyomolefthebrew=1450;e.yericyrillic=1099;e.yerudieresiscyrillic=1273;e.yesieungkorean=12673;e.yesieungpansioskorean=12675;e.yesieungsioskorean=12674;e.yetivhebrew=1434;e.ygrave=7923;e.yhook=436;e.yhookabove=7927;e.yiarmenian=1397;e.yicyrillic=1111;e.yikorean=12642;e.yinyang=9775;e.yiwnarmenian=1410;e.ymonospace=65369;e.yod=1497;e.yoddagesh=64313;e.yoddageshhebrew=64313;e.yodhebrew=1497;e.yodyodhebrew=1522;e.yodyodpatahhebrew=64287;e.yohiragana=12424;e.yoikorean=12681;e.yokatakana=12520;e.yokatakanahalfwidth=65430;e.yokorean=12635;e.yosmallhiragana=12423;e.yosmallkatakana=12519;e.yosmallkatakanahalfwidth=65390;e.yotgreek=1011;e.yoyaekorean=12680;e.yoyakorean=12679;e.yoyakthai=3618;e.yoyingthai=3597;e.yparen=9396;e.ypogegrammeni=890;e.ypogegrammenigreekcmb=837;e.yr=422;e.yring=7833;e.ysuperior=696;e.ytilde=7929;e.yturned=654;e.yuhiragana=12422;e.yuikorean=12684;e.yukatakana=12518;e.yukatakanahalfwidth=65429;e.yukorean=12640;e.yusbigcyrillic=1131;e.yusbigiotifiedcyrillic=1133;e.yuslittlecyrillic=1127;e.yuslittleiotifiedcyrillic=1129;e.yusmallhiragana=12421;e.yusmallkatakana=12517;e.yusmallkatakanahalfwidth=65389;e.yuyekorean=12683;e.yuyeokorean=12682;e.yyabengali=2527;e.yyadeva=2399;e.z=122;e.zaarmenian=1382;e.zacute=378;e.zadeva=2395;e.zagurmukhi=2651;e.zaharabic=1592;e.zahfinalarabic=65222;e.zahinitialarabic=65223;e.zahiragana=12374;e.zahmedialarabic=65224;e.zainarabic=1586;e.zainfinalarabic=65200;e.zakatakana=12470;e.zaqefgadolhebrew=1429;e.zaqefqatanhebrew=1428;e.zarqahebrew=1432;e.zayin=1494;e.zayindagesh=64310;e.zayindageshhebrew=64310;e.zayinhebrew=1494;e.zbopomofo=12567;e.zcaron=382;e.zcircle=9449;e.zcircumflex=7825;e.zcurl=657;e.zdot=380;e.zdotaccent=380;e.zdotbelow=7827;e.zecyrillic=1079;e.zedescendercyrillic=1177;e.zedieresiscyrillic=1247;e.zehiragana=12380;e.zekatakana=12476;e.zero=48;e.zeroarabic=1632;e.zerobengali=2534;e.zerodeva=2406;e.zerogujarati=2790;e.zerogurmukhi=2662;e.zerohackarabic=1632;e.zeroinferior=8320;e.zeromonospace=65296;e.zerooldstyle=63280;e.zeropersian=1776;e.zerosuperior=8304;e.zerothai=3664;e.zerowidthjoiner=65279;e.zerowidthnonjoiner=8204;e.zerowidthspace=8203;e.zeta=950;e.zhbopomofo=12563;e.zhearmenian=1386;e.zhebrevecyrillic=1218;e.zhecyrillic=1078;e.zhedescendercyrillic=1175;e.zhedieresiscyrillic=1245;e.zihiragana=12376;e.zikatakana=12472;e.zinorhebrew=1454;e.zlinebelow=7829;e.zmonospace=65370;e.zohiragana=12382;e.zokatakana=12478;e.zparen=9397;e.zretroflexhook=656;e.zstroke=438;e.zuhiragana=12378;e.zukatakana=12474;e[".notdef"]=0;e.angbracketleftbig=9001;e.angbracketleftBig=9001;e.angbracketleftbigg=9001;e.angbracketleftBigg=9001;e.angbracketrightBig=9002;e.angbracketrightbig=9002;e.angbracketrightBigg=9002;e.angbracketrightbigg=9002;e.arrowhookleft=8618;e.arrowhookright=8617;e.arrowlefttophalf=8636;e.arrowleftbothalf=8637;e.arrownortheast=8599;e.arrownorthwest=8598;e.arrowrighttophalf=8640;e.arrowrightbothalf=8641;e.arrowsoutheast=8600;e.arrowsouthwest=8601;e.backslashbig=8726;e.backslashBig=8726;e.backslashBigg=8726;e.backslashbigg=8726;e.bardbl=8214;e.bracehtipdownleft=65079;e.bracehtipdownright=65079;e.bracehtipupleft=65080;e.bracehtipupright=65080;e.braceleftBig=123;e.braceleftbig=123;e.braceleftbigg=123;e.braceleftBigg=123;e.bracerightBig=125;e.bracerightbig=125;e.bracerightbigg=125;e.bracerightBigg=125;e.bracketleftbig=91;e.bracketleftBig=91;e.bracketleftbigg=91;e.bracketleftBigg=91;e.bracketrightBig=93;e.bracketrightbig=93;e.bracketrightbigg=93;e.bracketrightBigg=93;e.ceilingleftbig=8968;e.ceilingleftBig=8968;e.ceilingleftBigg=8968;e.ceilingleftbigg=8968;e.ceilingrightbig=8969;e.ceilingrightBig=8969;e.ceilingrightbigg=8969;e.ceilingrightBigg=8969;e.circledotdisplay=8857;e.circledottext=8857;e.circlemultiplydisplay=8855;e.circlemultiplytext=8855;e.circleplusdisplay=8853;e.circleplustext=8853;e.contintegraldisplay=8750;e.contintegraltext=8750;e.coproductdisplay=8720;e.coproducttext=8720;e.floorleftBig=8970;e.floorleftbig=8970;e.floorleftbigg=8970;e.floorleftBigg=8970;e.floorrightbig=8971;e.floorrightBig=8971;e.floorrightBigg=8971;e.floorrightbigg=8971;e.hatwide=770;e.hatwider=770;e.hatwidest=770;e.intercal=7488;e.integraldisplay=8747;e.integraltext=8747;e.intersectiondisplay=8898;e.intersectiontext=8898;e.logicalanddisplay=8743;e.logicalandtext=8743;e.logicalordisplay=8744;e.logicalortext=8744;e.parenleftBig=40;e.parenleftbig=40;e.parenleftBigg=40;e.parenleftbigg=40;e.parenrightBig=41;e.parenrightbig=41;e.parenrightBigg=41;e.parenrightbigg=41;e.prime=8242;e.productdisplay=8719;e.producttext=8719;e.radicalbig=8730;e.radicalBig=8730;e.radicalBigg=8730;e.radicalbigg=8730;e.radicalbt=8730;e.radicaltp=8730;e.radicalvertex=8730;e.slashbig=47;e.slashBig=47;e.slashBigg=47;e.slashbigg=47;e.summationdisplay=8721;e.summationtext=8721;e.tildewide=732;e.tildewider=732;e.tildewidest=732;e.uniondisplay=8899;e.unionmultidisplay=8846;e.unionmultitext=8846;e.unionsqdisplay=8852;e.unionsqtext=8852;e.uniontext=8899;e.vextenddouble=8741;e.vextendsingle=8739}),gr=getLookupTableFactory(function(e){e.space=32;e.a1=9985;e.a2=9986;e.a202=9987;e.a3=9988;e.a4=9742;e.a5=9990;e.a119=9991;e.a118=9992;e.a117=9993;e.a11=9755;e.a12=9758;e.a13=9996;e.a14=9997;e.a15=9998;e.a16=9999;e.a105=1e4;e.a17=10001;e.a18=10002;e.a19=10003;e.a20=10004;e.a21=10005;e.a22=10006;e.a23=10007;e.a24=10008;e.a25=10009;e.a26=10010;e.a27=10011;e.a28=10012;e.a6=10013;e.a7=10014;e.a8=10015;e.a9=10016;e.a10=10017;e.a29=10018;e.a30=10019;e.a31=10020;e.a32=10021;e.a33=10022;e.a34=10023;e.a35=9733;e.a36=10025;e.a37=10026;e.a38=10027;e.a39=10028;e.a40=10029;e.a41=10030;e.a42=10031;e.a43=10032;e.a44=10033;e.a45=10034;e.a46=10035;e.a47=10036;e.a48=10037;e.a49=10038;e.a50=10039;e.a51=10040;e.a52=10041;e.a53=10042;e.a54=10043;e.a55=10044;e.a56=10045;e.a57=10046;e.a58=10047;e.a59=10048;e.a60=10049;e.a61=10050;e.a62=10051;e.a63=10052;e.a64=10053;e.a65=10054;e.a66=10055;e.a67=10056;e.a68=10057;e.a69=10058;e.a70=10059;e.a71=9679;e.a72=10061;e.a73=9632;e.a74=10063;e.a203=10064;e.a75=10065;e.a204=10066;e.a76=9650;e.a77=9660;e.a78=9670;e.a79=10070;e.a81=9687;e.a82=10072;e.a83=10073;e.a84=10074;e.a97=10075;e.a98=10076;e.a99=10077;e.a100=10078;e.a101=10081;e.a102=10082;e.a103=10083;e.a104=10084;e.a106=10085;e.a107=10086;e.a108=10087;e.a112=9827;e.a111=9830;e.a110=9829;e.a109=9824;e.a120=9312;e.a121=9313;e.a122=9314;e.a123=9315;e.a124=9316;e.a125=9317;e.a126=9318;e.a127=9319;e.a128=9320;e.a129=9321;e.a130=10102;e.a131=10103;e.a132=10104;e.a133=10105;e.a134=10106;e.a135=10107;e.a136=10108;e.a137=10109;e.a138=10110;e.a139=10111;e.a140=10112;e.a141=10113;e.a142=10114;e.a143=10115;e.a144=10116;e.a145=10117;e.a146=10118;e.a147=10119;e.a148=10120;e.a149=10121;e.a150=10122;e.a151=10123;e.a152=10124;e.a153=10125;e.a154=10126;e.a155=10127;e.a156=10128;e.a157=10129;e.a158=10130;e.a159=10131;e.a160=10132;e.a161=8594;e.a163=8596;e.a164=8597;e.a196=10136;e.a165=10137;e.a192=10138;e.a166=10139;e.a167=10140;e.a168=10141;e.a169=10142;e.a170=10143;e.a171=10144;e.a172=10145;e.a173=10146;e.a162=10147;e.a174=10148;e.a175=10149;e.a176=10150;e.a177=10151;e.a178=10152;e.a179=10153;e.a193=10154;e.a180=10155;e.a199=10156;e.a181=10157;e.a200=10158;e.a182=10159;e.a201=10161;e.a183=10162;e.a184=10163;e.a197=10164;e.a185=10165;e.a194=10166;e.a198=10167;e.a186=10168;e.a195=10169;e.a187=10170;e.a188=10171;e.a189=10172;e.a190=10173;e.a191=10174;e.a89=10088;e.a90=10089;e.a93=10090;e.a94=10091;e.a91=10092;e.a92=10093;e.a205=10094;e.a85=10095;e.a206=10096;e.a86=10097;e.a87=10098;e.a88=10099;e.a95=10100;e.a96=10101;e[".notdef"]=0}),pr=getLookupTableFactory(function(e){e[63721]=169;e[63193]=169;e[63720]=174;e[63194]=174;e[63722]=8482;e[63195]=8482;e[63729]=9127;e[63730]=9128;e[63731]=9129;e[63740]=9131;e[63741]=9132;e[63742]=9133;e[63726]=9121;e[63727]=9122;e[63728]=9123;e[63737]=9124;e[63738]=9125;e[63739]=9126;e[63723]=9115;e[63724]=9116;e[63725]=9117;e[63734]=9118;e[63735]=9119;e[63736]=9120});function getUnicodeForGlyph(e,t){let a=t[e];if(void 0!==a)return a;if(!e)return-1;if("u"===e[0]){const t=e.length;let r;if(7===t&&"n"===e[1]&&"i"===e[2])r=e.substring(3);else{if(!(t>=5&&t<=7))return-1;r=e.substring(1)}if(r===r.toUpperCase()){a=parseInt(r,16);if(a>=0)return a}}return-1}const mr=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const a=mr[t];for(let r=0,i=a.length;r=a[r]&&e<=a[r+1])return t}for(let t=0,a=mr.length;t=a[r]&&e<=a[r+1])return t}return-1}const br=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),yr=new Map;const wr=!0,xr=1,Sr=2,Ar=4,kr=32,Cr=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const a=getUnicodeForGlyph(e,t);if(-1!==a)for(const e in t)if(t[e]===a)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,a){const r=Object.create(null);let i,n,s;const o=!!(e.flags&Ar);if(e.isInternalFont){s=t;for(n=0;n=0?i:0}}else if(e.baseEncodingName){s=getEncoding(e.baseEncodingName);for(n=0;n=0?i:0}}else if(o)for(n in t)r[n]=t[n];else{s=lr;for(n=0;n=0?i:0}}const c=e.differences;let l;if(c)for(n in c){const e=c[n];i=a.indexOf(e);if(-1===i){l||(l=fr());const t=recoverGlyphName(e,l);t!==e&&(i=a.indexOf(t))}r[n]=i>=0?i:0}return r}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const vr=getLookupTableFactory(e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080});const Fr=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],Ir=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],Tr=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Or=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],Dr=391,Mr=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1},{id:"return",min:0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],Rr=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,a){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!a}parse(){const e=this.properties,t=new CFF;this.cff=t;const a=this.parseHeader(),r=this.parseIndex(a.endPos),i=this.parseIndex(r.endPos),n=this.parseIndex(i.endPos),s=this.parseIndex(n.endPos),o=this.parseDict(i.obj.get(0)),c=this.createDict(CFFTopDict,o,t.strings);t.header=a.obj;t.names=this.parseNameIndex(r.obj);t.strings=this.parseStringIndex(n.obj);t.topDict=c;t.globalSubrIndex=s.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=c.hasName("ROS");const l=c.getByName("CharStrings"),h=this.parseIndex(l).obj;t.charStringCount=h.count;const u=c.getByName("FontMatrix");u&&(e.fontMatrix=u);const d=c.getByName("FontBBox");if(d){e.ascent=Math.max(d[3],d[1]);e.descent=Math.min(d[1],d[3]);e.ascentScaled=!0}let f,g;if(t.isCIDFont){const e=this.parseIndex(c.getByName("FDArray")).obj;for(let a=0,r=e.count;a=t)throw new FormatError("Invalid CFF header");if(0!==a){info("cff data is shifted");e=e.subarray(a);this.bytes=e}const r=e[0],i=e[1],n=e[2],s=e[3];return{obj:new CFFHeader(r,i,n,s),endPos:n}}parseDict(e){let t=0;function parseOperand(){let a=e[t++];if(30===a)return function parseFloatOperand(){let a="";const r=15,i=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],n=e.length;for(;t>4,o=15&n;if(s===r)break;a+=i[s];if(o===r)break;a+=i[o]}return parseFloat(a)}();if(28===a){a=readInt16(e,t);t+=2;return a}if(29===a){a=e[t++];a=a<<8|e[t++];a=a<<8|e[t++];a=a<<8|e[t++];return a}if(a>=32&&a<=246)return a-139;if(a>=247&&a<=250)return 256*(a-247)+e[t++]+108;if(a>=251&&a<=254)return-256*(a-251)-e[t++]-108;warn('CFFParser_parseDict: "'+a+'" is a reserved command.');return NaN}let a=[];const r=[];t=0;const i=e.length;for(;t10)return!1;let i=e.stackSize;const n=e.stack;let s=t.length;for(let o=0;o=4){i-=4;if(this.seacAnalysisEnabled){e.seac=n.slice(i,i+4);return!1}}l=Mr[c]}else if(c>=32&&c<=246){n[i]=c-139;i++}else if(c>=247&&c<=254){n[i]=c<251?(c-247<<8)+t[o]+108:-(c-251<<8)-t[o]-108;o++;i++}else if(255===c){n[i]=(t[o]<<24|t[o+1]<<16|t[o+2]<<8|t[o+3])/65536;o+=4;i++}else if(19===c||20===c){e.hints+=i>>1;if(0===e.hints){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}o+=e.hints+7>>3;i%=2;l=Mr[c]}else{if(10===c||29===c){const t=10===c?a:r;if(!t){l=Mr[c];warn("Missing subrsIndex for "+l.id);return!1}let s=32768;t.count<1240?s=107:t.count<33900&&(s=1131);const o=n[--i]+s;if(o<0||o>=t.count||isNaN(o)){l=Mr[c];warn("Out of bounds subrIndex for "+l.id);return!1}e.stackSize=i;e.callDepth++;if(!this.parseCharString(e,t.get(o),a,r))return!1;e.callDepth--;i=e.stackSize;continue}if(11===c){e.stackSize=i;return!0}if(0===c&&o===t.length){t[o-1]=14;l=Mr[14]}else{if(9===c){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}l=Mr[c]}}if(l){if(l.stem){e.hints+=i>>1;if(3===c||23===c)e.hasVStems=!0;else if(e.hasVStems&&(1===c||18===c)){warn("CFF stem hints are in wrong order");t[o-1]=1===c?3:23}}if(i=2&&l.stem?i%=2:i>1&&warn("Found too many parameters for stack-clearing command");i>0&&(e.width=n[i-1])}if("stackDelta"in l){"stackFn"in l&&l.stackFn(n,i);i+=l.stackDelta}else(l.stackClearing||l.resetStack)&&(i=0)}}s=i.length){warn("Invalid fd index for glyph index.");u=!1}if(u){f=i[e].privateDict;d=f.subrsIndex}}else t&&(d=t);u&&(u=this.parseCharString(h,c,d,a));if(null!==h.width){const e=f.getByName("nominalWidthX");o[l]=e+h.width}else{const e=f.getByName("defaultWidthX");o[l]=e}null!==h.seac&&(s[l]=h.seac);u||e.set(l,new Uint8Array([14]))}return{charStrings:e,seacs:s,widths:o}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const a=t[0],r=t[1];if(0===a||r>=this.bytes.length){this.emptyPrivateDictionary(e);return}const i=r+a,n=this.bytes.subarray(r,i),s=this.parseDict(n),o=this.createDict(CFFPrivateDict,s,e.strings);e.privateDict=o;0===o.getByName("ExpansionFactor")&&o.setByName("ExpansionFactor",.06);if(!o.getByName("Subrs"))return;const c=o.getByName("Subrs"),l=r+c;if(0===c||l>=this.bytes.length){this.emptyPrivateDictionary(e);return}const h=this.parseIndex(l);o.subrsIndex=h.obj}parseCharsets(e,t,a,r){if(0===e)return new CFFCharset(!0,Er.ISO_ADOBE,Fr);if(1===e)return new CFFCharset(!0,Er.EXPERT,Ir);if(2===e)return new CFFCharset(!0,Er.EXPERT_SUBSET,Tr);const i=this.bytes,n=e,s=i[e++],o=[r?0:".notdef"];let c,l,h;t-=1;switch(s){case 0:for(h=0;h=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,a,r){this.major=e;this.minor=t;this.hdrSize=a;this.offSize=r}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Or[e]:e-Dr<=this.strings.length?this.strings[e-Dr]:Or[0]}getSID(e){let t=Or.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+Dr:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const a of t)if(isNaN(a)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const a=this.types[e];"num"!==a&&"sid"!==a&&"offset"!==a||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const a of e){const e=Array.isArray(a[0])?(a[0][0]<<8)+a[0][1]:a[0];t.keyToNameMap[e]=a[1];t.nameToKeyMap[a[1]]=e;t.types[e]=a[2];t.defaults[e]=a[3];t.opcodes[e]=Array.isArray(a[0])?a[0]:[a[0]];t.order.push(e)}return t}}const Nr=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(Nr))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const Pr=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(Pr))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const Er={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,a,r){this.predefined=e;this.format=t;this.charset=a;this.raw=r}}class CFFEncoding{constructor(e,t,a,r){this.predefined=e;this.format=t;this.encoding=a;this.raw=r}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,a){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const r=a.data,i=this.offsets[e];for(let e=0,a=t.length;e>24&255;r[s]=l>>16&255;r[o]=l>>8&255;r[c]=255&l}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},a=this.compileHeader(e.header);t.add(a);const r=this.compileNameIndex(e.names);t.add(r);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const a of e.fdArray){let e=t.slice(0);a.hasName("FontMatrix")&&(e=Util.transform(e,a.getByName("FontMatrix")));a.setByName("FontMatrix",e)}}const i=e.topDict.getByName("XUID");i?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let n=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(n.output);const s=n.trackers[0],o=this.compileStringIndex(e.strings.strings);t.add(o);const c=this.compileIndex(e.globalSubrIndex);t.add(c);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)s.setEntryLocation("Encoding",[e.encoding.format],t);else{const a=this.compileEncoding(e.encoding);s.setEntryLocation("Encoding",[t.length],t);t.add(a)}const l=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);s.setEntryLocation("charset",[t.length],t);t.add(l);const h=this.compileCharStrings(e.charStrings);s.setEntryLocation("CharStrings",[t.length],t);t.add(h);if(e.isCIDFont){s.setEntryLocation("FDSelect",[t.length],t);const a=this.compileFDSelect(e.fdSelect);t.add(a);n=this.compileTopDicts(e.fdArray,t.length,!0);s.setEntryLocation("FDArray",[t.length],t);t.add(n.output);const r=n.trackers;this.compilePrivateDicts(e.fdArray,r,t)}this.compilePrivateDicts([e.topDict],[s],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const a=CFFCompiler.EncodeFloatRegExp.exec(t);if(a){const r=parseFloat("1e"+((a[2]?+a[2]:0)+a[1].length));t=(Math.round(e*r)/r).toString()}let r,i,n="";for(r=0,i=t.length;r=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const a of e){const e=Math.min(a.length,127);let r=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");r[t]=e}r=r.join("");""===r&&(r="Bad_Font_Name");t.add(stringToBytes(r))}return this.compileIndex(t)}compileTopDicts(e,t,a){const r=[];let i=new CFFIndex;for(const n of e){if(a){n.removeByName("CIDFontVersion");n.removeByName("CIDFontRevision");n.removeByName("CIDFontType");n.removeByName("CIDCount");n.removeByName("UIDBase")}const e=new CFFOffsetTracker,s=this.compileDict(n,e);r.push(e);i.add(s);e.offset(t)}i=this.compileIndex(i,r);return{trackers:r,output:i}}compilePrivateDicts(e,t,a){for(let r=0,i=e.length;r>8&255,255&e])}else{i=new Uint8Array(1+2*n);i[0]=0;let t=0;const r=e.charset.length;let s=!1;for(let n=1;n>8&255;i[n+1]=255&o}}return this.compileTypedArray(i)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let a,r;switch(t){case 0:a=new Uint8Array(1+e.fdSelect.length);a[0]=t;for(r=0;r>8&255,255&i,n];for(r=1;r>8&255,255&r,t);n=t}}const o=(s.length-3)/3;s[1]=o>>8&255;s[2]=255&o;s.push(r>>8&255,255&r);a=new Uint8Array(s)}return this.compileTypedArray(a)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const a=e.objects,r=a.length;if(0===r)return[0,0];const i=[r>>8&255,255&r];let n,s,o=1;for(n=0;n>8&255,255&c):3===s?i.push(c>>16&255,c>>8&255,255&c):i.push(c>>>24&255,c>>16&255,c>>8&255,255&c);a[n]&&(c+=a[n].length)}for(n=0;n=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const a=new CFFParser(e,t,wr);this.cff=a.parse();this.cff.duplicateFirstGlyph();const r=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=r.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:a,cMap:r}=t,i=e.charset.charset;let n,s;if(t.composite){let t,o;if(a?.length>0){t=Object.create(null);for(let e=0,r=a.length;e=0){const r=a[t];r&&(i[e]=r)}}i.length>0&&(this.properties.builtInEncoding=i)}}function getFloat214(e,t){return readInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let a=32768;t<1240?a=107:t<33900&&(a=1131);return a}function parseCmap(e,t,a){const r=1===readUint16(e,t+2)?readUint32(e,t+8):readUint32(e,t+16),i=readUint16(e,t+r);let n,s,o;if(4===i){readUint16(e,t+r+2);const a=readUint16(e,t+r+6)>>1;s=t+r+14;n=[];for(o=0;o>1;a0;)h.push({flags:n})}for(a=0;a>1;y=!0;break;case 4:s+=i.pop();moveTo(n,s);y=!0;break;case 5:for(;i.length>0;){n+=i.shift();s+=i.shift();lineTo(n,s)}break;case 6:for(;i.length>0;){n+=i.shift();lineTo(n,s);if(0===i.length)break;s+=i.shift();lineTo(n,s)}break;case 7:for(;i.length>0;){s+=i.shift();lineTo(n,s);if(0===i.length)break;n+=i.shift();lineTo(n,s)}break;case 8:for(;i.length>0;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 10:m=i.pop();b=null;if(a.isCFFCIDFont){const e=a.fdSelect.getFDIndex(r);if(e>=0&&eMath.abs(s-t)?n+=i.shift():s+=i.shift();bezierCurveTo(l,u,h,d,n,s);break;default:throw new FormatError(`unknown operator: 12 ${w}`)}break;case 14:if(i.length>=4){const e=i.pop(),r=i.pop();s=i.pop();n=i.pop();t.save();t.translate(n,s);let o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[e]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId);t.restore();o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[r]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId)}return;case 19:case 20:o+=i.length>>1;c+=o+7>>3;y=!0;break;case 21:s+=i.pop();n+=i.pop();moveTo(n,s);y=!0;break;case 22:n+=i.pop();moveTo(n,s);y=!0;break;case 24:for(;i.length>2;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}n+=i.shift();s+=i.shift();lineTo(n,s);break;case 25:for(;i.length>6;){n+=i.shift();s+=i.shift();lineTo(n,s)}l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s);break;case 26:i.length%2&&(n+=i.shift());for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h;s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 27:i.length%2&&(s+=i.shift());for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d;bezierCurveTo(l,u,h,d,n,s)}break;case 28:i.push(readInt16(e,c));c+=2;break;case 29:m=i.pop()+a.gsubrsBias;b=a.gsubrs[m];b&&parse(b);break;case 30:for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;case 31:for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;default:if(w<32)throw new FormatError(`unknown operator: ${w}`);if(w<247)i.push(w-139);else if(w<251)i.push(256*(w-247)+e[c++]+108);else if(w<255)i.push(256*-(w-251)-e[c++]-108);else{i.push((e[c]<<24|e[c+1]<<16|e[c+2]<<8|e[c+3])/65536);c+=4}}y&&(i.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const{currentTransform:a}=this;for(let e=0,r=t.length;e=0&&e2*readUint16(e,t)}const n=[];let s=i(t,0);for(let a=r;ae.getSize()+3&-4))}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),a=e>131070,r=a?4:2,i=new DataView(new ArrayBuffer((this.glyphs.length+1)*r));a?i.setUint32(0,0):i.setUint16(0,0);let n=0,s=0;for(const e of this.glyphs){n+=e.write(n,t);n=n+3&-4;s+=r;a?i.setUint32(s,n):i.setUint16(s,n>>1)}return{isLocationLong:a,loca:new Uint8Array(i.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,a=this.glyphs.length;te.getSize()));return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const a=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const a of this.composites)e+=a.write(e,t);return e-a}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const a of this.composites)a.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:a,xMax:r,yMax:i}){this.numberOfContours=e;this.xMin=t;this.yMin=a;this.xMax=r;this.yMax=i}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:a}){this.xCoordinates=t;this.yCoordinates=a;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,a){const r=[];for(let i=0;i255?e+=2:o>0&&(e+=1);t=n;o=Math.abs(s-a);o>255?e+=2:o>0&&(e+=1);a=s}}return e}write(e,t){const a=e,r=[],i=[],n=[];let s=0,o=0;for(const a of this.contours){for(let e=0,t=a.xCoordinates.length;e=0?18:2;r.push(e)}else r.push(l)}s=c;const h=a.yCoordinates[e];l=h-o;if(0===l){t|=32;i.push(0)}else{const e=Math.abs(l);if(e<=255){t|=l>=0?36:4;i.push(e)}else i.push(l)}o=h;n.push(t)}t.setUint16(e,r.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const a of n)t.setUint8(e++,a);for(let a=0,i=r.length;a=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const a=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-a}scale(e,t){}}function writeInt16(e,t,a){e[t]=a>>8&255;e[t+1]=255&a}function writeInt32(e,t,a){e[t]=a>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}function writeData(e,t,a){if(a instanceof Uint8Array)e.set(a,t);else if("string"==typeof a)for(let r=0,i=a.length;ra;){a<<=1;r++}const i=a*t;return{range:i,entry:r,rangeShift:t*e-i}}toArray(){let e=this.sfnt;const t=this.tables,a=Object.keys(t);a.sort();const r=a.length;let i,n,s,o,c,l=12+16*r;const h=[l];for(i=0;i>>0;h.push(l)}const u=new Uint8Array(l);for(i=0;i>>0}writeInt32(u,l+4,e);writeInt32(u,l+8,h[i]);writeInt32(u,l+12,t[c].length);l+=16}return u}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const Gr=[4],Vr=[5],Kr=[6],Jr=[7],Yr=[8],Zr=[12,35],Qr=[14],ei=[21],ti=[22],ai=[30],ri=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,a){const r=e.length;let i,n,s,o=!1;for(let c=0;cr)return!0;const i=r-e;for(let e=i;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);a?this.stack.splice(i,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,a){if(a>=e.length)return new Uint8Array(0);let r,i,n=0|t;for(r=0;r>8;n=52845*(t+n)+22719&65535}return o}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,a){if(t){const t=e.getBytes(),a=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(a?decrypt(t,55665,4):function decryptAscii(e,t,a){let r=0|t;const i=e.length,n=new Uint8Array(i>>>1);let s,o;for(s=0,o=0;s>8;r=52845*(e+r)+22719&65535}}return n.slice(a,o)}(t,55665,4))}this.seacAnalysisEnabled=!!a;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let a="";do{a+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return a}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,a=[],r=[],i=Object.create(null);i.lenIV=4;const n={subrs:[],charstrings:[],properties:{privateData:i}};let s,o,c,l;for(;null!==(s=this.getToken());)if("/"===s){s=this.getToken();switch(s){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){s=this.getToken();if(null===s||"end"===s)break;if("/"!==s)continue;const e=this.getToken();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const a=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s?this.getToken():"/"===s&&this.prevChar();r.push({glyph:e,encoded:a})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const r=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s&&this.getToken();a[e]=r}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":n.properties.privateData[s]=this.readNumberArray();break;case"StdHW":case"StdVW":n.properties.privateData[s]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":n.properties.privateData[s]=this.readNumber();break;case"ExpansionFactor":n.properties.privateData[s]=this.readNumber()||.06;break;case"ForceBold":n.properties.privateData[s]=this.readBoolean()}}for(const{encoded:t,glyph:i}of r){const r=new Type1CharString,s=r.convert(t,a,this.seacAnalysisEnabled);let o=r.output;s&&(o=[14]);const c={glyphName:i,charstring:o,width:r.width,lsb:r.lsb,seac:r.seac};".notdef"===i?n.charstrings.unshift(c):n.charstrings.push(c);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(i);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=r.width)}}return n}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const a=this.readNumberArray();e.fontMatrix=a;break;case"Encoding":const r=this.getToken();let i;if(/^\d+$/.test(r)){i=[];const e=0|parseInt(r,10);this.getToken();for(let a=0;a=i){s+=a;for(;s=0&&(r[e]=i)}}return type1FontGlyphMapping(e,r,a)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let a=0,r=e.length;a0;e--)t[e]-=t[e-1];f.setByName(e,t)}n.topDict.privateDict=f;const p=new CFFIndex;for(h=0,u=r.length;h0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,a,r,i,n,s,o,c){this.originalCharCode=e;this.fontChar=t;this.unicode=a;this.accent=r;this.width=i;this.vmetric=n;this.operatorListId=s;this.isSpace=o;this.isInFont=c}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=yr.get(e);if(t)return t;const a=e.match(br),r={isWhitespace:!!a?.[1],isZeroWidthDiacritic:!!a?.[2],isInvisibleFormatMark:!!a?.[3]};yr.set(e,r);return r}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,a){e[t+1]=a;e[t]=a>>>8}function signedInt16(e,t){const a=(e<<8)+t;return 32768&a?a-65536:a}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:a,composite:r}){let i,n;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))i=r?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))i=r?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))i=r?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(r){i="CIDFontType0";n="CIDFontType0C"}else{i="MMType1"===t?"MMType1":"Type1";n="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");i=t;n=a}return[i,n]}function applyStandardFontGlyphMap(e,t){for(const a in t)e[+a]=t[a]}function buildToFontChar(e,t,a){const r=[];let i;for(let a=0,n=e.length;aii[0][0]<=e&&e<=ii[0][1]||ii[1][0]<=e&&e<=ii[1][1];let u=null;for(const d in e){let f=e[d];if(!t(f))continue;if(l>h){c++;if(c>=ii.length){warn("Ran out of space in font private use area.");break}l=ii[c][0];h=ii[c][1]}const g=l++;0===f&&(f=a);let p=r.get(d);if("string"==typeof p)if(1===p.length)p=p.codePointAt(0);else{if(!u){u=new Map;for(let e=64256;e<=64335;e++){const t=String.fromCharCode(e).normalize("NFKD");t.length>1&&u.set(t,e)}}p=u.get(p)||p.codePointAt(0)}if(p&&!isInPrivateArea(p)&&!o.has(f)){n.set(p,f);o.add(f)}i[g]=f;s[d]=g}return{toFontChar:s,charCodeToGlyphId:i,toUnicodeExtraMap:n,nextAvailableFontCharCode:l}}function createCmapTable(e,t,a){const r=function getRanges(e,t,a){const r=[];for(const t in e)e[t]>=a||r.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,i]of t)i>=a||r.push({fontCharCode:e,glyphId:i});0===r.length&&r.push({fontCharCode:0,glyphId:0});r.sort((e,t)=>e.fontCharCode-t.fontCharCode);const i=[],n=r.length;for(let e=0;e65535?2:1;let n,s,o,c,l="\0\0"+string16(i)+"\0\0"+string32(4+8*i);for(n=r.length-1;n>=0&&!(r[n][0]<=65535);--n);const h=n+1;r[n][0]<65535&&65535===r[n][1]&&(r[n][1]=65534);const u=r[n][1]<65535?1:0,d=h+u,f=OpenTypeFileBuilder.getSearchParams(d,2);let g,p,m,b,y="",w="",x="",S="",k="",C=0;for(n=0,s=h;n0){w+="ÿÿ";y+="ÿÿ";x+="\0";S+="\0\0"}const v="\0\0"+string16(2*d)+string16(f.range)+string16(f.entry)+string16(f.rangeShift)+w+"\0\0"+y+x+S+k;let F="",T="";if(i>1){l+="\0\0\n"+string32(4+8*i+4+v.length);F="";for(n=0,s=r.length;ne||!o)&&(o=e);c 123 are reserved for internal usage");s|=1<65535&&(c=65535)}else{o=0;c=255}const h=e.bbox||[0,0,0,0],u=a.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),d=e.ascentScaled?1:u/ni,f=a.ascent||Math.round(d*(e.ascent||h[3]));let g=a.descent||Math.round(d*(e.descent||h[1]));g>0&&e.descent>0&&h[1]<0&&(g=-g);const p=a.yMax||f,m=-a.yMin||-g;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(r)+string32(i)+string32(n)+string32(s)+"*21*"+string16(e.italicAngle?1:0)+string16(o||e.firstChar)+string16(c||e.lastChar)+string16(f)+string16(g)+"\0d"+string16(p)+string16(m)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(o||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const a=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],r=[];let i,n,s,o,c;for(i=0,n=a.length;i0;if((s||o)&&"CIDFontType2"===a&&this.cidEncoding.startsWith("Identity-")){const a=e.cidToGidMap,r=[];applyStandardFontGlyphMap(r,qr());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(r,Hr()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(r,Wr());if(a){for(const e in r){const t=r[e];void 0!==a[t]&&(r[+e]=a[t])}a.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach(function(e,t){const i=r[e];void 0===a[i]&&(r[+e]=t)})}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach(function(e,t){r[+e]=t});this.toFontChar=r;this.toUnicode=new ToUnicodeMap(r)}else if(/Symbol/i.test(r))this.toFontChar=buildToFontChar(ur,fr(),this.differences);else if(/Dingbats/i.test(r))this.toFontChar=buildToFontChar(dr,gr(),this.differences);else if(s||o){const e=buildToFontChar(this.defaultEncoding,fr(),this.differences);"CIDFontType2"!==a||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach(function(t,a){e[+t]=a});this.toFontChar=e}else{const e=fr(),a=[];this.toUnicode.forEach((t,r)=>{if(!this.composite){const a=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==a&&(r=a)}a[+t]=r});this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(a,qr());this.toFontChar=a}amendFallbackToUnicode(e);this.loadedName=r.split("-",1)[0]}checkAndRepair(e,t,a){const r=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const a=Object.create(null);a["OS/2"]=null;a.cmap=null;a.head=null;a.hhea=null;a.hmtx=null;a.maxp=null;a.name=null;a.post=null;for(let i=0;i>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0,n=e.pos;e.pos=e.start||0;e.skip(r);const s=e.getBytes(i);e.pos=n;if("head"===t){s[8]=s[9]=s[10]=s[11]=0;s[17]|=32}return{tag:t,checksum:a,length:i,offset:r,data:s}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,a,r,i,n){const s={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||a>e.length||a-t<=12)return s;const o=e.subarray(t,a),c=signedInt16(o[2],o[3]),l=signedInt16(o[4],o[5]),h=signedInt16(o[6],o[7]),u=signedInt16(o[8],o[9]);if(c>h){writeSignedInt16(o,2,h);writeSignedInt16(o,6,c)}if(l>u){writeSignedInt16(o,4,u);writeSignedInt16(o,8,l)}const d=signedInt16(o[0],o[1]);if(d<0){if(d<-1)return s;r.set(o,i);s.length=o.length;return s}let f,g=10,p=0;for(f=0;fo.length)return s;if(!n&&b>0){r.set(o.subarray(0,m),i);r.set([0,0],i+m);r.set(o.subarray(y,x),i+m+2);x-=b;o.length-x>3&&(x=x+3&-4);s.length=x;return s}if(o.length-x>3){x=x+3&-4;r.set(o.subarray(0,x),i);s.length=x;return s}r.set(o,i);s.length=o.length;return s}function readNameTable(e){const a=(t.start||0)+e.offset;t.pos=a;const r=[[],[]],i=[],n=e.length,s=a+n;if(0!==t.getUint16()||n<6)return[r,i];const o=t.getUint16(),c=t.getUint16();let l,h;for(l=0;ls)continue;t.pos=n;const o=e.name;if(e.encoding){let a="";for(let r=0,i=e.length;r0&&(l+=e-1)}}else{if(m||y){warn("TT: nested FDEFs not allowed");p=!0}m=!0;u=l;s=d.pop();t.functionsDefined[s]={data:c,i:l}}else if(!m&&!y){s=d.at(-1);if(isNaN(s))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[s]=!0;if(s in t.functionsStackDeltas){const e=d.length+t.functionsStackDeltas[s];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}d.length=e}else if(s in t.functionsDefined&&!g.includes(s)){f.push({data:c,i:l,stackTop:d.length-1});g.push(s);o=t.functionsDefined[s];if(!o){warn("TT: CALL non-existent function");t.hintsValid=!1;return}c=o.data;l=o.i}}}if(!m&&!y){let t=0;e<=142?t=i[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){r=d.pop();isNaN(r)||(t=2*-r)}for(;t<0&&d.length>0;){d.pop();t++}for(;t>0;){d.push(NaN);t--}}}t.tooComplexToFollowFunctions=p;const w=[c];l>c.length&&w.push(new Uint8Array(l-c.length));if(u>h){warn("TT: complementing a missing function tail");w.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let a,r,i=0;for(a=0,r=t.length;a>>0,n=[];for(let t=0;t>>0);const s={ttcTag:t,majorVersion:a,minorVersion:r,numFonts:i,offsetTable:n};switch(a){case 1:return s;case 2:s.dsigTag=e.getInt32()>>>0;s.dsigLength=e.getInt32()>>>0;s.dsigOffset=e.getInt32()>>>0;return s}throw new FormatError(`Invalid TrueType Collection majorVersion: ${a}.`)}(e),i=t.split("+");let n;for(let s=0;s=32))throw new FormatError('"maxp" table has a wrong version number');l=65536}!function writeUint32(e,t,a){e[t+3]=255&a;e[t+2]=a>>>8;e[t+1]=a>>>16;e[t]=a>>>24}(s.maxp.data,0,l)}let u=int16(s.head.data[50],s.head.data[51]);if(s.loca){const e=u?4*(h+1):2*(h+1);if(s.loca.length!==e){warn("Incorrect 'loca' table length -- attempting to fix it.");const a=Object.values(s).filter(Boolean).sort((e,t)=>e.offset-t.offset),r=a.indexOf(s.loca),i=a[r+1]||null;if(i&&s.loca.offset+e>8&255;o[a+1]=255&r;writeSignedInt16(o,a+2,Math.round(e[t]*signedInt16(o[a+2],o[a+3])))}}let d=h+1,f=!0;if(d>65535){f=!1;d=h;warn("Not enough space in glyfs to duplicate first glyph.")}let g=0,p=0;if(l>=65536&&s.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){s.maxp.data[14]=0;s.maxp.data[15]=2}t.pos+=4;g=t.getUint16();t.pos+=4;p=t.getUint16()}s.maxp.data[4]=d>>8;s.maxp.data[5]=255&d;const m=function sanitizeTTPrograms(e,t,a,r){const i={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,i);t&&sanitizeTTProgram(t,i);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let a=0,r=e.functionsUsed.length;at){warn("TT: invalid function id: "+a);e.hintsValid=!1;return}if(e.functionsUsed[a]&&!e.functionsDefined[a]){warn("TT: undefined function: "+a);e.hintsValid=!1;return}}}(i,r);if(a&&1&a.length){const e=new Uint8Array(a.length+1);e.set(a.data);a.data=e}return i.hintsValid}(s.fpgm,s.prep,s["cvt "],g);if(!m){delete s.fpgm;delete s.prep;delete s["cvt "]}!function sanitizeMetrics(e,t,a,r,i,n){if(!t){a&&(a.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const s=e.getUint16();e.pos+=8;e.pos+=2;let o=e.getUint16();if(0!==s){if(!(2&int16(r.data[44],r.data[45]))){t.data[22]=0;t.data[23]=0}}if(o>i){info(`The numOfMetrics (${o}) should not be greater than the numGlyphs (${i}).`);o=i;t.data[34]=(65280&o)>>8;t.data[35]=255&o}const c=i-o-(a.length-4*o>>1);if(c>0){const e=new Uint8Array(a.length+2*c);e.set(a.data);if(n){e[a.length]=a.data[2];e[a.length+1]=a.data[3]}a.data=e}}(t,s.hhea,s.hmtx,s.head,d,f);if(!s.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,a){const r=e.data,i=function int32(e,t,a,r){return(e<<24)+(t<<16)+(a<<8)+r}(r[0],r[1],r[2],r[3]);if(i>>16!=1){info("Attempting to fix invalid version in head table: "+i);r[0]=0;r[1]=1;r[2]=0;r[3]=0}const n=int16(r[50],r[51]);if(n<0||n>1){info("Attempting to fix invalid indexToLocFormat in head table: "+n);const e=t+1;if(a===e<<1){r[50]=0;r[51]=0}else{if(a!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+n);r[50]=0;r[51]=1}}}(s.head,h,o?s.loca.length:0);let b=Object.create(null);if(o){const e=function sanitizeGlyphLocations(e,t,a,r,i,n,s){let o,c,l;if(r){o=4;c=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};l=function fontItemEncodeLong(e,t,a){e[t]=a>>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}}else{o=2;c=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};l=function fontItemEncode(e,t,a){e[t]=a>>9&255;e[t+1]=a>>1&255}}const h=n?a+1:a,u=o*(1+h),d=new Uint8Array(u);d.set(e.data.subarray(0,u));e.data=d;const f=t.data,g=f.length,p=new Uint8Array(g);let m,b;const y=[];for(m=0,b=0;mg&&(e=g);y.push({index:m,offset:e,endOffset:0})}y.sort((e,t)=>e.offset-t.offset);for(m=0;me.index-t.index);for(m=0;ms&&(s=e.sizeOfInstructions);S+=t;l(d,b,S)}if(0===S){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(m=0,b=o;ma+S)t.data=p.subarray(0,a+S);else{t.data=new Uint8Array(a+S);t.data.set(p.subarray(0,S))}t.data.set(p.subarray(0,a),S);l(e.data,d.length-o,S+a)}else t.data=p.subarray(0,S);return{missingGlyphs:x,maxSizeOfInstructions:s}}(s.loca,s.glyf,h,u,m,f,p);b=e.missingGlyphs;if(l>=65536&&s.maxp.length>=32){s.maxp.data[26]=e.maxSizeOfInstructions>>8;s.maxp.data[27]=255&e.maxSizeOfInstructions}}if(!s.hhea)throw new FormatError('Required "hhea" table is not found');if(0===s.hhea.data[10]&&0===s.hhea.data[11]){s.hhea.data[10]=255;s.hhea.data[11]=255}const y={unitsPerEm:int16(s.head.data[18],s.head.data[19]),yMax:signedInt16(s.head.data[42],s.head.data[43]),yMin:signedInt16(s.head.data[38],s.head.data[39]),ascent:signedInt16(s.hhea.data[4],s.hhea.data[5]),descent:signedInt16(s.hhea.data[6],s.hhea.data[7]),lineGap:signedInt16(s.hhea.data[8],s.hhea.data[9])};this.ascent=y.ascent/y.unitsPerEm;this.descent=y.descent/y.unitsPerEm;this.lineGap=y.lineGap/y.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;s.post&&function readPostScriptTable(e,a,r){const i=(t.start||0)+e.offset;t.pos=i;const n=i+e.length,s=t.getInt32();t.skip(28);let o,c,l=!0;switch(s){case 65536:o=Cr;break;case 131072:const e=t.getUint16();if(e!==r){l=!1;break}const i=[];for(c=0;c=32768){l=!1;break}i.push(e)}if(!l)break;const h=[],u=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let i=-1;t?i=r:void 0!==e[r]&&(i=e[r]);i>=0&&i>>0;let h=!1;if(o?.platformId!==i||o?.encodingId!==n){if(0!==i||0!==n&&1!==n&&3!==n)if(1===i&&0===n)h=!0;else if(3!==i||1!==n||!r&&o){if(a&&3===i&&0===n){h=!0;let a=!0;if(e>3;e.push(r);a=Math.max(r,a)}const r=[];for(let e=0;e<=a;e++)r.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let a=0;a<256;a++)if(0===e[a]){t.pos=r[0].idRangePos+2*a;f=t.getUint16();u.push({charCode:a,glyphId:f})}else{const i=r[e[a]];for(d=0;d>1;t.skip(6);const a=[];let r;for(r=0;r>1)-(e-r);i.offsetIndex=s;o=Math.max(o,s+i.end-i.start+1)}else i.offsetIndex=-1}const c=[];for(d=0;d>>0;for(d=0;d>>0,a=t.getInt32()>>>0;let r=t.getInt32()>>>0;for(let t=e;t<=a;t++)u.push({charCode:t,glyphId:r++})}}}u.sort((e,t)=>e.charCode-t.charCode);const g=[],p=new Set;for(const e of u){const{charCode:t}=e;if(!p.has(t)){p.add(t);g.push(e)}}return{platformId:o.platformId,encodingId:o.encodingId,mappings:g,hasShortCmap:h}}(s.cmap,t,this.isSymbolicFont,a.hasEncoding),r=e.platformId,i=e.encodingId,n=e.mappings;let o=[],c=!1;!a.hasEncoding||"MacRomanEncoding"!==a.baseEncodingName&&"WinAnsiEncoding"!==a.baseEncodingName||(o=getEncoding(a.baseEncodingName));if(a.hasEncoding&&!this.isSymbolicFont&&(3===r&&1===i||1===r&&0===i)){const e=fr();for(let t=0;t<256;t++){let s;s=void 0!==this.differences[t]?this.differences[t]:o.length&&""!==o[t]?o[t]:lr[t];if(!s)continue;const c=recoverGlyphName(s,e);let l;3===r&&1===i?l=e[c]:1===r&&0===i&&(l=cr.indexOf(c));if(void 0===l){if(!a.glyphNames&&a.hasIncludedToUnicodeMap&&!(this.toUnicode instanceof IdentityToUnicodeMap)){const e=this.toUnicode.get(t);e&&(l=e.codePointAt(0))}if(void 0===l)continue}for(const e of n)if(e.charCode===l){w[t]=e.glyphId;break}}}else if(0===r){for(const e of n)w[e.charCode]=e.glyphId;c=!0}else if(3===r&&0===i)for(const e of n){let t=e.charCode;t>=61440&&t<=61695&&(t&=255);w[t]=e.glyphId}else for(const e of n)w[e.charCode]=e.glyphId;if(a.glyphNames&&(o.length||this.differences.length))for(let e=0;e<256;++e){if(!c&&void 0!==w[e])continue;const t=this.differences[e]||o[e];if(!t)continue;const r=a.glyphNames.indexOf(t);r>0&&hasGlyph(r)&&(w[e]=r)}}0===w.length&&(w[0]=0);let x=d-1;f||(x=0);if(!a.cssFontInfo){const e=adjustMapping(w,hasGlyph,x,this.toUnicode);this.toFontChar=e.toFontChar;s.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,d)};s["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const a=t.getUint16();t.skip(60);const r=t.getUint16();if(a<4&&768&r)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(s["OS/2"],t)||(s["OS/2"]={tag:"OS/2",data:createOS2Table(a,e.charCodeToGlyphId,y)})}if(s.name){const[t,r]=readNameTable(s.name);s.name.data=createNameTable(e,t);this.psName=t[0][6]||null;a.composite||function adjustTrueTypeToUnicode(e,t,a){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===a.length)return;if(e.defaultEncoding===hr)return;for(const e of a)if(!isWinNameRecord(e))return;const r=hr,i=[],n=fr();for(const e in r){const t=r[e];if(""===t)continue;const a=n[t];void 0!==a&&(i[e]=String.fromCharCode(a))}i.length>0&&e.toUnicode.amend(i)}(a,this.isSymbolicFont,r)}else s.name={tag:"name",data:createNameTable(this.name)};const S=new OpenTypeFileBuilder(n.version);for(const e in s)S.addTable(e,s[e].data);return S.toArray()}convert(e,a,r){r.fixedPitch=!1;r.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const a=[],r=fr();for(const i in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[i]))continue;const n=getUnicodeForGlyph(t[i],r);-1!==n&&(a[i]=String.fromCharCode(n))}a.length>0&&e.toUnicode.amend(a)}(r,r.builtInEncoding);let i=1;a instanceof CFFFont&&(i=a.numGlyphs-1);const n=a.getGlyphMapping(r);let s=null,o=n,c=null;if(!r.cssFontInfo){s=adjustMapping(n,a.hasGlyphId.bind(a),i,this.toUnicode);this.toFontChar=s.toFontChar;o=s.charCodeToGlyphId;c=s.toUnicodeExtraMap}const l=a.numGlyphs;function getCharCodes(e,t){let a=null;for(const r in e)t===e[r]&&(a||=[]).push(0|r);return a}function createCharCode(e,t){for(const a in e)if(t===e[a])return 0|a;s.charCodeToGlyphId[s.nextAvailableFontCharCode]=t;return s.nextAvailableFontCharCode++}const h=a.seacs;if(s&&h?.length){const e=r.fontMatrix||t,i=a.getCharset(),o=Object.create(null);for(let t in h){t|=0;const a=h[t],r=lr[a[2]],c=lr[a[3]],l=i.indexOf(r),u=i.indexOf(c);if(l<0||u<0)continue;const d={x:a[0]*e[0]+a[1]*e[2]+e[4],y:a[0]*e[1]+a[1]*e[3]+e[5]},f=getCharCodes(n,t);if(f)for(const e of f){const t=s.charCodeToGlyphId,a=createCharCode(t,l),r=createCharCode(t,u);o[e]={baseFontCharCode:a,accentFontCharCode:r,accentOffset:d}}}r.seacMap=o}const u=r.fontMatrix?1/Math.max(...r.fontMatrix.slice(0,4).map(Math.abs)):1e3,d=new OpenTypeFileBuilder("OTTO");d.addTable("CFF ",a.data);d.addTable("OS/2",createOS2Table(r,o));d.addTable("cmap",createCmapTable(o,c,l));d.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(u)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(r.descent)+"ÿ"+safeString16(r.ascent)+string16(r.italicAngle?2:0)+"\0\0\0\0\0\0\0");d.addTable("hhea","\0\0\0"+safeString16(r.ascent)+safeString16(r.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(r.capHeight)+safeString16(Math.tan(r.italicAngle)*r.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(l));d.addTable("hmtx",function fontFieldsHmtx(){const e=a.charstrings,t=a.cff?a.cff.widths:null;let r="\0\0\0\0";for(let a=1,i=l;a=65520&&e<=65535?0:e>=62976&&e<=63743?pr()[e]||e:173===e?45:e}(a)}this.isType3Font&&(i=a);let h=null;if(this.seacMap?.[e]){l=!0;const t=this.seacMap[e];a=t.baseFontCharCode;h={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let u="";"number"==typeof a&&(a<=1114111?u=String.fromCodePoint(a):warn(`charToGlyph - invalid fontCharCode: ${a}`));if(this.missingFile&&this.vertical&&1===u.length){const e=vr()[u.charCodeAt(0)];e&&(u=c=String.fromCharCode(e))}n=new fonts_Glyph(e,u,c,h,r,o,i,t,l);return this._glyphCache[e]=n}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const a=Object.create(null),r=e.length;let i=0;for(;it.length%2==1,r=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let i=0,n=e.length;i55295&&(n<57344||n>65533)&&i++;if(this.toUnicode){const e=r(n);if(-1!==e){if(hasCurrentBufErrors()){t.push(a.join(""));a.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)a.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(a.join(""));a.length=0}a.push(String.fromCodePoint(n))}t.push(a.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(){return{error:this.error}}}class CssFontInfo{#P;#H;#W;static strings=["fontFamily","fontWeight","italicAngle"];static write(e){const t=new TextEncoder,a={};let r=0;for(const i of CssFontInfo.strings){const n=t.encode(e[i]);a[i]=n;r+=4+n.length}const i=new ArrayBuffer(r),n=new Uint8Array(i),s=new DataView(i);let o=0;for(const e of CssFontInfo.strings){const t=a[e],r=t.length;s.setUint32(o,r);n.set(t,o+4);o+=4+r}assert(o===i.byteLength,"CssFontInfo.write: Buffer overflow");return i}constructor(e){this.#P=e;this.#H=new DataView(this.#P);this.#W=new TextDecoder}#z(e){assert(e>a&3;return 0===r?void 0:2===r}get black(){return this.#Y(0)}get bold(){return this.#Y(1)}get disableFontFace(){return this.#Y(2)}get fontExtraProperties(){return this.#Y(3)}get isInvalidPDFjsFont(){return this.#Y(4)}get isType3Font(){return this.#Y(5)}get italic(){return this.#Y(6)}get missingFile(){return this.#Y(7)}get remeasure(){return this.#Y(8)}get vertical(){return this.#Y(9)}#Z(e){assert(e0){let e=l[0],a=l[0],r=l[1],i=l[1];for(let t=0;tn?n:e;r=r>s?s:r;a=a"boolean"==typeof e)})(f,2)&&([u,d]=f);if(!(this.shadingType!==li||u&&d)){const[e,t,a,r,i,n]=this.coordsArr,s=Math.hypot(e-r,t-i);a<=n+s&&n<=a+s&&warn("Unsupported radial gradient.")}this.extendStart=u;this.extendEnd=d;const g=e.getRaw("Function"),p=r.create(g,!0),m=(l-c)/840,b=this.colorStops=[];if(c>=l||m<=0){info("Bad shading domain.");return}const y=new Float32Array(o.numComps),w=new Float32Array(1);let x=0;w[0]=c;p(w,0,y,0);const S=new Uint8ClampedArray(3);o.getRgb(y,0,S);let[k,C,v]=S;b.push([0,Util.makeHexColor(k,C,v)]);let F=1;w[0]=c+m;p(w,0,y,0);o.getRgb(y,0,S);let[T,O,D]=S,M=T-k+1,R=O-C+1,N=D-v+1,E=T-k-1,L=O-C-1,_=D-v-1;for(let e=2;e<840;e++){w[0]=c+e*m;p(w,0,y,0);o.getRgb(y,0,S);const[t,a,r]=S,i=e-x;M=Math.min(M,(t-k+1)/i);R=Math.min(R,(a-C+1)/i);N=Math.min(N,(r-v+1)/i);E=Math.max(E,(t-k-1)/i);L=Math.max(L,(a-C-1)/i);_=Math.max(_,(r-v-1)/i);if(!(E<=M&&L<=R&&_<=N)){const e=Util.makeHexColor(T,O,D);b.push([F/840,e]);M=t-T+1;R=a-O+1;N=r-D+1;E=t-T-1;L=a-O-1;_=r-D-1;x=F;k=T;C=O;v=D}F=e;T=t;O=a;D=r}b.push([1,Util.makeHexColor(T,O,D)]);let U="transparent";e.has("Background")&&(U=o.getRgbHex(e.get("Background"),0));if(!u){b.unshift([0,U]);b[1][0]+=BaseShading.SMALL_NUMBER}if(!d){b.at(-1)[0]-=BaseShading.SMALL_NUMBER;b.push([1,U])}this.colorStops=b}getIR(){const{coordsArr:e,shadingType:t}=this;let a,r,i,n,s;if(t===ci){r=[e[0],e[1]];i=[e[2],e[3]];n=null;s=null;a="axial"}else if(t===li){r=[e[0],e[1]];i=[e[3],e[4]];n=e[2];s=e[5];a="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",a,this.bbox,this.colorStops,r,i,n,s]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const a=t.numComps;this.tmpCompsBuf=new Float32Array(a);const r=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(r):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){const{stream:t}=this;let{buffer:a,bufferLength:r}=this;if(32===e){if(0===r)return t.getInt32()>>>0;a=a<<24|t.getByte()<<16|t.getByte()<<8|t.getByte();const e=t.getByte();this.buffer=e&(1<>r)>>>0}if(8===e&&0===r)return t.getByte();for(;r>r}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const{bitsPerCoordinate:e,decode:t}=this.context,a=this.readBits(e),r=this.readBits(e),i=e<32?1/((1<n?n:e;t=t>s?s:t;a=ae*i[t]):a;let s,o=-2;const c=[];for(const[e,t]of r.map((e,t)=>[e,t]).sort(([e],[t])=>e-t))if(-1!==e)if(e===o+1){s.push(n[t]);o+=1}else{o=e;s=[n[t]];c.push(e,s)}return c}(e),a=new Dict(null);a.set("BaseFont",Name.get(e));a.set("Type",Name.get("Font"));a.set("Subtype",Name.get("CIDFontType2"));a.set("Encoding",Name.get("Identity-H"));a.set("CIDToGIDMap",Name.get("Identity"));a.set("W",t);a.set("FirstChar",t[0]);a.set("LastChar",t.at(-2)+t.at(-1).length-1);const r=new Dict(null);a.set("FontDescriptor",r);const i=new Dict(null);i.set("Ordering","Identity");i.set("Registry","Adobe");i.set("Supplement",0);a.set("CIDSystemInfo",i);return a}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(nn.LBRACE);this.parseBlock();this.expect(nn.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(nn.NUMBER))this.operators.push(this.prev.value);else if(this.accept(nn.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(nn.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(nn.RBRACE);if(this.accept(nn.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(nn.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const a=this.operators.length;this.parseBlock();this.expect(nn.RBRACE);this.expect(nn.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=a;this.operators[e+1]="jz"}}}}const nn={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(nn.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(nn.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(nn.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(nn.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(nn.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return sa;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(nn.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const a=this.strBuf;a.length=0;a[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)a.push(String.fromCharCode(t));const r=a.join("");switch(r.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(r)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const a=parseFloat(t.join(""));if(isNaN(a))throw new FormatError(`Invalid floating point number: ${a}`);return a}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,a){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,a){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class GlobalColorSpaceCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('GlobalColorSpaceCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}clear(){this._imageCache.clear()}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#oe=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#ce(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#le(){return!(this._imageCache.size+e):null}class PDFFunction{static getSampleArray(e,t,a,r){let i,n,s=1;for(i=0,n=e.length;i>c)*h;l&=(1<0&&(d=n[u-1]);let f=a[1];u>1,c=r.length>>1,l=new PostScriptEvaluator(s),h=Object.create(null);let u=8192;const d=new Float32Array(c);return function constructPostScriptFn(e,t,a,r){let n,s,f="";const g=d;for(n=0;ne&&(s=e)}m[n]=s}if(u>0){u--;h[f]=m}a.set(m,r)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let a=t.length-e,r=e-1;r>=0;r--,a++)t.push(t[a])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const a=this.stack,r=a.length-e,i=a.length-1,n=r+(t-Math.floor(t/e)*e);for(let e=r,t=i;e0?t.push(s<>o);break;case"ceiling":s=t.pop();t.push(Math.ceil(s));break;case"copy":s=t.pop();t.copy(s);break;case"cos":s=t.pop();t.push(Math.cos(s%360/180*Math.PI));break;case"cvi":s=0|t.pop();t.push(s);break;case"cvr":break;case"div":o=t.pop();s=t.pop();t.push(s/o);break;case"dup":t.copy(1);break;case"eq":o=t.pop();s=t.pop();t.push(s===o);break;case"exch":t.roll(2,1);break;case"exp":o=t.pop();s=t.pop();t.push(s**o);break;case"false":t.push(!1);break;case"floor":s=t.pop();t.push(Math.floor(s));break;case"ge":o=t.pop();s=t.pop();t.push(s>=o);break;case"gt":o=t.pop();s=t.pop();t.push(s>o);break;case"idiv":o=t.pop();s=t.pop();t.push(s/o|0);break;case"index":s=t.pop();t.index(s);break;case"le":o=t.pop();s=t.pop();t.push(s<=o);break;case"ln":s=t.pop();t.push(Math.log(s));break;case"log":s=t.pop();t.push(Math.log10(s));break;case"lt":o=t.pop();s=t.pop();t.push(s=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,a){const r=[],i=[],n=t.length>>1,s=a.length>>1;let o,c,l,h,u,d,f,g,p=0;for(let e=0;et.min){o.unshift("Math.max(",n,", ");o.push(")")}if(s4){r=!0;t=0}else{r=!1;t=1}const c=[];for(n=0;n=0&&"ET"===ln[e];--e)ln[e]="EN";for(let e=n+1;e0&&(t=ln[n-1]);let a=u;e+1g&&isOdd(g)&&(m=g)}for(g=p;g>=m;--g){let e=-1;for(n=0,s=c.length;n=0){reverseValues(cn,e,n);e=-1}}else e<0&&(e=n);e>=0&&reverseValues(cn,e,c.length)}for(n=0,s=cn.length;n"!==e||(cn[n]="")}return createBidiText(cn.join(""),r)}const hn={style:"normal",weight:"normal"},un={style:"normal",weight:"bold"},dn={style:"italic",weight:"normal"},fn={style:"italic",weight:"bold"},gn=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","PT Astra Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:hn,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:un,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:dn,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:fn,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:hn,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:un,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:dn,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:fn,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:hn,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:un,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:dn,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:fn,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:hn,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:un,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:dn,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:fn,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:hn,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:un,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:dn,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:fn,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:hn}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}],["ËÎÌå",{local:["SimSun","SimSun Regular","NSimSun"],style:hn,ultimate:"serif"}],["ºÚÌå",{local:["SimHei","SimHei Regular"],style:hn,ultimate:"sans-serif"}],["¿¬Ìå",{local:["KaiTi","SimKai","SimKai Regular"],style:hn,ultimate:"sans-serif"}],["·ÂËÎ",{local:["FangSong","SimFang","SimFang Regular"],style:hn,ultimate:"serif"}],["¿¬Ìå_GB2312",{alias:"¿¬Ìå"}],["·ÂËÎ_GB2312",{alias:"·ÂËÎ"}],["Á¥Êé",{local:["SimLi","SimLi Regular"],style:hn,ultimate:"serif"}],["ÐÂËÎ",{alias:"ËÎÌå"}]]),pn=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter(e=>!t.has(e.toLowerCase())).join(" ")}function generateFont({alias:e,local:t,path:a,fallback:r,style:i,ultimate:n},s,o,c=!0,l=!0,h=""){const u={style:null,ultimate:null};if(t){const e=h?` ${h}`:"";for(const a of t)s.push(`local(${a}${e})`)}if(e){const t=gn.get(e),n=h||function getStyleToAppend(e){switch(e){case un:return"Bold";case dn:return"Italic";case fn:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(i);Object.assign(u,generateFont(t,s,o,c&&!r,l&&!a,n))}i&&(u.style=i);n&&(u.ultimate=n);if(c&&r){const e=gn.get(r),{ultimate:t}=generateFont(e,s,o,c,l&&!a,h);u.ultimate||=t}l&&a&&o&&s.push(`url(${o}${a})`);return u}function getFontSubstitution(e,t,a,r,i,n){if(r.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==n&&"Type1"!==n||!/^[A-Z]{6}\+/.test(r)||(r=r.slice(7));const s=r=normalizeFontName(r);let o=e.get(s);if(o)return o;let c=gn.get(r);if(!c)for(const[e,t]of pn)if(r.startsWith(e)){r=`${t}${r.substring(e.length)}`;c=gn.get(r);break}let l=!1;if(!c){c=gn.get(i);l=!0}const h=`${t.getDocId()}_s${t.createFontId()}`;if(!c){if(!validateFontName(r)){warn(`Cannot substitute the font because of its name: ${r}`);e.set(s,null);return null}const t=/bold/gi.test(r),a=/oblique|italic/gi.test(r),i=t&&a&&fn||t&&un||a&&dn||hn;o={css:`"${getFamilyName(r)}",${h}`,guessFallback:!0,loadedName:h,baseFontName:r,src:`local(${r})`,style:i};e.set(s,o);return o}const u=[];l&&validateFontName(r)&&u.push(`local(${r})`);const{style:d,ultimate:f}=generateFont(c,u,a),g=null===f,p=g?"":`,${f}`;o={css:`"${getFamilyName(r)}",${h}${p}`,guessFallback:g,loadedName:h,baseFontName:r,src:u.join(","),style:d};e.set(s,o);return o}const mn=3285377520,bn=4294901760,yn=65535;class MurmurHash3_64{constructor(e){this.h1=e?4294967295&e:mn;this.h2=e?4294967295&e:mn}update(e){let t,a;if("string"==typeof e){t=new Uint8Array(2*e.length);a=0;for(let r=0,i=e.length;r>>8;t[a++]=255&i}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();a=t.byteLength}const r=a>>2,i=a-4*r,n=new Uint32Array(t.buffer,0,r);let s=0,o=0,c=this.h1,l=this.h2;const h=3432918353,u=461845907,d=11601,f=13715;for(let e=0;e>>17;s=s*u&bn|s*f&yn;c^=s;c=c<<13|c>>>19;c=5*c+3864292196}else{o=n[e];o=o*h&bn|o*d&yn;o=o<<15|o>>>17;o=o*u&bn|o*f&yn;l^=o;l=l<<13|l>>>19;l=5*l+3864292196}s=0;switch(i){case 3:s^=t[4*r+2]<<16;case 2:s^=t[4*r+1]<<8;case 1:s^=t[4*r];s=s*h&bn|s*d&yn;s=s<<15|s>>>17;s=s*u&bn|s*f&yn;1&r?c^=s:l^=s}this.h1=c;this.h2=l}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&bn|36045*e&yn;t=4283543511*t&bn|(2950163797*(t<<16|e>>>16)&bn)>>>16;e^=t>>>1;e=444984403*e&bn|60499*e&yn;t=3301882366*t&bn|(3120437893*(t<<16|e>>>16)&bn)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function resizeImageMask(e,t,a,r,i,n){const s=i*n;let o;o=t<=8?new Uint8Array(s):t<=16?new Uint16Array(s):new Uint32Array(s);const c=a/i,l=r/n;let h,u,d,f,g=0;const p=new Uint16Array(i),m=a;for(h=0;h0&&Number.isInteger(a.height)&&a.height>0&&(a.width!==f||a.height!==g)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");f=a.width;g=a.height}else{const e="number"==typeof f&&f>0,t="number"==typeof g&&g>0;if(!e||!t){if(!a.fallbackDims)throw new FormatError(`Invalid image width: ${f} or height: ${g}`);warn("PDFImage - using the Width/Height of the parent image, for SMask/Mask data.");e||(f=a.fallbackDims.width);t||(g=a.fallbackDims.height)}}this.width=f;this.height=g;this.interpolate=h.get("I","Interpolate");this.imageMask=h.get("IM","ImageMask")||!1;this.matte=h.get("Matte")||!1;let p=a.bitsPerComponent;if(!p){p=h.get("BPC","BitsPerComponent");if(!p){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);p=1}}this.bpc=p;if(!this.imageMask){let i=h.getRaw("CS")||h.getRaw("ColorSpace");const n=!!i;if(n)this.jpxDecoderOptions?.smaskInData&&(i=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)i=Name.get("DeviceRGBA");else switch(a.numComps){case 1:i=Name.get("DeviceGray");break;case 3:i=Name.get("DeviceRGB");break;case 4:i=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${a.numComps} color components not supported.`)}this.colorSpace=ColorSpaceUtils.parse({cs:i,xref:e,resources:r?t:null,pdfFunctionFactory:o,globalColorSpaceCache:c,localColorSpaceCache:l});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=n?this.numComps:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=h.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,p)||s&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<0,c=(r+7>>3)*i,l=e.getBytes(c),h=1===r&&1===i&&o===(0===l.length||!!(128&l[0]));if(h)return{isSingleOpaquePixel:h};if(t){if(ImageResizer.needsToBeResized(r,i)){const e=new Uint8ClampedArray(r*i*4);convertBlackAndWhiteToRGBA({src:l,dest:e,width:r,height:i,nonBlackColor:0,inverseDecode:o});return ImageResizer.createImage({kind:O,data:e,width:r,height:i,interpolate:n})}const e=new OffscreenCanvas(r,i),t=e.getContext("2d"),a=t.createImageData(r,i);convertBlackAndWhiteToRGBA({src:l,dest:a.data,width:r,height:i,nonBlackColor:0,inverseDecode:o});t.putImageData(a,0,0);return{data:null,width:r,height:i,interpolate:n,bitmap:e.transferToImageBitmap()}}const u=l.byteLength;let d;if(e instanceof DecodeStream&&(!o||c===u))d=l;else if(o){d=new Uint8Array(c);d.set(l);d.fill(255,u)}else d=new Uint8Array(l);if(o)for(let e=0;e>7&1;s[d+1]=u>>6&1;s[d+2]=u>>5&1;s[d+3]=u>>4&1;s[d+4]=u>>3&1;s[d+5]=u>>2&1;s[d+6]=u>>1&1;s[d+7]=1&u;d+=8}if(d>=1}}}}else{let a=0;u=0;for(d=0,h=n;d>r;i<0?i=0:i>l&&(i=l);s[d]=i;u&=(1<s[r+1]){t=255;break}}o[h]=t}}}if(o)for(h=0,d=3,u=t*r;h>3,h=t&&ImageResizer.needsToBeResized(a,r);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){i.kind=O;const e=i.data=await this.getImageBytes(o*s*4,{});return t?h?ImageResizer.createImage(i,!1):this.createBitmap(O,a,r,e):i}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===c?e=F:"DeviceRGB"!==this.colorSpace.name||8!==c||this.needsDecode||(e=T);if(e&&!this.smask&&!this.mask&&a===s&&r===o){const n=await this.#he(s,o);if(n)return n;const c=await this.getImageBytes(o*l,{});if(t)return h?ImageResizer.createImage({data:c,kind:e,width:a,height:r,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,s,o,c);i.kind=e;i.data=c;if(this.needsDecode){assert(e===F,"PDFImage.createImageData: The image must be grayscale.");const t=i.data;for(let e=0,a=t.length;e>3,s=await this.getImageBytes(r*n,{internal:!0}),o=this.getComponents(s);let c,l;if(1===i){l=a*r;if(this.needsDecode)for(c=0;c0&&r[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedo){const e="Image exceeded maximum allowed size and was removed.";if(!c)throw new Error(e);warn(e);return}let g;h.has("OC")&&(g=await this.parseMarkedContentProps(h.get("OC"),e));let p,m,b;if(h.get("IM","ImageMask")||!1){p=await PDFImage.createMask({image:t,isOffscreenCanvasSupported:l&&!this.parsingType3Font});if(p.isSingleOpaquePixel){m=Xt;b=[];r.addImageOps(m,b,g);if(i){const e={fn:m,args:b,optionalContent:g};n.set(i,u,e);u&&this._regionalImageCache.set(null,u,e)}return}if(this.parsingType3Font){b=function compileType3Glyph({data:e,width:t,height:a}){if(t>1e3||a>1e3)return null;const r=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1,n=new Uint8Array(i*(a+1));let s,o,c;const l=t+7&-8,h=new Uint8Array(l*a);let u=0;for(const t of e){let e=128;for(;e>0;){h[u++]=t&e?0:255;e>>=1}}let d=0;u=0;if(0!==h[u]){n[0]=1;++d}for(o=1;o>2)+(h[u+1]?4:0)+(h[u-l+1]?8:0);if(r[e]){n[c+o]=r[e];++d}u++}if(h[u-l]!==h[u]){n[c+o]=h[u]?2:4;++d}if(d>1e3)return null}u=l*(a-1);c=s*i;if(0!==h[u]){n[c]=8;++d}for(o=1;o1e3)return null;const f=new Int32Array([0,i,-1,0,-i,0,0,0,1]),g=[],{a:p,b:m,c:b,d:y,e:w,f:x}=(new DOMMatrix).scaleSelf(1/t,-1/a).translateSelf(0,-a);for(s=0;d&&s<=a;s++){let e=s*i;const a=e+t;for(;e>4;n[e]&=l>>2|l<<2}r=e%i;o=e/i|0;g.push(Gt,p*r+b*o+w,m*r+y*o+x);n[e]||--d}while(c!==e);--s}return[zt,[new Float32Array(g)],new Float32Array([0,0,t,a])]}(p);if(b){r.addImageOps(qt,b,g);return}warn("Cannot compile Type3 glyph.");r.addImageOps(Nt,[p],g);return}const e=`mask_${this.idFactory.createObjId()}`;r.addDependency(e);p.dataLen=p.bitmap?p.width*p.height*4:p.data.length;this._sendImgData(e,p);m=Nt;b=[{data:e,width:p.width,height:p.height,interpolate:p.interpolate,count:1}];r.addImageOps(m,b,g);if(i){const t={objId:e,fn:m,args:b,optionalContent:g};n.set(i,u,t);u&&this._regionalImageCache.set(null,u,t)}return}const y=h.has("SMask")||h.has("Mask");if(a&&d+f<200&&!y){try{const i=new PDFImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:s});p=await i.createImageData(!0,!1);r.addImageOps(Lt,[p],g)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!c)throw new Error(t);warn(t)}return}let w=`img_${this.idFactory.createObjId()}`,x=!1,S=null;if(this.parsingType3Font)w=`${this.idFactory.getDocId()}_type3_${w}`;else if(i&&u){x=this.globalImageCache.shouldCache(u,this.pageIndex);if(x){assert(!a,"Cannot cache an inline image globally.");w=`${this.idFactory.getDocId()}_${w}`}}r.addDependency(w);m=Et;b=[w,d,f];r.addImageOps(m,b,g,y);if(x){S={objId:w,fn:m,args:b,optionalContent:g,hasMask:y,byteSize:0};if(this.globalImageCache.hasDecodeFailed(u)){this.globalImageCache.setData(u,S);this._sendImgData(w,null,x);return}if(d*f>25e4||y){const e=await this.handler.sendWithPromise("commonobj",[w,"CopyLocalImage",{imageRef:u}]);if(e){this.globalImageCache.setData(u,S);this.globalImageCache.addByteSize(u,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:s}).then(async e=>{p=await e.createImageData(!1,l);p.dataLen=p.bitmap?p.width*p.height*4:p.data.length;p.ref=u;x&&this.globalImageCache.addByteSize(u,p.dataLen);return this._sendImgData(w,p,x)}).catch(e=>{warn(`Unable to decode image "${w}": "${e}".`);u&&this.globalImageCache.addDecodeFailed(u);return this._sendImgData(w,null,x)});if(i){const e={objId:w,fn:m,args:b,optionalContent:g,hasMask:y};n.set(i,u,e);if(u){this._regionalImageCache.set(null,u,e);if(x){assert(S,"The global cache-data must be available.");this.globalImageCache.setData(u,S)}}}}handleSMask(e,t,a,r,i,n,s){const o=e.get("G"),c={subtype:e.get("S").name,backdrop:e.get("BC")},l=e.get("TR");if(isPDFFunction(l)){const e=this._pdfFunctionFactory.create(l),t=new Uint8Array(256),a=new Float32Array(1);for(let r=0;r<256;r++){a[0]=r/255;e(a,0,a,0);t[r]=255*a[0]|0}c.transferMap=t}return this.buildFormXObject(t,o,c,a,r,i.state.clone({newPath:!0}),n,s)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const a=[];let r=0,i=0;for(const e of t){const t=this.xref.fetchIfRef(e);r++;if(isName(t,"Identity")){a.push(null);continue}if(!isPDFFunction(t))return null;const n=this._pdfFunctionFactory.create(t),s=new Uint8Array(256),o=new Float32Array(1);for(let e=0;e<256;e++){o[0]=e/255;n(o,0,o,0);s[e]=255*o[0]|0}a.push(s);i++}return 1!==r&&4!==r||0===i?null:a}handleTilingType(e,t,a,r,i,n,s,o){const c=new OperatorList,l=Dict.merge({xref:this.xref,dictArray:[i.get("Resources"),a]});return this.getOperatorList({stream:r,task:s,resources:l,operatorList:c}).then(function(){const a=c.getIR(),r=getTilingPatternIR(a,i,t);n.addDependencies(c.dependencies);n.addOp(e,r);i.objId&&o.set(null,i.objId,{operatorListIR:a,dict:i})}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}})}async handleSetFont(e,t,a,r,i,n,s=null,o=null){const c=t?.[0]instanceof Name?t[0].name:null,l=await this.loadFont(c,a,e,i,s,o);l.font.isType3Font&&r.addDependencies(l.type3Dependencies);n.font=l.font;l.send(this.handler);return l.loadedName}handleText(e,t){const a=t.font,r=a.charsToGlyphs(e);if(a.data){(!!(t.textRenderingMode&v)||"Pattern"===t.fillColorSpace.name||a.disableFontFace)&&PartialEvaluator.buildFontPaths(a,r,this.handler,this.options)}return r}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:a,cacheKey:r,task:i,stateManager:n,localGStateCache:s,localColorSpaceCache:o,seenRefs:c}){const l=t.objId;let h=!0;const u=[];let d=Promise.resolve();for(const[r,s]of t)switch(r){case"Type":break;case"LW":if("number"!=typeof s){warn(`Invalid LW (line width): ${s}`);break}u.push([r,Math.abs(s)]);break;case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":u.push([r,s]);break;case"Font":h=!1;d=d.then(()=>this.handleSetFont(e,null,s[0],a,i,n.state).then(function(e){a.addDependency(e);u.push([r,[e,s[1]]])}));break;case"BM":u.push([r,normalizeBlendMode(s)]);break;case"SMask":if(isName(s,"None")){u.push([r,!1]);break}if(s instanceof Dict){h=!1;d=d.then(()=>this.handleSMask(s,e,a,i,n,o,c));u.push([r,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(s);u.push([r,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+r);break;default:info("Unknown graphic state operator "+r)}await d;u.length>0&&a.addOp(be,[u]);h&&s.set(r,l,u)}loadFont(e,t,a,r,i=null,n=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t});let s;if(t)t instanceof Ref&&(s=t);else{const t=a.get("Font");t&&(s=t.getRaw(e))}if(s){if(this.type3FontRefs?.has(s))return errorFont();if(this.fontCache.has(s))return this.fontCache.get(s);try{t=this.xref.fetchIfRef(s)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=i||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:o,resolve:c}=Promise.withResolvers();let l;try{l=this.preEvaluateFont(t);l.cssFontInfo=n}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:h,hash:u}=l,d=s instanceof Ref;let f;if(u&&h instanceof Dict){const e=h.fontAliases||=Object.create(null);if(e[u]){const t=e[u].aliasRef;if(d&&t&&this.fontCache.has(t)){this.fontCache.putAlias(s,t);return this.fontCache.get(s)}}else e[u]={fontID:this.idFactory.createFontId()};d&&(e[u].aliasRef=s);f=e[u].fontID}else f=this.idFactory.createFontId();assert(f?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(d)this.fontCache.put(s,o);else{t.cacheKey=`cacheKey_${f}`;this.fontCache.put(t.cacheKey,o)}t.loadedName=`${this.idFactory.getDocId()}_${f}`;this.translateFont(l).then(async e=>{const i=new TranslatedFont({loadedName:t.loadedName,font:e,dict:t});if(e.isType3Font)try{await i.loadType3Data(this,a,r)}catch(e){throw new Error(`Type3 font load error: ${e}`)}c(i)}).catch(e=>{warn(`loadFont - translateFont failed: "${e}".`);c(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e?.message),dict:t}))});return o}buildPath(e,t,a){const{pathMinMax:r,pathBuffer:i}=a;switch(0|e){case Ie:{const e=a.currentPointX=t[0],n=a.currentPointY=t[1],s=t[2],o=t[3],c=e+s,l=n+o;0===s||0===o?i.push($t,e,n,Gt,c,l,Jt):i.push($t,e,n,Gt,c,n,Gt,c,l,Gt,e,l,Jt);Util.rectBoundingBox(e,n,c,l,r);break}case Se:{const e=a.currentPointX=t[0],n=a.currentPointY=t[1];i.push($t,e,n);Util.pointBoundingBox(e,n,r);break}case Ae:{const e=a.currentPointX=t[0],n=a.currentPointY=t[1];i.push(Gt,e,n);Util.pointBoundingBox(e,n,r);break}case ke:{const e=a.currentPointX,n=a.currentPointY,[s,o,c,l,h,u]=t;a.currentPointX=h;a.currentPointY=u;i.push(Vt,s,o,c,l,h,u);Util.bezierBoundingBox(e,n,s,o,c,l,h,u,r);break}case Ce:{const e=a.currentPointX,n=a.currentPointY,[s,o,c,l]=t;a.currentPointX=c;a.currentPointY=l;i.push(Vt,e,n,s,o,c,l);Util.bezierBoundingBox(e,n,e,n,s,o,c,l,r);break}case ve:{const e=a.currentPointX,n=a.currentPointY,[s,o,c,l]=t;a.currentPointX=c;a.currentPointY=l;i.push(Vt,s,o,c,l,c,l);Util.bezierBoundingBox(e,n,s,o,c,l,c,l,r);break}case Fe:i.push(Jt)}}_getColorSpace(e,t,a){return ColorSpaceUtils.parse({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:a,asyncIfNotCached:!0})}async _handleColorSpace(e){try{return await e}catch(e){if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`_handleColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}}parseShading({shading:e,resources:t,localColorSpaceCache:a,localShadingPatternCache:r}){let i,n=r.get(e);if(n)return n;try{i=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,this.globalColorSpaceCache,a).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);r.set(e,null);return null}throw t}n=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(n=`${this.idFactory.getDocId()}_type3_${n}`);r.set(e,n);if(this.parsingType3Font){const e=[],t=PatternInfo.write(i);e.push(t);this.handler.send("commonobj",[n,"Pattern",t],e)}else this.handler.send("obj",[n,this.pageIndex,"Pattern",i]);return n}handleColorN(e,t,a,r,i,n,s,o,c,l){const h=a.pop();if(h instanceof Name){const u=i.getRaw(h.name),d=u instanceof Ref&&c.getByRef(u);if(d)try{const i=r.base?r.base.getRgbHex(a,0):null,n=getTilingPatternIR(d.operatorListIR,d.dict,i);e.addOp(t,n);return}catch{}const f=this.xref.fetchIfRef(u);if(f){const i=f instanceof BaseStream?f.dict:f,h=i.get("PatternType");if(h===xn){const o=r.base?r.base.getRgbHex(a,0):null;return this.handleTilingType(t,o,n,f,i,e,s,c)}if(h===Sn){const a=i.get("Shading"),r=this.parseShading({shading:a,resources:n,localColorSpaceCache:o,localShadingPatternCache:l});if(r){const a=lookupMatrix(i.getArray("Matrix"),null);e.addOp(t,["Shading",r,a])}return}throw new FormatError(`Unknown PatternType: ${h}`)}}throw new FormatError(`Unknown PatternName: ${h}`)}_parseVisibilityExpression(e,t,a){if(++t>10){warn("Visibility expression is too deeply nested");return}const r=e.length,i=this.xref.fetchIfRef(e[0]);if(!(r<2)&&i instanceof Name){switch(i.name){case"And":case"Or":case"Not":a.push(i.name);break;default:warn(`Invalid operator ${i.name} in visibility expression`);return}for(let i=1;i0)return{type:"OCMD",expression:t}}const t=a.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const a of t)e.push(a.toString());else e.push(t.objId);return{type:r,ids:e,policy:a.get("P")instanceof Name?a.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:r,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:a,operatorList:r,initialState:i=null,fallbackFontDict:n=null,prevRefs:s=null}){const o=e.dict?.objId,c=new RefSet(s);if(o){if(s?.has(o))throw new Error(`getOperatorList - ignoring circular reference: ${o}`);c.put(o)}a||=Dict.empty;i||=new EvalState;if(!r)throw new Error('getOperatorList: missing "operatorList" parameter');const l=this,h=this.xref,u=new LocalImageCache,d=new LocalColorSpaceCache,f=new LocalGStateCache,g=new LocalTilingPatternCache,p=new Map,m=a.get("XObject")||Dict.empty,b=a.get("Pattern")||Dict.empty,y=new StateManager(i),w=new EvaluatorPreprocessor(e,h,y),x=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=w.savedStatesDepth;e{y.state.fillColorSpace=e||ColorSpaceUtils.gray}));return}case it:{const t=l._getColorSpace(e[0],a,d);if(t instanceof ColorSpace){y.state.strokeColorSpace=t;continue}next(l._handleColorSpace(t).then(e=>{y.state.strokeColorSpace=e||ColorSpaceUtils.gray}));return}case ct:C=y.state.fillColorSpace;e=[C.getRgbHex(e,0)];i=ft;break;case st:C=y.state.strokeColorSpace;e=[C.getRgbHex(e,0)];i=dt;break;case ut:y.state.fillColorSpace=ColorSpaceUtils.gray;e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=ft;break;case ht:y.state.strokeColorSpace=ColorSpaceUtils.gray;e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=dt;break;case pt:y.state.fillColorSpace=ColorSpaceUtils.cmyk;e=[ColorSpaceUtils.cmyk.getRgbHex(e,0)];i=ft;break;case gt:y.state.strokeColorSpace=ColorSpaceUtils.cmyk;e=[ColorSpaceUtils.cmyk.getRgbHex(e,0)];i=dt;break;case ft:y.state.fillColorSpace=ColorSpaceUtils.rgb;e=[ColorSpaceUtils.rgb.getRgbHex(e,0)];break;case dt:y.state.strokeColorSpace=ColorSpaceUtils.rgb;e=[ColorSpaceUtils.rgb.getRgbHex(e,0)];break;case lt:C=y.state.patternFillColorSpace;if(!C){if(isNumberArray(e,null)){e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=ft;break}e=[];i=Wt;break}if("Pattern"===C.name){next(l.handleColorN(r,lt,e,C,b,a,t,d,g,p));return}e=[C.getRgbHex(e,0)];i=ft;break;case ot:C=y.state.patternStrokeColorSpace;if(!C){if(isNumberArray(e,null)){e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=dt;break}e=[];i=Ht;break}if("Pattern"===C.name){next(l.handleColorN(r,ot,e,C,b,a,t,d,g,p));return}e=[C.getRgbHex(e,0)];i=dt;break;case mt:let T;try{const t=a.get("Shading");if(!t)throw new FormatError("No shading resource found");T=t.get(e[0].name);if(!T)throw new FormatError("No shading object found")}catch(e){if(e instanceof AbortException)continue;if(l.options.ignoreErrors){warn(`getOperatorList - ignoring Shading: "${e}".`);continue}throw e}const O=l.parseShading({shading:T,resources:a,localColorSpaceCache:d,localShadingPatternCache:p});if(!O)continue;e=[O];i=mt;break;case be:F=e[0]instanceof Name;v=e[0].name;if(F){const t=f.getByName(v);if(t){t.length>0&&r.addOp(be,[t]);e=null;continue}}next(new Promise(function(e,i){if(!F)throw new FormatError("GState must be referred to by name.");const n=a.get("ExtGState");if(!(n instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const s=n.get(v);if(!(s instanceof Dict))throw new FormatError("GState should be a dictionary.");l.setGState({resources:a,gState:s,operatorList:r,cacheKey:v,task:t,stateManager:y,localGStateCache:f,localColorSpaceCache:d,seenRefs:c}).then(e,i)}).catch(function(e){if(!(e instanceof AbortException)){if(!l.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}}));return;case he:{const[t]=e;if("number"!=typeof t){warn(`Invalid setLineWidth: ${t}`);continue}e[0]=Math.abs(t);break}case ge:{const t=e[1];if("number"!=typeof t){warn(`Invalid setDash: ${t}`);continue}const a=e[0];if(!Array.isArray(a)){warn(`Invalid setDash: ${a}`);continue}a.some(e=>"number"!=typeof e)&&(e[0]=a.filter(e=>"number"==typeof e));break}case Se:case Ae:case ke:case Ce:case ve:case Fe:case Ie:l.buildPath(i,e,y.state);continue;case Te:case Oe:case De:case Me:case Re:case Be:case Ne:case Pe:case Ee:{const{state:{pathBuffer:e,pathMinMax:t}}=y;i!==Oe&&i!==Ne&&i!==Pe||e.push(Jt);if(0===e.length)r.addOp(qt,[i,[null],null]);else{r.addOp(qt,[i,[new Float32Array(e)],t.slice()]);e.length=0;t.set([1/0,1/0,-1/0,-1/0],0)}continue}case Je:r.addOp(i,[new Float32Array(e)]);continue;case St:case At:case Ft:case It:continue;case Ct:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);r.addOp(Ct,["OC",null]);continue}if("OC"===e[0].name){next(l.parseMarkedContentProps(e[1],a).then(e=>{r.addOp(Ct,["OC",e])}).catch(e=>{if(!(e instanceof AbortException)){if(!l.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);r.addOp(Ct,["OC",null])}}));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(S=0,k=e.length;S{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}})}getTextContent({stream:e,task:a,resources:r,stateManager:i=null,includeMarkedContent:n=!1,sink:s,seenStyles:o=new Set,viewBox:c,lang:l=null,markedContentData:h=null,disableNormalization:u=!1,keepWhiteSpace:d=!1,prevRefs:f=null,intersector:g=null}){const p=e.dict?.objId,m=new RefSet(f);if(p){if(f?.has(p))throw new Error(`getTextContent - ignoring circular reference: ${p}`);m.put(p)}r||=Dict.empty;i||=new StateManager(new TextState);n&&(h||={level:0});const b={items:[],styles:Object.create(null),lang:l},y={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},w=[" "," "];let x=0;function saveLastChar(e){const t=(x+1)%2,a=" "!==w[x]&&" "===w[t];w[x]=e;x=t;return!d&&a}function shouldAddWhitepsace(){return!d&&" "!==w[x]&&" "===w[(x+1)%2]}function resetLastChars(){w[0]=w[1]=" ";x=0}const S=this,k=this.xref,C=[];let v=null;const F=new LocalImageCache,T=new LocalGStateCache,O=new EvaluatorPreprocessor(e,k,i);let D;function pushWhitespace({width:e=0,height:t=0,transform:a=y.prevTransform,fontName:r=y.fontName}){g?.addExtraChar(" ");b.items.push({str:" ",dir:"ltr",width:e,height:t,transform:a,fontName:r,hasEOL:!1})}function getCurrentTextTransform(){const e=D.font,a=[D.fontSize*D.textHScale,0,0,D.fontSize,0,D.textRise];if(e.isType3Font&&(D.fontSize<=1||e.isCharBBox)&&!isArrayEqual(D.fontMatrix,t)){const t=e.bbox[3]-e.bbox[1];t>0&&(a[3]*=t*D.fontMatrix[3])}return Util.transform(D.ctm,Util.transform(D.textMatrix,a))}function ensureTextContentItem(){if(y.initialized)return y;const{font:e,loadedName:t}=D;if(!o.has(t)){o.add(t);b.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(S.options.fontExtraProperties&&e.systemFontInfo){const a=b.styles[t];a.fontSubstitution=e.systemFontInfo.css;a.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}y.fontName=t;const a=y.transform=getCurrentTextTransform();if(e.vertical){y.width=y.totalWidth=Math.hypot(a[0],a[1]);y.height=y.totalHeight=0;y.vertical=!0}else{y.width=y.totalWidth=0;y.height=y.totalHeight=Math.hypot(a[2],a[3]);y.vertical=!1}const r=Math.hypot(D.textLineMatrix[0],D.textLineMatrix[1]),i=Math.hypot(D.ctm[0],D.ctm[1]);y.textAdvanceScale=i*r;const{fontSize:n}=D;y.trackingSpaceMin=.102*n;y.notASpace=.03*n;y.negativeSpaceMax=-.2*n;y.spaceInFlowMin=.102*n;y.spaceInFlowMax=.6*n;y.hasEOL=!1;y.initialized=!0;return y}function updateAdvanceScale(){if(!y.initialized)return;const e=Math.hypot(D.textLineMatrix[0],D.textLineMatrix[1]),t=Math.hypot(D.ctm[0],D.ctm[1])*e;if(t!==y.textAdvanceScale){if(y.vertical){y.totalHeight+=y.height*y.textAdvanceScale;y.height=0}else{y.totalWidth+=y.width*y.textAdvanceScale;y.width=0}y.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");u||(t=function normalizeUnicode(e){if(!ra){ra=/([\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;ia=new Map([["ſt","ſt"]])}return e.replaceAll(ra,(e,t,a)=>t?t.normalize("NFKC"):ia.get(a))}(t));const a=bidi(t,-1,e.vertical);return{str:a.str,dir:a.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const n=await S.loadFont(e,i,r,a);D.loadedName=n.loadedName;D.font=n.font;D.fontMatrix=n.font.fontMatrix||t}function applyInverseRotation(e,t,a){const r=Math.hypot(a[0],a[1]);return[(a[0]*e+a[1]*t)/r,(a[2]*e+a[3]*t)/r]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let a=t[4],r=t[5];if(D.font?.vertical){if(ac[2]||r+ec[3])return!1}else if(a+ec[2]||rc[3])return!1;if(!D.font||!y.prevTransform)return!0;let i=y.prevTransform[4],n=y.prevTransform[5];if(i===a&&n===r)return!0;let s=-1;t[0]&&0===t[1]&&0===t[2]?s=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(s=t[1]>0?90:270);switch(s){case 0:break;case 90:[a,r]=[r,a];[i,n]=[n,i];break;case 180:[a,r,i,n]=[-a,-r,-i,-n];break;case 270:[a,r]=[-r,-a];[i,n]=[-n,-i];break;default:[a,r]=applyInverseRotation(a,r,t);[i,n]=applyInverseRotation(i,n,y.prevTransform)}if(D.font.vertical){const e=(n-r)/y.textAdvanceScale,t=a-i,s=Math.sign(y.height);if(e.5*y.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>y.width){appendEOL();return!0}e<=s*y.notASpace&&resetLastChars();if(e<=s*y.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else y.height+=e;else if(!addFakeSpaces(e,y.prevTransform,s))if(0===y.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else y.height+=e;Math.abs(t)>.25*y.width&&flushTextContentItem();return!0}const o=(a-i)/y.textAdvanceScale,l=r-n,h=Math.sign(y.width);if(o.5*y.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(l)>y.height){appendEOL();return!0}o<=h*y.notASpace&&resetLastChars();if(o<=h*y.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(o)})}else y.width+=o;else if(!addFakeSpaces(o,y.prevTransform,h))if(0===y.str.length){resetLastChars();pushWhitespace({width:Math.abs(o)})}else y.width+=o;Math.abs(l)>.25*y.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const a=D.font;if(!e){const e=D.charSpacing+t;e&&(a.vertical?D.translateTextMatrix(0,-e):D.translateTextMatrix(e*D.textHScale,0));d&&compareWithLastPosition(0);return}const r=a.charsToGlyphs(e),i=D.fontMatrix[0]*D.fontSize;for(let e=0,n=r.length;e0){const e=C.join("");C.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case Ze:if(!i.state.font){S.ensureStateFont(i.state);continue}buildTextContentItem({chars:w[0],extraSpacing:0});break;case et:if(!i.state.font){S.ensureStateFont(i.state);continue}D.carriageReturn();buildTextContentItem({chars:w[0],extraSpacing:0});break;case tt:if(!i.state.font){S.ensureStateFont(i.state);continue}D.wordSpacing=w[0];D.charSpacing=w[1];D.carriageReturn();buildTextContentItem({chars:w[2],extraSpacing:0});break;case xt:flushTextContentItem();v??=r.get("XObject")||Dict.empty;y=w[0]instanceof Name;p=w[0].name;if(y&&F.getByName(p))break;next(new Promise(function(e,t){if(!y)throw new FormatError("XObject must be referred to by name.");let f=v.getRaw(p);if(f instanceof Ref){if(F.getByRef(f)){e();return}if(S.globalImageCache.getData(f,S.pageIndex)){e();return}f=k.fetch(f)}if(!(f instanceof BaseStream))throw new FormatError("XObject should be a stream");const{dict:g}=f,b=g.get("Subtype");if(!(b instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==b.name){F.set(p,g.objId,!0);e();return}const w=i.state.clone(),x=new StateManager(w),C=lookupMatrix(g.getArray("Matrix"),null);C&&x.transform(C);const T=g.get("Resources");enqueueChunk();const O={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;s.enqueue(e,t)},get desiredSize(){return s.desiredSize??0},get ready(){return s.ready}};S.getTextContent({stream:f,task:a,resources:T instanceof Dict?T:r,stateManager:x,includeMarkedContent:n,sink:s&&O,seenStyles:o,viewBox:c,lang:l,markedContentData:h,disableNormalization:u,keepWhiteSpace:d,prevRefs:m}).then(function(){O.enqueueInvoked||F.set(p,g.objId,!0);e()},t)}).catch(function(e){if(!(e instanceof AbortException)){if(!S.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}}));return;case be:y=w[0]instanceof Name;p=w[0].name;if(y&&T.getByName(p))break;next(new Promise(function(e,t){if(!y)throw new FormatError("GState must be referred to by name.");const a=r.get("ExtGState");if(!(a instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const i=a.get(p);if(!(i instanceof Dict))throw new FormatError("GState should be a dictionary.");const n=i.get("Font");if(n){flushTextContentItem();D.fontName=null;D.fontSize=n[1];handleSetFont(null,n[0]).then(e,t)}else{T.set(p,i.objId,!0);e()}}).catch(function(e){if(!(e instanceof AbortException)){if(!S.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}}));return;case kt:flushTextContentItem();if(n){h.level++;b.items.push({type:"beginMarkedContent",tag:w[0]instanceof Name?w[0].name:null})}break;case Ct:flushTextContentItem();if(n){h.level++;let e=null;w[1]instanceof Dict&&(e=w[1].get("MCID"));b.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${S.idFactory.getPageObjId()}_mc${e}`:null,tag:w[0]instanceof Name?w[0].name:null})}break;case vt:flushTextContentItem();if(n){if(0===h.level)break;h.level--;b.items.push({type:"endMarkedContent"})}break;case we:!e||e.font===D.font&&e.fontSize===D.fontSize&&e.fontName===D.fontName||flushTextContentItem()}if(b.items.length>=(s?.desiredSize??1)){g=!0;break}}if(g)next(An);else{flushTextContentItem();enqueueChunk();e()}}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${a.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}})}async extractDataStructures(e,t){const a=this.xref;let r;const i=this.readToUnicode(t.toUnicode);if(t.composite){const a=e.get("CIDSystemInfo");a instanceof Dict&&!t.cidSystemInfo&&(t.cidSystemInfo={registry:stringToPDFString(a.get("Registry")),ordering:stringToPDFString(a.get("Ordering")),supplement:a.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(r=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const n=[];let s,o=null;if(e.has("Encoding")){s=e.get("Encoding");if(s instanceof Dict){o=s.get("BaseEncoding");o=o instanceof Name?o.name:null;if(s.has("Differences")){const e=s.get("Differences");let t=0;for(const r of e){const e=a.fetchIfRef(r);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);n[t++]=e.name}}}}else if(s instanceof Name)o=s.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==o&&"MacExpertEncoding"!==o&&"WinAnsiEncoding"!==o&&(o=null)}const c=!t.file||t.isInternalFont,l=Xr()[t.name];o&&c&&l&&(o=null);if("WinAnsiEncoding"===o&&c&&t.name?.charCodeAt(0)>=183){const e=t.name;if(["ËÎÌå","ºÚÌå","¿¬Ìå","·ÂËÎ","¿¬Ìå_GB2312","·ÂËÎ_GB2312","Á¥Êé","ÐÂËÎ"].includes(e)){o=null;t.defaultEncoding="Adobe-GB1-UCS2";t.composite=!0;t.cidEncoding=Name.get("GBK-EUC-H");const e=await CMapFactory.create({encoding:t.cidEncoding,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null});t.cMap=e;t.vertical=t.cMap.vertical;t.cidSystemInfo={registry:"Adobe",ordering:"GB1",supplement:0}}}if(o)t.defaultEncoding=getEncoding(o);else{let e=!!(t.flags&Ar);const a=!!(t.flags&kr);if("TrueType"===t.type&&e&&a&&0!==n.length){t.flags&=~Ar;e=!1}s=lr;"TrueType"!==t.type||a||(s=hr);if(e||l){s=cr;c&&(/Symbol/i.test(t.name)?s=ur:/Dingbats/i.test(t.name)?s=dr:/Wingdings/i.test(t.name)&&(s=hr))}t.defaultEncoding=s}t.differences=n;t.baseEncodingName=o;t.hasEncoding=!!o||n.length>0;t.dict=e;t.toUnicode=await i;const h=await this.buildToUnicode(t);t.toUnicode=h;r&&(t.cidToGidMap=this.readCidToGidMap(r,h));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const a=[],r=e.defaultEncoding.slice(),i=e.baseEncodingName,n=e.differences;for(const e in n){const t=n[e];".notdef"!==t&&(r[e]=t)}const s=fr();for(const n in r){let o=r[n];if(""===o)continue;let c=s[o];if(void 0!==c){a[n]=String.fromCharCode(c);continue}let l=0;switch(o[0]){case"G":3===o.length&&(l=parseInt(o.substring(1),16));break;case"g":5===o.length&&(l=parseInt(o.substring(1),16));break;case"C":case"c":if(o.length>=3&&o.length<=4){const a=o.substring(1);if(t){l=parseInt(a,16);break}l=+a;if(Number.isNaN(l)&&Number.isInteger(parseInt(a,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":c=getUnicodeForGlyph(o,s);-1!==c&&(l=c);break;default:switch(o){case"f_h":case"f_t":case"T_h":a[n]=o.replaceAll("_","");continue}}if(l>0&&l<=1114111&&Number.isInteger(l)){if(i&&l===+n){const e=getEncoding(i);if(e&&(o=e[n])){a[n]=String.fromCharCode(s[o]);continue}}a[n]=String.fromCodePoint(l)}}return a}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:a}=e.cidSystemInfo,r=Name.get(`${t}-${a}-UCS2`),i=await CMapFactory.create({encoding:r,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),n=[],s=[];e.cMap.forEach(function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const a=i.lookup(t);if(a){s.length=0;for(let e=0,t=a.length;e>1;(0!==i||t.has(n))&&(a[n]=i)}return a}extractWidths(e,t,a){const r=this.xref;let i=[],n=0;const s=[];let o;if(a.composite){const t=e.get("DW");n="number"==typeof t?Math.ceil(t):1e3;const c=e.get("W");if(Array.isArray(c))for(let e=0,t=c.length;e{const t=c.get(e),r=new OperatorList;return n.getOperatorList({stream:t,task:a,resources:l,operatorList:r}).then(()=>{switch(r.fnArray[0]){case rt:this.#fe(r,b);break;case at:b||this.#ge(r)}h[e]=r.getIR();for(const e of r.dependencies)i.add(e)}).catch(function(t){warn(`Type3 font resource "${e}" is not available.`);const a=new OperatorList;h[e]=a.getIR()})});this.#de=o.then(()=>{r.charProcOperatorList=h;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}});return this.#de}#fe(e,t=NaN){const a=Util.normalizeRect(e.argsArray[0].slice(2)),r=a[2]-a[0],i=a[3]-a[1],n=Math.hypot(r,i);if(0===r||0===i){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(n/t)>=10){this._bbox??=[1/0,1/0,-1/0,-1/0];Util.rectBoundingBox(...a,this._bbox)}let s=0,o=e.length;for(;s=Se&&n<=Ee;if(i.variableArgs)o>s&&info(`Command ${r}: expected [0, ${s}] args, but received ${o} args.`);else{if(o!==s){const e=this.nonProcessedArgs;for(;o>s;){e.push(t.shift());o--}for(;oEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(n,t);e.fn=n;e.args=t;return!0}if(a===sa)return!1;if(null!==a){null===t&&(t=[]);t.push(a);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case ye:this.stateManager.save();break;case we:this.stateManager.restore();break;case xe:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:a,args:r}=e;switch(0|a){case ze:const[e,a]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof a&&a>0&&(t.fontSize=a);break;case ft:ColorSpaceUtils.rgb.getRgbItem(r,0,t.fontColor,0);break;case ut:ColorSpaceUtils.gray.getRgbItem(r,0,t.fontColor,0);break;case pt:ColorSpaceUtils.cmyk.getRgbItem(r,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,a,r){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=a;this.globalColorSpaceCache=r;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpaceUtils.gray},a=!1;const r=[];try{for(;;){e.args.length=0;if(a||!this.read(e))break;const{fn:i,args:n}=e;switch(0|i){case ye:r.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case we:t=r.pop()||t;break;case Je:t.scaleFactor*=Math.hypot(n[0],n[1]);break;case ze:const[e,i]=n;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i*t.scaleFactor);break;case nt:t.fillColorSpace=ColorSpaceUtils.parse({cs:n[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:this._localColorSpaceCache});break;case ct:t.fillColorSpace.getRgbItem(n,0,t.fontColor,0);break;case ft:ColorSpaceUtils.rgb.getRgbItem(n,0,t.fontColor,0);break;case ut:ColorSpaceUtils.gray.getRgbItem(n,0,t.fontColor,0);break;case pt:ColorSpaceUtils.cmyk.getRgbItem(n,0,t.fontColor,0);break;case Ze:case Qe:case et:case tt:a=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,e=>numberToString(e/255)).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const a=new OffscreenCanvas(1,1);this.ctxMeasure=a.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.setIfName("Type","FontDescriptor");e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.setIfName("FontStretch","Normal");e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.setIfName("Type","Font");e.setIfName("Subtype","CIDFontType0");e.setIfName("CIDToGIDMap","Identity");e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],a=[...this.widths.entries()].sort();let r=null,i=null;for(const[e,n]of a)if(r)if(e===r+i.length)i.push(n);else{t.push(r,i);r=e;i=[n]}else{r=e;i=[n]}r&&t.push(r,i);e.set("W",t);const n=new Dict(this.xref);n.set("Ordering","Identity");n.set("Registry","Adobe");n.set("Supplement",0);e.set("CIDSystemInfo",n);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.setIfName("Type","Font");e.setIfName("Subtype","Type0");e.setIfName("Encoding","Identity-H");e.set("DescendantFonts",[this.descendantFontRef]);e.setIfName("ToUnicode","Identity-H");return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const a of e.split(/\r\n?|\n/))for(const e of a.split("")){const a=e.charCodeAt(0);if(this.widths.has(a))continue;const r=t.measureText(e),i=Math.ceil(r.width);this.widths.set(a,i);this.firstChar=Math.min(a,this.firstChar);this.lastChar=Math.max(a,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[n,s,o,c]=e;let l=o-n,h=c-s;t%180!=0&&([l,h]=[h,l]);const u=a*i;return{coords:[0,h+r*i-u],bbox:[0,0,l,h],matrix:0!==t?getRotationMatrix(t,h,u):void 0}}createAppearance(e,t,i,n,s,o){const c=this._createContext(),l=[];let h=-1/0;for(const t of e.split(/\r\n?|\n/)){l.push(t);const e=c.measureText(t).width;h=Math.max(h,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let a=this.widths.get(e);if(void 0===a){const r=c.measureText(t);a=Math.ceil(r.width);this.widths.set(e,a);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}h*=n/1e3;const[u,d,f,g]=t;let p=f-u,m=g-d;i%180!=0&&([p,m]=[m,p]);let b=1;h>p&&(b=p/h);let y=1;const w=a*n,x=r*n,S=w*l.length;S>m&&(y=m/S);const k=n*Math.min(b,y),C=["q",`0 0 ${numberToString(p)} ${numberToString(m)} re W n`,"BT",`1 0 0 1 0 ${numberToString(m+x)} Tm 0 Tc ${getPdfColor(s,!0)}`,`/${this.fontName.name} ${numberToString(k)} Tf`],{resources:v}=this;if(1!==(o="number"==typeof o&&o>=0&&o<=1?o:1)){C.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",o);t.set("CA",o);t.setIfName("Type","ExtGState");e.set("R0",t);v.set("ExtGState",e)}const F=numberToString(w);for(const e of l)C.push(`0 -${F} Td <${stringToUTF16HexString(e)}> Tj`);C.push("ET","Q");const T=C.join("\n"),O=new Dict(this.xref);O.setIfName("Subtype","Form");O.setIfName("Type","XObject");O.set("BBox",[0,0,p,m]);O.set("Length",T.length);O.set("Resources",v);if(i){const e=getRotationMatrix(i,p,m);O.set("Matrix",e)}const D=new StringStream(T);D.dict=O;return D}}const kn=["m/d","m/d/yy","mm/dd/yy","mm/yy","d-mmm","d-mmm-yy","dd-mmm-yy","yy-mm-dd","mmm-yy","mmmm-yy","mmm d, yyyy","mmmm d, yyyy","m/d/yy h:MM tt","m/d/yy HH:MM"],Cn=["HH:MM","h:MM tt","HH:MM:ss","h:MM:ss tt"];class NameOrNumberTree{constructor(e,t,a){this.root=e;this.xref=t;this._type=a}getAll(e=!1){const t=new Map;if(!this.root)return t;const a=this.xref,r=new RefSet;r.put(this.root);const i=[this.root];for(;i.length>0;){const n=a.fetchIfRef(i.shift());if(!(n instanceof Dict))continue;if(n.has("Kids")){const e=n.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(r.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);i.push(t);r.put(t)}continue}const s=n.get(this._type);if(Array.isArray(s))for(let r=0,i=s.length;r10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const i=a.get("Kids");if(!Array.isArray(i))return null;let n=0,s=i.length-1;for(;n<=s;){const r=n+s>>1,o=t.fetchIfRef(i[r]),c=o.get("Limits");if(et.fetchIfRef(c[1]))){a=o;break}n=r+1}}if(n>s)return null}const i=a.get(this._type);if(Array.isArray(i)){let a=0,r=i.length-2;for(;a<=r;){const n=a+r>>1,s=n+(1&n),o=t.fetchIfRef(i[s]);if(eo))return i[s+1];a=s+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){gi=Object.create(null)}();!function clearPrimitiveCaches(){oa=Object.create(null);ca=Object.create(null);la=Object.create(null)}();!function clearUnicodeCaches(){yr.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#pe=!1;constructor(e,t,a=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");a||(e.has("EF")?this.#pe=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t,!0).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#pe)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const vn=0,Fn=-2,In=-3,Tn=-4,On=-5,Dn=-6,Mn=-9;function isWhitespace(e,t){const a=e[t];return" "===a||"\n"===a||"\r"===a||"\t"===a}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,(e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)})}_parseContent(e,t){const a=[];let r=t;function skipWs(){for(;r"!==e[r]&&"/"!==e[r];)++r;const i=e.substring(t,r);skipWs();for(;r"!==e[r]&&"/"!==e[r]&&"?"!==e[r];){skipWs();let t="",i="";for(;r"!==e[a]&&"?"!==e[a]&&"/"!==e[a];)++a;const r=e.substring(t,a);!function skipWs(){for(;a"!==e[a+1]);)++a;return{name:r,value:e.substring(i,a),parsed:a-t}}parseXml(e){let t=0;for(;t",a);if(t<0){this.onError(Mn);return}this.onEndElement(e.substring(a,t));a=t+1;break;case"?":++a;const r=this._parseProcessingInstruction(e,a);if("?>"!==e.substring(a+r.parsed,a+r.parsed+2)){this.onError(In);return}this.onPi(r.name,r.value);a+=r.parsed+2;break;case"!":if("--"===e.substring(a+1,a+3)){t=e.indexOf("--\x3e",a+3);if(t<0){this.onError(On);return}this.onComment(e.substring(a+3,t));a=t+3}else if("[CDATA["===e.substring(a+1,a+8)){t=e.indexOf("]]>",a+8);if(t<0){this.onError(Fn);return}this.onCdata(e.substring(a+8,t));a=t+3}else{if("DOCTYPE"!==e.substring(a+1,a+8)){this.onError(Dn);return}{const r=e.indexOf("[",a+8);let i=!1;t=e.indexOf(">",a+8);if(t<0){this.onError(Tn);return}if(r>0&&t>r){t=e.indexOf("]>",a+8);if(t<0){this.onError(Tn);return}i=!0}const n=e.substring(a+8,t+(i?1:0));this.onDoctype(n);a=t+(i?2:1)}}break;default:const i=this._parseContent(e,a);if(null===i){this.onError(Dn);return}let n=!1;if("/>"===e.substring(a+i.parsed,a+i.parsed+2))n=!0;else if(">"!==e.substring(a+i.parsed,a+i.parsed+1)){this.onError(Mn);return}this.onBeginElement(i.name,i.attributes,n);a+=i.parsed+(n?2:1)}}else{for(;ae.textContent).join(""):this.nodeValue||""}get children(){return this.childNodes||[]}hasChildNodes(){return this.childNodes?.length>0}searchNode(e,t){if(t>=e.length)return this;const a=e[t];if(a.name.startsWith("#")&&t0){r.push([i,0]);i=i.childNodes[0]}else{if(0===r.length)return null;for(;0!==r.length;){const[e,t]=r.pop(),a=t+1;if(a");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=vn;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=vn;this.parseXml(e);if(this._errorCode!==vn)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,a=e.length;t\\376\\377([^<]+)/g,function(e,t){const a=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,function(e,t,a,r){return String.fromCharCode(64*t+8*a+1*r)}).replaceAll(/&(amp|apos|gt|lt|quot);/g,function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)}),r=[">"];for(let e=0,t=a.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?r.push(String.fromCharCode(t)):r.push("&#x"+(65536+t).toString(16).substring(1)+";")}return r.join("")})}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter(e=>"rdf:li"===e.nodeName)}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,a=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,a.map(e=>e.textContent.trim()))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Rn=1,Bn=2,Nn=3,Pn=4,En=5;class StructTreeRoot{constructor(e,t,a){this.xref=e;this.dict=t;this.ref=a instanceof Ref?a:null;this.roleMap=new Map;this.structParentIds=null;this.kidRefToPosition=void 0;this.parentTree=null}getKidPosition(e){if(void 0===this.kidRefToPosition){const e=this.dict.get("K");if(Array.isArray(e)){const t=this.kidRefToPosition=new Map;for(let a=0,r=e.length;a=0||(e.parentTreeId=a++);s=!1}}if(s){for(const e of t.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:a}){const{ref:r,xref:i}=this,n=this.dict.clone(),s=new RefSetCache;s.put(r,n);let o,c=n.getRaw("ParentTree");if(c instanceof Ref)o=i.fetch(c);else{o=c;c=i.getNewTemporaryRef();n.set("ParentTree",c)}o=o.clone();s.put(c,o);let l=o.getRaw("Nums"),h=null;if(l instanceof Ref){h=l;l=i.fetch(h)}l=l.slice();h||o.set("Nums",l);const u=await StructTreeRoot.#be({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:l,xref:i,pdfManager:t,changes:a,cache:s});if(-1!==u){n.set("ParentTreeNextKey",u);h&&s.put(h,l);for(const[e,t]of s.items())a.put(e,{data:t})}}static async#be({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:a,kids:r,nums:i,xref:n,pdfManager:s,changes:o,cache:c}){const l=Name.get("OBJR");let h,u=-1;for(const[d,f]of e){const e=await s.getPage(d),{ref:g}=e,p=g instanceof Ref;for(const{accessibilityData:s,ref:m,parentTreeId:b,structTreeParent:y}of f){if(!s?.type)continue;const{structParent:f}=s;if(a&&Number.isInteger(f)&&f>=0){let t=(h||=new Map).get(d);if(void 0===t){t=new StructTreePage(a,e.pageDict).collectObjects(g);h.set(d,t)}const r=t?.get(f);if(r){const e=n.fetch(r).clone();StructTreeRoot.#we(e,s);o.put(r,{data:e});continue}}u=Math.max(u,b);const w=n.getNewTemporaryRef(),x=new Dict(n);StructTreeRoot.#we(x,s);await this.#xe({structTreeParent:y,tagDict:x,newTagRef:w,structTreeRootRef:t,fallbackKids:r,xref:n,cache:c});const S=new Dict(n);x.set("K",S);S.set("Type",l);p&&S.set("Pg",g);S.set("Obj",m);c.put(w,x);i.push(b,w)}}return u+1}static#we(e,{type:t,title:a,lang:r,alt:i,expanded:n,actualText:s}){e.set("S",Name.get(t));a&&e.set("T",stringToAsciiOrUTF16BE(a));r&&e.set("Lang",stringToAsciiOrUTF16BE(r));i&&e.set("Alt",stringToAsciiOrUTF16BE(i));n&&e.set("E",stringToAsciiOrUTF16BE(n));s&&e.set("ActualText",stringToAsciiOrUTF16BE(s))}static#ye({elements:e,xref:t,pageDict:a,numberTree:r}){const i=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let a=i.get(e);if(!a){a=[];i.set(e,a)}a.push(t)}const n=a.get("StructParents");if(!Number.isInteger(n))return;const s=r.get(n),updateElement=(e,a,r)=>{const n=i.get(e);if(n){const e=a.getRaw("P"),i=t.fetchIfRef(e);if(e instanceof Ref&&i instanceof Dict){const e={ref:r,dict:a};for(const t of n)t.structTreeParent=e}return!0}return!1};for(const e of s){if(!(e instanceof Ref))continue;const a=t.fetch(e),r=a.get("K");if(Number.isInteger(r))updateElement(r,a,e);else if(Array.isArray(r))for(let i of r){i=t.fetchIfRef(i);if(Number.isInteger(i)&&updateElement(i,a,e))break;if(!(i instanceof Dict))continue;if(!isName(i.get("Type"),"MCR"))break;const r=i.get("MCID");if(Number.isInteger(r)&&updateElement(r,a,e))break}}}static async#xe({structTreeParent:e,tagDict:t,newTagRef:a,structTreeRootRef:r,fallbackKids:i,xref:n,cache:s}){let o,c=null;if(e){({ref:c}=e);o=e.dict.getRaw("P")||r}else o=r;t.set("P",o);const l=n.fetchIfRef(o);if(!l){i.push(a);return}let h=s.get(o);if(!h){h=l.clone();s.put(o,h)}const u=h.getRaw("K");let d=u instanceof Ref?s.get(u):null;if(!d){d=n.fetchIfRef(u);d=Array.isArray(d)?d.slice():[u];const e=n.getNewTemporaryRef();h.set("K",e);s.put(e,d)}const f=d.indexOf(c);d.splice(f>=0?f+1:d.length,0,a)}}class StructElementNode{constructor(e,t){this.tree=e;this.xref=e.xref;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:a}=this.tree;return a.roleMap.get(t)??t}get mathML(){let e=this.dict.get("AF")||[];Array.isArray(e)||(e=[e]);for(let t of e){t=this.xref.fetchIfRef(t);if(!(t instanceof Dict))continue;if(!isName(t.get("Type"),"Filespec"))continue;if(!isName(t.get("AFRelationship"),"Supplement"))continue;const e=t.get("EF");if(!(e instanceof Dict))continue;const a=e.get("UF")||e.get("F");if(a instanceof BaseStream&&(isName(a.dict.get("Type"),"EmbeddedFile")&&isName(a.dict.get("Subtype"),"application/mathml+xml")))return stringToUTF8String(a.getString())}const t=this.dict.get("A");if(t instanceof Dict){if(isName(t.get("O"),"MSFT_Office")){const e=t.get("MSFT_MathML");return e?stringToPDFString(e):null}}return null}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const a=this.dict.get("K");if(Array.isArray(a))for(const t of a){const a=this.parseKid(e,this.xref.fetchIfRef(t));a&&this.kids.push(a)}else{const t=this.parseKid(e,a);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Rn,mcid:t,pageObjId:e});if(!(t instanceof Dict))return null;const a=t.getRaw("Pg");a instanceof Ref&&(e=a.toString());const r=t.get("Type")instanceof Name?t.get("Type").name:null;if("MCR"===r){if(this.tree.pageDict.objId!==e)return null;const a=t.getRaw("Stm");return new StructElement({type:Bn,refObjId:a instanceof Ref?a.toString():null,pageObjId:e,mcid:t.get("MCID")})}if("OBJR"===r){if(this.tree.pageDict.objId!==e)return null;const a=t.getRaw("Obj");return new StructElement({type:Nn,refObjId:a instanceof Ref?a.toString():null,pageObjId:e})}return new StructElement({type:En,dict:t})}}class StructElement{constructor({type:e,dict:t=null,mcid:a=null,pageObjId:r=null,refObjId:i=null}){this.type=e;this.dict=t;this.mcid=a;this.pageObjId=r;this.refObjId=i;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.xref=e?.xref??null;this.rootDict=e?.dict??null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const a=this.root.structParentIds?.get(e);if(!a)return null;const r=new Map,i=new NumberTree(t,this.xref);for(const[e]of a){const t=i.getRaw(e);t instanceof Ref&&r.set(e,t)}return r}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const{parentTree:t}=this.root;if(!t)return;const a=this.pageDict.get("StructParents"),r=this.root.structParentIds?.get(e);if(!Number.isInteger(a)&&!r)return;const i=new Map;if(Number.isInteger(a)){const e=t.get(a);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.xref.fetch(t),i)}if(r)for(const[e,a]of r){const r=t.get(e);if(r){const e=this.addNode(this.xref.fetchIfRef(r),i);1===e?.kids?.length&&e.kids[0].type===Nn&&(e.kids[0].type=a)}}}addNode(e,t,a=0){if(a>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const r=new StructElementNode(this,e);t.set(e,r);switch(r.role){case"L":case"LBody":case"LI":case"Table":case"THead":case"TBody":case"TFoot":case"TR":for(const e of r.kids)e.type===En&&this.addNode(e.dict,t,a-1)}const i=e.get("P");if(!(i instanceof Dict)||isName(i.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,r)||t.delete(e);return r}const n=this.addNode(i,t,a+1);if(!n)return r;let s=!1;for(const t of n.kids)if(t.type===En&&t.dict===e){t.parentNode=r;s=!0}s||t.delete(e);return r}addTopLevelNode(e,t){const a=this.root.getKidPosition(e.objId);if(isNaN(a))return!1;-1!==a&&(this.nodes[a]=t);return!0}get serializable(){function nodeToSerializable(e,t,a=0){if(a>40){warn("StructTree too deep to be fully serialized.");return}const r=Object.create(null);r.role=e.role;r.children=[];t.children.push(r);let i=e.dict.get("Alt");"string"!=typeof i&&(i=e.dict.get("ActualText"));"string"==typeof i&&(r.alt=stringToPDFString(i));if("Formula"===r.role){const{mathML:t}=e;t&&(r.mathML=t)}const n=e.dict.get("A");if(n instanceof Dict){const e=lookupNormalRect(n.getArray("BBox"),null);if(e)r.bbox=e;else{const e=n.get("Width"),t=n.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(r.bbox=[0,0,e,t])}}const s=e.dict.get("Lang");"string"==typeof s&&(r.lang=stringToPDFString(s));for(const t of e.kids){const e=t.type===En?t.parentNode:null;e?nodeToSerializable(e,r,a+1):t.type===Rn||t.type===Bn?r.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Nn?r.children.push({type:"object",id:t.refObjId}):t.type===Pn&&r.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}const Ln=function _isValidExplicitDest(e,t,a){if(!Array.isArray(a)||a.length<2)return!1;const[r,i,...n]=a;if(!e(r)&&!Number.isInteger(r))return!1;if(!t(i))return!1;const s=n.length;let o=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;o=!1;break;default:return!1}for(const e of n)if(!("number"==typeof e||o&&null===e))return!1;return!0}.bind(null,e=>e instanceof Ref,isName);function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return Ln(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t,!0);if(Ln(t))return JSON.stringify(t)}return null}class Catalog{#Se=null;#Ae=null;builtInCMapCache=new Map;fontCache=new RefSetCache;globalColorSpaceCache=new GlobalColorSpaceCache;globalImageCache=new GlobalImageCache;nonBlendModesSet=new RefSet;pageDictCache=new RefSetCache;pageIndexCache=new RefSetCache;pageKidsCountCache=new RefSetCache;standardFontDataCache=new Map;systemFontCache=new Map;constructor(e,t){this.pdfManager=e;this.xref=t;this.#Ae=t.getCatalogObj();if(!(this.#Ae instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict}cloneDict(){return this.#Ae.clone()}get version(){const e=this.#Ae.get("Version");if(e instanceof Name){if(ua.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this.#Ae.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this.#Ae.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this.#Ae.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this.#Ae.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this.#Ae.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this.#Ae.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const a=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(a instanceof BaseStream&&a.dict instanceof Dict){const e=a.dict.get("Type"),r=a.dict.get("Subtype");if(isName(e,"Metadata")&&isName(r,"XML")){const e=stringToUTF8String(a.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this.#ke()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}#ke(){const e=this.#Ae.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const a in t){const r=e.get(a);"boolean"==typeof r&&(t[a]=r)}return t}get hasStructTree(){return this.#Ae.has("StructTreeRoot")}get structTreeRoot(){let e=null;try{e=this.#Ce()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}#Ce(){const e=this.#Ae.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const a=new StructTreeRoot(this.xref,t,e);a.init();return a}get toplevelPagesDict(){const e=this.#Ae.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this.#ve()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}#ve(){let e=this.#Ae.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},a=[{obj:e,parent:t}],r=new RefSet;r.put(e);const i=this.xref,n=new Uint8ClampedArray(3);for(;a.length>0;){const t=a.shift(),s=i.fetchIfRef(t.obj);if(null===s)continue;s.has("Title")||warn("Invalid outline item encountered.");const o={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:s,resultObj:o,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const c=s.get("Title"),l=s.get("F")||0,h=s.getArray("C"),u=s.get("Count");let d=n;!isNumberArray(h,3)||0===h[0]&&0===h[1]&&0===h[2]||(d=ColorSpaceUtils.rgb.getRgb(h,0));const f={action:o.action,attachment:o.attachment,dest:o.dest,url:o.url,unsafeUrl:o.unsafeUrl,newWindow:o.newWindow,setOCGState:o.setOCGState,title:"string"==typeof c?stringToPDFString(c):"",color:d,count:Number.isInteger(u)?u:void 0,bold:!!(2&l),italic:!!(1&l),items:[]};t.parent.items.push(f);e=s.getRaw("First");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:f});r.put(e)}e=s.getRaw("Next");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:t.parent});r.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this.#Fe()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}#Fe(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const a=[];for(const e in w){const r=w[e];t&r&&a.push(r)}return a}get optionalContentConfig(){let e=null;try{const t=this.#Ae.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const a=t.get("D");if(!a)return shadow(this,"optionalContentConfig",null);const r=t.get("OCGs");if(!Array.isArray(r))return shadow(this,"optionalContentConfig",null);const i=new RefSetCache;for(const e of r)e instanceof Ref&&!i.has(e)&&i.put(e,this.#Ie(e));e=this.#Te(a,i)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#Ie(e){const t=this.xref.fetch(e),a={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},r=t.get("Name");"string"==typeof r&&(a.name=stringToPDFString(r));let i=t.getArray("Intent");Array.isArray(i)||(i=[i]);i.every(e=>e instanceof Name)&&(a.intent=i.map(e=>e.name));const n=t.get("Usage");if(!(n instanceof Dict))return a;const s=a.usage,o=n.get("Print");if(o instanceof Dict){const e=o.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.print={printState:e.name}}}const c=n.get("View");if(c instanceof Dict){const e=c.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.view={viewState:e.name}}}return a}#Te(e,t){function parseOnOff(e){const a=[];if(Array.isArray(e))for(const r of e)r instanceof Ref&&t.has(r)&&a.push(r.toString());return a}function parseOrder(e,a=0){if(!Array.isArray(e))return null;const i=[];for(const n of e){if(n instanceof Ref&&t.has(n)){r.put(n);i.push(n.toString());continue}const e=parseNestedOrder(n,a);e&&i.push(e)}if(a>0)return i;const n=[];for(const[e]of t.items())r.has(e)||n.push(e.toString());n.length&&i.push({name:null,order:n});return i}function parseNestedOrder(e,t){if(++t>i){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const r=a.fetchIfRef(e);if(!Array.isArray(r))return null;const n=a.fetchIfRef(r[0]);if("string"!=typeof n)return null;const s=parseOrder(r.slice(1),t);return s?.length?{name:stringToPDFString(n),order:s}:null}const a=this.xref,r=new RefSet,i=10;!function parseRBGroups(e){if(Array.isArray(e))for(const r of e){const e=a.fetchIfRef(r);if(!Array.isArray(e)||!e.length)continue;const i=new Set;for(const a of e)if(a instanceof Ref&&t.has(a)&&!i.has(a.toString())){i.add(a.toString());t.get(a).rbGroups.push(i)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this.#Se=e}get hasActualNumPages(){return null!==this.#Se}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.#Se??this._pagesCount}get destinations(){const e=this.#Oe(),t=Object.create(null);for(const a of e)if(a instanceof NameTree)for(const[e,r]of a.getAll()){const a=fetchDest(r);a&&(t[stringToPDFString(e,!0)]=a)}else if(a instanceof Dict)for(const[e,r]of a){const a=fetchDest(r);a&&(t[stringToPDFString(e,!0)]||=a)}return shadow(this,"destinations",t)}getDestination(e){if(this.hasOwnProperty("destinations"))return this.destinations[e]??null;const t=this.#Oe();for(const a of t)if(a instanceof NameTree||a instanceof Dict){const t=fetchDest(a.get(e));if(t)return t}if(t.length){const t=this.destinations[e];if(t)return t}return null}#Oe(){const e=this.#Ae.get("Names"),t=[];e?.has("Dests")&&t.push(new NameTree(e.getRaw("Dests"),this.xref));this.#Ae.has("Dests")&&t.push(this.#Ae.get("Dests"));return t}get rawPageLabels(){const e=this.#Ae.getRaw("PageLabels");if(!e)return null;return new NumberTree(e,this.xref).getAll()}get pageLabels(){let e=null;try{e=this.#De()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}#De(){const e=this.rawPageLabels;if(!e)return null;const t=new Array(this.numPages);let a=null,r="",i="",n=1;for(let s=0,o=this.numPages;s=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(a){case"D":i=n;break;case"R":case"r":i=toRomanNumerals(n,"r"===a);break;case"A":case"a":const e=26,t="a"===a?97:65,r=n-1;i=String.fromCharCode(t+r%e).repeat(Math.floor(r/e)+1);break;default:if(a)throw new FormatError(`Invalid style "${a}" in PageLabel dictionary.`);i=""}t[s]=r+i;n++}return t}get pageLayout(){const e=this.#Ae.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this.#Ae.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this.#Ae.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const[a,r]of e){let e;switch(a){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof r&&(e=r);break;case"NonFullScreenPageMode":if(r instanceof Name)switch(r.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":e=r.name;break;default:e="UseNone"}break;case"Direction":if(r instanceof Name)switch(r.name){case"L2R":case"R2L":e=r.name;break;default:e="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(r instanceof Name)switch(r.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":e=r.name;break;default:e="CropBox"}break;case"PrintScaling":if(r instanceof Name)switch(r.name){case"None":case"AppDefault":e=r.name;break;default:e="AppDefault"}break;case"Duplex":if(r instanceof Name)switch(r.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":e=r.name;break;default:e="None"}break;case"PrintPageRange":if(Array.isArray(r)&&r.length%2==0){r.every((e,t,a)=>Number.isInteger(e)&&e>0&&(0===t||e>=a[t-1])&&e<=this.numPages)&&(e=r)}break;case"NumCopies":Number.isInteger(r)&&r>0&&(e=r);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${a}.`);continue}if(void 0!==e){t??=Object.create(null);t[a]=e}else warn(`Bad value, for key "${a}", in ViewerPreferences: ${r}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this.#Ae.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const a=new Dict(this.xref);a.set("A",e);const r={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:a,resultObj:r});Array.isArray(r.dest)?t.dest=r.dest:r.action&&(t.action=r.action)}else Ln(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this.#Ae.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const a=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,r]of a.getAll()){const a=new FileSpec(r,this.xref);t??=Object.create(null);t[stringToPDFString(e,!0)]=a.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this.#Ae.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const a=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,r]of a.getAll())if(r instanceof BaseStream){t??=new Map;t.set(stringToPDFString(e,!0),r.getBytes())}}return shadow(this,"xfaImages",t)}#Me(){const e=this.#Ae.get("Names");let t=null;function appendIfJavaScriptDict(e,a){if(!(a instanceof Dict))return;if(!isName(a.get("S"),"JavaScript"))return;let r=a.get("JS");if(r instanceof BaseStream)r=r.getString();else if("string"!=typeof r)return;r=stringToPDFString(r,!0).replaceAll("\0","");r&&(t||=new Map).set(e,r)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,a]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e,!0),a)}const a=this.#Ae.get("OpenAction");a&&appendIfJavaScriptDict("OpenAction",a);return t}get jsActions(){const e=this.#Me();let t=collectActions(this.xref,this.#Ae,ne);if(e){t||=Object.create(null);for(const[a,r]of e)a in t?t[a].push(r):t[a]=[r]}return shadow(this,"jsActions",t)}async cleanup(e=!1){clearGlobalCaches();this.globalColorSpaceCache.clear();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();for(const{dict:e}of await Promise.all(this.fontCache))delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],a=new RefSet,r=this.#Ae.getRaw("Pages");r instanceof Ref&&a.put(r);const i=this.xref,n=this.pageKidsCountCache,s=this.pageIndexCache,o=this.pageDictCache;let c=0;for(;t.length;){const r=t.pop();if(r instanceof Ref){const l=n.get(r);if(l>=0&&c+l<=e){c+=l;continue}if(a.has(r))throw new FormatError("Pages tree contains circular reference.");a.put(r);const h=await(o.get(r)||i.fetchAsync(r));if(h instanceof Dict){let t=h.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!h.has("Kids")){n.has(r)||n.put(r,1);s.has(r)||s.put(r,c);if(c===e)return[h,r];c++;continue}}t.push(h);continue}if(!(r instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:l}=r;let h=r.getRaw("Count");h instanceof Ref&&(h=await i.fetchAsync(h));if(Number.isInteger(h)&&h>=0){l&&!n.has(l)&&n.put(l,h);if(c+h<=e){c+=h;continue}}let u=r.getRaw("Kids");u instanceof Ref&&(u=await i.fetchAsync(u));if(!Array.isArray(u)){let t=r.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!r.has("Kids")){if(c===e)return[r,null];c++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=u.length-1;e>=0;e--){const a=u[e];t.push(a);r===this.toplevelPagesDict&&a instanceof Ref&&!o.has(a)&&o.put(a,i.fetchAsync(a))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,a=[{currentNode:this.toplevelPagesDict,posInKids:0}],r=new RefSet,i=this.#Ae.getRaw("Pages");i instanceof Ref&&r.put(i);const n=new Map,s=this.xref,o=this.pageIndexCache;let c=0;function addPageDict(e,t){t&&!o.has(t)&&o.put(t,c);n.set(c++,[e,t])}function addPageError(a){if(a instanceof XRefEntryException&&!e)throw a;if(e&&t&&0===c){warn(`getAllPageDicts - Skipping invalid first page: "${a}".`);a=Dict.empty}n.set(c++,[a,null])}for(;a.length>0;){const e=a.at(-1),{currentNode:t,posInKids:i}=e;let n=t.getRaw("Kids");if(n instanceof Ref)try{n=await s.fetchAsync(n)}catch(e){addPageError(e);break}if(!Array.isArray(n)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(i>=n.length){a.pop();continue}const o=n[i];let c;if(o instanceof Ref){if(r.has(o)){addPageError(new FormatError("Pages tree contains circular reference."));break}r.put(o);try{c=await s.fetchAsync(o)}catch(e){addPageError(e);break}}else c=o;if(!(c instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let l=c.getRaw("Type");if(l instanceof Ref)try{l=await s.fetchAsync(l)}catch(e){addPageError(e);break}isName(l,"Page")||!c.has("Kids")?addPageDict(c,o instanceof Ref?o:null):a.push({currentNode:c,posInKids:0});e.posInKids++}return n}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const a=this.xref;let r=0;const next=t=>function pagesBeforeRef(t){let r,i=0;return a.fetchAsync(t).then(function(a){if(isRefsEqual(t,e)&&!isDict(a,"Page")&&!(a instanceof Dict&&!a.has("Type")&&a.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!a)return null;if(!(a instanceof Dict))throw new FormatError("Node must be a dictionary.");r=a.getRaw("Parent");return a.getAsync("Parent")}).then(function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")}).then(function(e){if(!e)return null;const n=[];let s=!1;for(const r of e){if(!(r instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(r,t)){s=!0;break}n.push(a.fetchAsync(r).then(function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?i+=e.get("Count"):i++}))}if(!s)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(n).then(()=>[i,r])})}(t).then(t=>{if(!t){this.pageIndexCache.put(e,r);return r}const[a,i]=t;r+=a;return next(i)});return next(e)}get baseUrl(){const e=this.#Ae.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:a=null,docAttachments:r=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let i,n,s=e.get("A");if(!(s instanceof Dict))if(e.has("Dest"))s=e.get("Dest");else{s=e.get("AA");s instanceof Dict&&(s.has("D")?s=s.get("D"):s.has("U")&&(s=s.get("U")))}if(s instanceof Dict){const e=s.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const a=e.name;switch(a){case"ResetForm":const e=s.get("Flags"),o=!(1&("number"==typeof e?e:0)),c=[],l=[];for(const e of s.get("Fields")||[])e instanceof Ref?l.push(e.toString()):"string"==typeof e&&c.push(stringToPDFString(e));t.resetForm={fields:c,refs:l,include:o};break;case"URI":i=s.get("URI");i instanceof Name&&(i="/"+i.name);break;case"GoTo":n=s.get("D");break;case"Launch":case"GoToR":const h=s.get("F");if(h instanceof Dict){const e=new FileSpec(h,null,!0),{rawFilename:t}=e.serializable;i=t}else"string"==typeof h&&(i=h);const u=fetchRemoteDest(s);u&&"string"==typeof i&&(i=i.split("#",1)[0]+"#"+u);const d=s.get("NewWindow");"boolean"==typeof d&&(t.newWindow=d);break;case"GoToE":const f=s.get("T");let g;if(r&&f instanceof Dict){const e=f.get("R"),t=f.get("N");isName(e,"C")&&"string"==typeof t&&(g=r[stringToPDFString(t,!0)])}if(g){t.attachment=g;const e=fetchRemoteDest(s);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const p=s.get("N");p instanceof Name&&(t.action=p.name);break;case"SetOCGState":const m=s.get("State"),b=s.get("PreserveRB");if(!Array.isArray(m)||0===m.length)break;const y=[];for(const e of m)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":y.push(e.name)}else e instanceof Ref&&y.push(e.toString());if(y.length!==m.length)break;t.setOCGState={state:y,preserveRB:"boolean"!=typeof b||b};break;case"JavaScript":const w=s.get("JS");let x;w instanceof BaseStream?x=w.getString():"string"==typeof w&&(x=w);const S=x&&recoverJsURL(stringToPDFString(x,!0));if(S){i=S.url;t.newWindow=S.newWindow;break}default:if("JavaScript"===a||"SubmitForm"===a)break;warn(`parseDestDictionary - unsupported action: "${a}".`)}}else e.has("Dest")&&(n=e.get("Dest"));if("string"==typeof i){const e=createValidAbsoluteUrl(i,a,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=i}if(n){n instanceof Name&&(n=n.name);"string"==typeof n?t.dest=stringToPDFString(n,!0):Ln(n)&&(t.dest=n)}}}function mayHaveChildren(e){return e instanceof Ref||e instanceof Dict||e instanceof BaseStream||Array.isArray(e)}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)mayHaveChildren(a)&&t.push(a)}class ObjectLoader{refSet=new RefSet;constructor(e,t,a){this.dict=e;this.keys=t;this.xref=a}async load(){const{keys:e,dict:t}=this,a=[];for(const r of e){const e=t.getRaw(r);void 0!==e&&a.push(e)}await this.#Re(a);this.refSet=null}async#Re(e){const t=[],a=[];for(;e.length;){let r=e.pop();if(r instanceof Ref){if(this.refSet.has(r))continue;try{this.refSet.put(r);r=this.xref.fetch(r)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader.#walk - requesting all data: "${e}".`);await this.xref.stream.manager.requestAllChunks();return}t.push(r);a.push({begin:e.begin,end:e.end})}}if(r instanceof BaseStream){const e=r.getBaseStreams();if(e){let i=!1;for(const t of e)if(!t.isDataLoaded){i=!0;a.push({begin:t.start,end:t.end})}i&&t.push(r)}}addChildren(r,e)}if(a.length){await this.xref.stream.manager.requestRanges(a);for(const e of t)e instanceof Ref&&this.refSet.remove(e);await this.#Re(t)}}static async load(e,t,a){if(a.stream.isDataLoaded)return;const r=new ObjectLoader(e,t,a);await r.load()}}const _n=Symbol(),Un=Symbol(),jn=Symbol(),Xn=Symbol(),qn=Symbol(),Hn=Symbol(),Wn=Symbol(),zn=Symbol(),$n=Symbol(),Gn=Symbol("content"),Vn=Symbol("data"),Kn=Symbol(),Jn=Symbol("extra"),Yn=Symbol(),Zn=Symbol(),Qn=Symbol(),es=Symbol(),ts=Symbol(),as=Symbol(),rs=Symbol(),is=Symbol(),ns=Symbol(),ss=Symbol(),os=Symbol(),cs=Symbol(),ls=Symbol(),hs=Symbol(),us=Symbol(),ds=Symbol(),fs=Symbol(),gs=Symbol(),ps=Symbol(),ms=Symbol(),bs=Symbol(),ys=Symbol(),ws=Symbol(),xs=Symbol(),Ss=Symbol(),As=Symbol(),ks=Symbol(),Cs=Symbol(),vs=Symbol(),Fs=Symbol(),Is=Symbol(),Ts=Symbol(),Os=Symbol("namespaceId"),Ds=Symbol("nodeName"),Ms=Symbol(),Rs=Symbol(),Bs=Symbol(),Ns=Symbol(),Es=Symbol(),Ls=Symbol(),_s=Symbol(),Us=Symbol(),js=Symbol("root"),Xs=Symbol(),qs=Symbol(),Hs=Symbol(),Ws=Symbol(),zs=Symbol(),$s=Symbol(),Gs=Symbol(),Vs=Symbol(),Ks=Symbol(),Js=Symbol(),Ys=Symbol(),Zs=Symbol("uid"),Qs=Symbol(),eo={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},to={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},ao=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseInt(e,10);return!isNaN(r)&&a(r)?r:t}function getFloat({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseFloat(e);return!isNaN(r)&&a(r)?r:t}function getKeyword({data:e,defaultValue:t,validate:a}){return e&&a(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const a=e.trim().match(ao);if(!a)return getMeasurement(t);const[,r,i]=a,n=parseFloat(r);if(isNaN(n))return getMeasurement(t);if(0===n)return 0;const s=to[i];return s?s(n):n}function getRatio(e){if(!e)return{num:1,den:1};const t=e.split(":",2).map(e=>parseFloat(e.trim())).filter(e=>!isNaN(e));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[a,r]=t;return{num:a,den:r}}function getRelevant(e){return e?e.trim().split(/\s+/).map(e=>({excluded:"-"===e[0],viewname:e.substring(1)})):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,a,r){this.success=e;this.html=t;this.bbox=a;this.breakNode=r}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const a=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,a)}addPdfFont(e){const t=e.cssFontInfo,a=t.fontFamily;let r=this.fonts.get(a);if(!r){r=Object.create(null);this.fonts.set(a,r);this.defaultFont||(this.defaultFont=r)}let i="";const n=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?i=n>=700?"bolditalic":"italic":n>=700&&(i="bold");if(!i){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(i="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(i+="italic")}i||(i="regular");r[i]=e}getDefault(){return this.defaultFont}find(e,t=!0){let a=this.fonts.get(e)||this.cache.get(e);if(a)return a;const r=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let i=e.replaceAll(r,"");a=this.fonts.get(i);if(a){this.cache.set(e,a);return a}i=i.toLowerCase();const n=[];for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t);if(0===n.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(0===n.length){i=i.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t)}if(0===n.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(n.length>=1){1!==n.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,n[0]);return n[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class text_FontInfo{constructor(e,t,a,r){this.lineHeight=a;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(r);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const i=r.find(e.typeface);if(i){this.pdfFont=selectFont(e,i);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(r))}else[this.pdfFont,this.xfaFont]=this.defaultFont(r)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,a,r){this.fontFinder=r;this.stack=[new text_FontInfo(e,t,a,r)]}pushData(e,t,a){const r=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=r.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=r.paraMargin[e]);const i=new text_FontInfo(e,t,a||r.lineHeight,this.fontFinder);i.pdfFont||(i.pdfFont=r.pdfFont);this.stack.push(i)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,a,r){this.glyphs=[];this.fontSelector=new FontSelector(e,t,a,r);this.extraHeight=0}pushData(e,t,a){this.fontSelector.pushData(e,t,a)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),a=t.xfaFont.size;if(t.pdfFont){const r=t.xfaFont.letterSpacing,i=t.pdfFont,n=i.lineHeight||1.2,s=t.lineHeight||Math.max(1.2,n)*a,o=n-(void 0===i.lineGap?.2:i.lineGap),c=Math.max(1,o)*a,l=a/1e3,h=i.defaultWidth||i.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=i.encodeString(t).join(""),a=i.charsToGlyphs(e);for(const e of a){const t=e.width||h;this.glyphs.push([t*l+r,s,c,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop();return}for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([a,1.2*a,a,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}compute(e){let t=-1,a=0,r=0,i=0,n=0,s=0,o=!1,c=!0;for(let l=0,h=this.glyphs.length;le){r=Math.max(r,n);n=0;i+=s;s=m;t=-1;a=0;o=!0;c=!1}else{s=Math.max(m,s);a=n;n+=h;t=l}else if(n+h>e){i+=s;s=m;if(-1!==t){l=t;r=Math.max(r,a);n=0;t=-1;a=0}else{r=Math.max(r,n);n=h}o=!0;c=!1}else{n+=h;s=Math.max(m,s)}}r=Math.max(r,n);i+=s+this.extraHeight;return{width:1.02*r,height:i,isBroken:o}}}const ro=/^[^.[]+/,io=/^[^\]]+/,no=0,so=1,oo=2,co=3,lo=4,ho=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[cs]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),uo=new WeakMap;function parseIndex(e){return"*"===(e=e.trim())?1/0:parseInt(e,10)||0}function parseExpression(e,t,a=!0){let r=e.match(ro);if(!r)return null;let[i]=r;const n=[{name:i,cacheName:"."+i,index:0,js:null,formCalc:null,operator:no}];let s=i.length;for(;s0&&h.push(e)}if(0===h.length&&!o&&0===c){const a=t[ds]();if(!(t=a))return null;c=-1;e=[t];continue}e=isFinite(l)?h.filter(e=>le[l]):h.flat()}return 0===e.length?null:e}function createDataNode(e,t,a){const r=parseExpression(a);if(!r)return null;if(r.some(e=>e.operator===so))return null;const i=ho.get(r[0].name);let n=0;if(i){e=i(e,t);n=1}else e=t||e;for(let t=r.length;ne[Gs]()).join("")}get[po](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,po,e._attributes)}[As](e){let t=this;for(;t;){if(t===e)return!0;t=t[ds]()}return!1}[ds](){return this[Fo]}[us](){return this[ds]()}[cs](e=null){return e?this[e]:this[mo]}[Kn](){const e=Object.create(null);this[Gn]&&(e.$content=this[Gn]);for(const t of Object.getOwnPropertyNames(this)){const a=this[t];null!==a&&(a instanceof XFAObject?e[t]=a[Kn]():a instanceof XFAObjectArray?a.isEmpty()||(e[t]=a.dump()):e[t]=a)}return e}[Ys](){return null}[Ks](){return HTMLResult.EMPTY}*[ls](){for(const e of this[cs]())yield e}*[xo](e,t){for(const a of this[ls]())if(!e||t===e.has(a[Ds])){const e=this[ts](),t=a[Ks](e);t.success||(this[Jn].failingNode=a);yield t}}[Zn](){return null}[Un](e,t){this[Jn].children.push(e)}[ts](){}[Xn]({filter:e=null,include:t=!0}){if(this[Jn].generator){const e=this[ts](),t=this[Jn].failingNode[Ks](e);if(!t.success)return t;t.html&&this[Un](t.html,t.bbox);delete this[Jn].failingNode}else this[Jn].generator=this[xo](e,t);for(;;){const e=this[Jn].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Un](t.html,t.bbox)}this[Jn].generator=null;return HTMLResult.EMPTY}[Ws](e){this[Oo]=new Set(Object.keys(e))}[Ao](e){const t=this[po],a=this[Oo];return[...e].filter(e=>t.has(e)&&!a.has(e))}[Xs](e,t=new Set){for(const a of this[mo])a[Io](e,t)}[Io](e,t){const a=this[So](e,t);a?this[fo](a,e,t):this[Xs](e,t)}[So](e,t){const{use:a,usehref:r}=this;if(!a&&!r)return null;let i=null,n=null,s=null,o=a;if(r){o=r;r.startsWith("#som(")&&r.endsWith(")")?n=r.slice(5,-1):r.startsWith(".#som(")&&r.endsWith(")")?n=r.slice(6,-1):r.startsWith("#")?s=r.slice(1):r.startsWith(".#")&&(s=r.slice(2))}else a.startsWith("#")?s=a.slice(1):n=a;this.use=this.usehref="";if(s)i=e.get(s);else{i=searchNode(e.get(js),this,n,!0,!1);i&&(i=i[0])}if(!i){warn(`XFA - Invalid prototype reference: ${o}.`);return null}if(i[Ds]!==this[Ds]){warn(`XFA - Incompatible prototype: ${i[Ds]} !== ${this[Ds]}.`);return null}if(t.has(i)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(i);const c=i[So](e,t);c&&i[fo](c,e,t);i[Xs](e,t);t.delete(i);return i}[fo](e,t,a){if(a.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[Gn]&&e[Gn]&&(this[Gn]=e[Gn]);new Set(a).add(e);for(const t of this[Ao](e[Oo])){this[t]=e[t];this[Oo]&&this[Oo].add(t)}for(const r of Object.getOwnPropertyNames(this)){if(this[po].has(r))continue;const i=this[r],n=e[r];if(i instanceof XFAObjectArray){for(const e of i[mo])e[Io](t,a);for(let r=i[mo].length,s=n[mo].length;rXFAObject[bo](e)):"object"==typeof e&&null!==e?Object.assign({},e):e}[zn](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Zs]=`${e[Ds]}${Mo++}`;e[mo]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[po].has(t)){e[t]=XFAObject[bo](this[t]);continue}const a=this[t];e[t]=a instanceof XFAObjectArray?new XFAObjectArray(a[Co]):null}for(const t of this[mo]){const a=t[Ds],r=t[zn]();e[mo].push(r);r[Fo]=e;null===e[a]?e[a]=r:e[a][mo].push(r)}return e}[cs](e=null){return e?this[mo].filter(t=>t[Ds]===e):this[mo]}[as](e){return this[e]}[rs](e,t,a=!0){return Array.from(this[is](e,t,a))}*[is](e,t,a=!0){if("parent"!==e){for(const a of this[mo]){a[Ds]===e&&(yield a);a.name===e&&(yield a);(t||a[Fs]())&&(yield*a[is](e,t,!1))}a&&this[po].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[Fo]}}class XFAObjectArray{constructor(e=1/0){this[Co]=e;this[mo]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[mo].length<=this[Co]){this[mo].push(e);return!0}warn(`XFA - node "${e[Ds]}" accepts no more than ${this[Co]} children`);return!1}isEmpty(){return 0===this[mo].length}dump(){return 1===this[mo].length?this[mo][0][Kn]():this[mo].map(e=>e[Kn]())}[zn](){const e=new XFAObjectArray(this[Co]);e[mo]=this[mo].map(e=>e[zn]());return e}get children(){return this[mo]}clear(){this[mo].length=0}}class XFAAttribute{constructor(e,t,a){this[Fo]=e;this[Ds]=t;this[Gn]=a;this[$n]=!1;this[Zs]="attribute"+Mo++}[ds](){return this[Fo]}[Ss](){return!0}[ns](){return this[Gn].trim()}[zs](e){e=e.value||"";this[Gn]=e.toString()}[Gs](){return this[Gn]}[As](e){return this[Fo]===e||this[Fo][As](e)}}class XmlObject extends XFAObject{constructor(e,t,a={}){super(e,t);this[Gn]="";this[yo]=null;if("#text"!==t){const e=new Map;this[go]=e;for(const[t,r]of Object.entries(a))e.set(t,new XFAAttribute(this,t,r));if(a.hasOwnProperty(Ms)){const e=a[Ms].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[yo]=!1:"dataValue"===e&&(this[yo]=!0))}}this[$n]=!1}[Js](e){const t=this[Ds];if("#text"===t){e.push(encodeToXmlString(this[Gn]));return}const a=utf8StringToString(t),r=this[Os]===Ro?"xfa:":"";e.push(`<${r}${a}`);for(const[t,a]of this[go].entries()){const r=utf8StringToString(t);e.push(` ${r}="${encodeToXmlString(a[Gn])}"`)}null!==this[yo]&&(this[yo]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[Gn]||0!==this[mo].length){e.push(">");if(this[Gn])"string"==typeof this[Gn]?e.push(encodeToXmlString(this[Gn])):this[Gn][Js](e);else for(const t of this[mo])t[Js](e);e.push(``)}else e.push("/>")}[Rs](e){if(this[Gn]){const e=new XmlObject(this[Os],"#text");this[jn](e);e[Gn]=this[Gn];this[Gn]=""}this[jn](e);return!0}[Ns](e){this[Gn]+=e}[Yn](){if(this[Gn]&&this[mo].length>0){const e=new XmlObject(this[Os],"#text");this[jn](e);e[Gn]=this[Gn];delete this[Gn]}}[Ks](){return"#text"===this[Ds]?HTMLResult.success({name:"#text",value:this[Gn]}):HTMLResult.EMPTY}[cs](e=null){return e?this[mo].filter(t=>t[Ds]===e):this[mo]}[es](){return this[go]}[as](e){const t=this[go].get(e);return void 0!==t?t:this[cs](e)}*[is](e,t){const a=this[go].get(e);a&&(yield a);for(const a of this[mo]){a[Ds]===e&&(yield a);t&&(yield*a[is](e,t))}}*[Qn](e,t){const a=this[go].get(e);!a||t&&a[$n]||(yield a);for(const a of this[mo])yield*a[Qn](e,t)}*[os](e,t,a){for(const r of this[mo]){r[Ds]!==e||a&&r[$n]||(yield r);t&&(yield*r[os](e,t,a))}}[Ss](){return null===this[yo]?0===this[mo].length||this[mo][0][Os]===eo.xhtml.id:this[yo]}[ns](){return null===this[yo]?0===this[mo].length?this[Gn].trim():this[mo][0][Os]===eo.xhtml.id?this[mo][0][Gs]().trim():null:this[Gn].trim()}[zs](e){e=e.value||"";this[Gn]=e.toString()}[Kn](e=!1){const t=Object.create(null);e&&(t.$ns=this[Os]);this[Gn]&&(t.$content=this[Gn]);t.$name=this[Ds];t.children=[];for(const a of this[mo])t.children.push(a[Kn](e));t.attributes=Object.create(null);for(const[e,a]of this[go])t.attributes[e]=a[Gn];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[Gn]=""}[Ns](e){this[Gn]+=e}[Yn](){}}class OptionObject extends ContentObject{constructor(e,t,a){super(e,t);this[vo]=a}[Yn](){this[Gn]=getKeyword({data:this[Gn],defaultValue:this[vo][0],validate:e=>this[vo].includes(e)})}[qn](e){super[qn](e);delete this[vo]}}class StringObject extends ContentObject{[Yn](){this[Gn]=this[Gn].trim()}}class IntegerObject extends ContentObject{constructor(e,t,a,r){super(e,t);this[wo]=a;this[Do]=r}[Yn](){this[Gn]=getInteger({data:this[Gn],defaultValue:this[wo],validate:this[Do]})}[qn](e){super[qn](e);delete this[wo];delete this[Do]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,e=>1===e)}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,e=>0===e)}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Bo={anchorType(e,t){const a=e[us]();if(a&&(!a.layout||"position"===a.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const a=e[us]();let r=e.w;const i=e.h;if(a.layout?.includes("row")){const t=a[Jn],i=e.colSpan;let n;if(-1===i){n=Math.sumPrecise(t.columnWidths.slice(t.currentColumn));t.currentColumn=0}else{n=Math.sumPrecise(t.columnWidths.slice(t.currentColumn,t.currentColumn+i));t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(n)||(r=e.w=n)}t.width=""!==r?measureToString(r):"auto";t.height=""!==i?measureToString(i):"auto"},position(e,t){const a=e[us]();if(!a?.layout||"position"===a.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[Ds])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Ys]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[us]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,a,r,i,n){const s=new TextMeasure(t,a,r,i);"string"==typeof e?s.addString(e):e[Es](s);return s.compute(n)}function layoutNode(e,t){let a=null,r=null,i=!1;if((!e.w||!e.h)&&e.value){let n=0,s=0;if(e.margin){n=e.margin.leftInset+e.margin.rightInset;s=e.margin.topInset+e.margin.bottomInset}let o=null,c=null;if(e.para){c=Object.create(null);o=""===e.para.lineHeight?null:e.para.lineHeight;c.top=""===e.para.spaceAbove?0:e.para.spaceAbove;c.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;c.left=""===e.para.marginLeft?0:e.para.marginLeft;c.right=""===e.para.marginRight?0:e.para.marginRight}let l=e.font;if(!l){const t=e[fs]();let a=e[ds]();for(;a&&a!==t;){if(a.font){l=a.font;break}a=a[ds]()}}const h=(e.w||t.width)-n,u=e[gs].fontFinder;if(e.value.exData&&e.value.exData[Gn]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[Gn],l,c,o,u,h);r=t.width;a=t.height;i=t.isBroken}else{const t=e.value[Gs]();if(t){const e=layoutText(t,l,c,o,u,h);r=e.width;a=e.height;i=e.isBroken}}null===r||e.w||(r+=n);null===a||e.h||(a+=s)}return{w:r,h:a,isBroken:i}}function computeBbox(e,t,a){let r;if(""!==e.w&&""!==e.h)r=[e.x,e.y,e.w,e.h];else{if(!a)return null;let i=e.w;if(""===i){if(0===e.maxW){const t=e[us]();i="position"===t.layout&&""!==t.w?0:e.minW}else i=Math.min(e.maxW,a.width);t.attributes.style.width=measureToString(i)}let n=e.h;if(""===n){if(0===e.maxH){const t=e[us]();n="position"===t.layout&&""!==t.h?0:e.minH}else n=Math.min(e.maxH,a.height);t.attributes.style.height=measureToString(n)}r=[e.x,e.y,i,n]}return r}function fixDimensions(e){const t=e[us]();if(t.layout?.includes("row")){const a=t[Jn],r=e.colSpan;let i;i=-1===r?Math.sumPrecise(a.columnWidths.slice(a.currentColumn)):Math.sumPrecise(a.columnWidths.slice(a.currentColumn,a.currentColumn+r));isNaN(i)||(e.w=i)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=Math.sumPrecise(e.columnWidths))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const a=Object.create(null);for(const r of t){const t=e[r];if(null!==t)if(Bo.hasOwnProperty(r))Bo[r](e,a);else if(t instanceof XFAObject){const e=t[Ys]();e?Object.assign(a,e):warn(`(DEBUG) - XFA - style for ${r} not implemented yet`)}}return a}function createWrapper(e,t){const{attributes:a}=t,{style:r}=a,i={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};a.class.push("xfaWrapped");if(e.border){const{widths:a,insets:n}=e.border[Jn];let s,o,c=n[0],l=n[3];const h=n[0]+n[2],u=n[1]+n[3];switch(e.border.hand){case"even":c-=a[0]/2;l-=a[3]/2;s=`calc(100% + ${(a[1]+a[3])/2-u}px)`;o=`calc(100% + ${(a[0]+a[2])/2-h}px)`;break;case"left":c-=a[0];l-=a[3];s=`calc(100% + ${a[1]+a[3]-u}px)`;o=`calc(100% + ${a[0]+a[2]-h}px)`;break;case"right":s=u?`calc(100% - ${u}px)`:"100%";o=h?`calc(100% - ${h}px)`:"100%"}const d=["xfaBorder"];isPrintOnly(e.border)&&d.push("xfaPrintOnly");const f={name:"div",attributes:{class:d,style:{top:`${c}px`,left:`${l}px`,width:s,height:o}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==r[e]){f.attributes.style[e]=r[e];delete r[e]}i.children.push(f,t)}else i.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==r[e]){i.attributes.style[e]=r[e];delete r[e]}i.attributes.style.position="absolute"===r.position?"absolute":"relative";delete r.position;if(r.alignSelf){i.attributes.style.alignSelf=r.alignSelf;delete r.alignSelf}return i}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const a="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),r=getMeasurement(e[a],"0px");e[a]=r-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[fs]()[Jn].paraStack;return t.length?t.at(-1):null}function setPara(e,t,a){if(a.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const r=getCurrentPara(e);if(r){const e=a.attributes.style;e.display="flex";e.flexDirection="column";switch(r.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=r[Ys]();for(const[a,r]of Object.entries(t))a in e||(e[a]=r)}}}function setFontFamily(e,t,a,r){if(!a){delete r.fontFamily;return}const i=stripQuotes(e.typeface);r.fontFamily=`"${i}"`;const n=a.find(i);if(n){const{fontFamily:a}=n.regular.cssFontInfo;a!==i&&(r.fontFamily=`"${a}"`);const s=getCurrentPara(t);if(s&&""!==s.lineHeight)return;if(r.lineHeight)return;const o=selectFont(e,n);o&&(r.lineHeight=Math.max(1.2,o.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Jn])return null;const t={name:"div",attributes:e[Jn].attributes,children:e[Jn].children};if(e[Jn].failingNode){const a=e[Jn].failingNode[Zn]();a&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[a])):t.children.push(a))}return 0===t.children.length?null:t}function addHTML(e,t,a){const r=e[Jn],i=r.availableSpace,[n,s,o,c]=a;switch(e.layout){case"position":r.width=Math.max(r.width,n+o);r.height=Math.max(r.height,s+c);r.children.push(t);break;case"lr-tb":case"rl-tb":if(!r.line||1===r.attempt){r.line=createLine(e,[]);r.children.push(r.line);r.numberInLine=0}r.numberInLine+=1;r.line.children.push(t);if(0===r.attempt){r.currentWidth+=o;r.height=Math.max(r.height,r.prevHeight+c)}else{r.currentWidth=o;r.prevHeight=r.height;r.height+=c;r.attempt=0}r.width=Math.max(r.width,r.currentWidth);break;case"rl-row":case"row":{r.children.push(t);r.width+=o;r.height=Math.max(r.height,c);const e=measureToString(r.height);for(const t of r.children)t.attributes.style.height=e;break}case"table":case"tb":r.width=MathClamp(o,r.width,i.width);r.height+=c;r.children.push(t)}}function getAvailableSpace(e){const t=e[Jn].availableSpace,a=e.margin?e.margin.topInset+e.margin.bottomInset:0,r=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Jn].attempt?{width:t.width-r-e[Jn].currentWidth,height:t.height-a-e[Jn].prevHeight}:{width:t.width-r,height:t.height-a-e[Jn].height};case"rl-row":case"row":return{width:Math.sumPrecise(e[Jn].columnWidths.slice(e[Jn].currentColumn)),height:t.height-r};case"table":case"tb":return{width:t.width-r,height:t.height-a-e[Jn].height};default:return t}}function checkDimensions(e,t){if(null===e[fs]()[Jn].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const a=e[us](),r=a[Jn]?.attempt||0,[,i,n,s]=function getTransformedBBox(e){let t,a,r=""===e.w?NaN:e.w,i=""===e.h?NaN:e.h,[n,s]=[0,0];switch(e.anchorType||""){case"bottomCenter":[n,s]=[r/2,i];break;case"bottomLeft":[n,s]=[0,i];break;case"bottomRight":[n,s]=[r,i];break;case"middleCenter":[n,s]=[r/2,i/2];break;case"middleLeft":[n,s]=[0,i/2];break;case"middleRight":[n,s]=[r,i/2];break;case"topCenter":[n,s]=[r/2,0];break;case"topRight":[n,s]=[r,0]}switch(e.rotate||0){case 0:[t,a]=[-n,-s];break;case 90:[t,a]=[-s,n];[r,i]=[i,-r];break;case 180:[t,a]=[n,s];[r,i]=[-r,-i];break;case 270:[t,a]=[s,-n];[r,i]=[-i,r]}return[e.x+t+Math.min(0,r),e.y+a+Math.min(0,i),Math.abs(r),Math.abs(i)]}(e);switch(a.layout){case"lr-tb":case"rl-tb":return 0===r?e[fs]()[Jn].noLayoutFailure?""!==e.w?Math.round(n-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(s-t.height)>2)&&(""!==e.w?Math.round(n-t.width)<=2||0===a[Jn].numberInLine&&t.height>2:t.width>2):!!e[fs]()[Jn].noLayoutFailure||!(""!==e.h&&Math.round(s-t.height)>2)&&((""===e.w||Math.round(n-t.width)<=2||!a[vs]())&&t.height>2);case"table":case"tb":return!!e[fs]()[Jn].noLayoutFailure||(""===e.h||e[Cs]()?(""===e.w||Math.round(n-t.width)<=2||!a[vs]())&&t.height>2:Math.round(s-t.height)<=2);case"position":if(e[fs]()[Jn].noLayoutFailure)return!0;if(""===e.h||Math.round(s+i-t.height)<=2)return!0;return s+i>e[fs]()[Jn].currentContentArea.h;case"rl-row":case"row":return!!e[fs]()[Jn].noLayoutFailure||(""===e.h||Math.round(s-t.height)<=2);default:return!0}}const No=eo.template.id,Po="http://www.w3.org/2000/svg",Eo=/^H(\d+)$/,Lo=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),_o=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ss]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[jn](t);e.value=t}e.value[zs](t)}function*getContainedChildren(e){for(const t of e[cs]())t instanceof SubformSet?yield*t[ls]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[$s]=e[ds]()[$s];return}if(e[$s])return;let t=null;for(const a of e.traversal[cs]())if("next"===a.operation){t=a;break}if(!t||!t.ref){e[$s]=e[ds]()[$s];return}const a=e[fs]();e[$s]=++a[$s];const r=a[qs](t.ref,e);if(!r)return;e=r[0]}}function applyAssist(e,t){const a=e.assist;if(a){const e=a[Ks]();e&&(t.title=e);const r=a.role.match(Eo);if(r){const e="heading",a=r[1];t.role=e;t["aria-level"]=a}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const a=e[ds]();"row"===a.layout&&(t.role="TH"===a.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[Gn]?t.speak[Gn]:t.toolTip?t.toolTip[Gn]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[fs]();if(null===t[Jn].firstUnsplittable){t[Jn].firstUnsplittable=e;t[Jn].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[fs]();t[Jn].firstUnsplittable===e&&(t[Jn].noLayoutFailure=!1)}function handleBreak(e){if(e[Jn])return!1;e[Jn]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[fs]();let a=null;if(e.target){a=t[qs](e.target,e[ds]());if(!a)return!1;a=a[0]}const{currentPageArea:r,currentContentArea:i}=t[Jn];if("pageArea"===e.targetType){a instanceof PageArea||(a=null);if(e.startNew){e[Jn].target=a||r;return!0}if(a&&a!==r){e[Jn].target=a;return!0}return!1}a instanceof ContentArea||(a=null);const n=a&&a[ds]();let s,o=n;if(e.startNew)if(a){const e=n.contentArea.children,t=e.indexOf(i),r=e.indexOf(a);-1!==t&&te;r[Jn].noLayoutFailure=!0;const s=t[Ks](a);e[Un](s.html,s.bbox);r[Jn].noLayoutFailure=i;t[us]=n}class AppearanceFilter extends StringObject{constructor(e){super(No,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(No,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[Ks](){const e=this.edge||new Edge({}),t=e[Ys](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ys]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;let r;const i={xmlns:Po,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)r={name:"ellipse",attributes:{xmlns:Po,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:a}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,n=this.sweepAngle>180?1:0,[s,o,c,l]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];r={name:"path",attributes:{xmlns:Po,d:`M ${s} ${o} A 50 50 0 ${n} 0 ${c} ${l}`,vectorEffect:"non-scaling-stroke",style:a}};Object.assign(i,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const n={name:"svg",children:[r],attributes:i};if(hasMargin(this[ds]()[ds]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[n]});n.attributes.style.position="absolute";return HTMLResult.success(n)}}class Area extends XFAObject{constructor(e){super(No,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[ls](){yield*getContainedChildren(this)}[Fs](){return!0}[xs](){return!0}[Un](e,t){const[a,r,i,n]=t;this[Jn].width=Math.max(this[Jn].width,a+i);this[Jn].height=Math.max(this[Jn].height,r+n);this[Jn].children.push(e)}[ts](){return this[Jn].availableSpace}[Ks](e){const t=toStyle(this,"position"),a={style:t,id:this[Zs],class:["xfaArea"]};isPrintOnly(this)&&a.class.push("xfaPrintOnly");this.name&&(a.xfaName=this.name);const r=[];this[Jn]={children:r,width:0,height:0,availableSpace:e};const i=this[Xn]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!i.success){if(i.isBreak())return i;delete this[Jn];return HTMLResult.FAILURE}t.width=measureToString(this[Jn].width);t.height=measureToString(this[Jn].height);const n={name:"div",attributes:a,children:r},s=[this.x,this.y,this[Jn].width,this[Jn].height];delete this[Jn];return HTMLResult.success(n,s)}}class Assist extends XFAObject{constructor(e){super(No,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[Ks](){return this.toolTip?.[Gn]||null}}class Barcode extends XFAObject{constructor(e){super(No,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(No,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(No,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(No,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(No,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Ks](e){return valueToHtml(1===this[Gn]?"1":"0")}}class Border extends XFAObject{constructor(e){super(No,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ss](){if(!this[Jn]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let a=e.length;a<4;a++)e.push(t)}const t=e.map(e=>e.thickness),a=[0,0,0,0];if(this.margin){a[0]=this.margin.topInset;a[1]=this.margin.rightInset;a[2]=this.margin.bottomInset;a[3]=this.margin.leftInset}this[Jn]={widths:t,insets:a,edges:e}}return this[Jn]}[Ys](){const{edges:e}=this[ss](),t=e.map(e=>{const t=e[Ys]();t.color||="#000000";return t}),a=Object.create(null);this.margin&&Object.assign(a,this.margin[Ys]());"visible"===this.fill?.presence&&Object.assign(a,this.fill[Ys]());if(this.corner.children.some(e=>0!==e.radius)){const e=this.corner.children.map(e=>e[Ys]());if(2===e.length||3===e.length){const t=e.at(-1);for(let a=e.length;a<4;a++)e.push(t)}a.borderRadius=e.map(e=>e.radius).join(" ")}switch(this.presence){case"invisible":case"hidden":a.borderStyle="";break;case"inactive":a.borderStyle="none";break;default:a.borderStyle=t.map(e=>e.style).join(" ")}a.borderWidth=t.map(e=>e.width).join(" ");a.borderColor=t.map(e=>e.color).join(" ");return a}}class Break extends XFAObject{constructor(e){super(No,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(No,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(No,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[Ks](e){this[Jn]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(No,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ks](e){const t=this[ds]()[ds](),a={name:"button",attributes:{id:this[Zs],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[Gn]);if(!t)continue;const r=fixURL(t.url);r&&a.children.push({name:"a",attributes:{id:"link"+this[Zs],href:r,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(a)}}class Calculate extends XFAObject{constructor(e){super(No,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(No,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[zs](e){_setValue(this,e)}[ss](e){if(!this[Jn]){let{width:t,height:a}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":a=this.reserve<=0?a:this.reserve}this[Jn]=layoutNode(this,{width:t,height:a})}return this[Jn]}[Ks](e){if(!this.value)return HTMLResult.EMPTY;this[_s]();const t=this.value[Ks](e).html;if(!t){this[Ls]();return HTMLResult.EMPTY}const a=this.reserve;if(this.reserve<=0){const{w:t,h:a}=this[ss](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=a}}const r=[];"string"==typeof t?r.push({name:"#text",value:t}):r.push(t);const i=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(i.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(i.height=measureToString(this.reserve))}setPara(this,null,t);this[Ls]();this.reserve=a;return HTMLResult.success({name:"div",attributes:{style:i,class:["xfaCaption"]},children:r})}}class Certificate extends StringObject{constructor(e){super(No,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(No,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(No,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"margin"),a=measureToString(this.size);t.width=t.height=a;let r,i,n;const s=this[ds]()[ds](),o=s.items.children.length&&s.items.children[0][Ks]().html||[],c={on:(void 0!==o[0]?o[0]:"on").toString(),off:(void 0!==o[1]?o[1]:"off").toString()},l=(s.value?.[Gs]()||"off")===c.on||void 0,h=s[us](),u=s[Zs];let d;if(h instanceof ExclGroup){n=h[Zs];r="radio";i="xfaRadio";d=h[Vn]?.[Zs]||h[Zs]}else{r="checkbox";i="xfaCheckbox";d=s[Vn]?.[Zs]||s[Zs]}const f={name:"input",attributes:{class:[i],style:t,fieldId:u,dataId:d,type:r,checked:l,xfaOn:c.on,xfaOff:c.off,"aria-label":ariaLabel(s),"aria-required":!1}};n&&(f.attributes.name=n);if(isRequired(s)){f.attributes["aria-required"]=!0;f.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[f]})}}class ChoiceList extends XFAObject{constructor(e){super(No,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","margin"),a=this[ds]()[ds](),r={fontSize:`calc(${a.font?.size||10}px * var(--total-scale-factor))`},i=[];if(a.items.children.length>0){const e=a.items;let t=0,n=0;if(2===e.children.length){t=e.children[0].save;n=1-t}const s=e.children[t][Ks]().html,o=e.children[n][Ks]().html;let c=!1;const l=a.value?.[Gs]()||"";for(let e=0,t=s.length;eMathClamp(parseInt(e.trim(),10),0,255)).map(e=>isNaN(e)?0:e);if(n.length<3)return{r:a,g:r,b:i};[a,r,i]=n;return{r:a,g:r,b:i}}(e.value):"";this.extras=null}[ps](){return!1}[Ys](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(No,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(No,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(No,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[Ks](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},a=["xfaContentarea"];isPrintOnly(this)&&a.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:a,id:this[Zs]}})}}class Corner extends XFAObject{constructor(e){super(No,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(No,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=this[Gn].trim();this[Gn]=e?new Date(e):null}[Ks](e){return valueToHtml(this[Gn]?this[Gn].toString():"")}}class DateTime extends ContentObject{constructor(e){super(No,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=this[Gn].trim();this[Gn]=e?new Date(e):null}[Ks](e){return valueToHtml(this[Gn]?this[Gn].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(No,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","font","margin"),a=this[ds]()[ds](),r={name:"input",attributes:{type:"text",fieldId:a[Zs],dataId:a[Vn]?.[Zs]||a[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Decimal extends ContentObject{constructor(e){super(No,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=parseFloat(this[Gn].trim());this[Gn]=isNaN(e)?null:e}[Ks](e){return valueToHtml(null!==this[Gn]?this[Gn].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(No,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(No,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(No,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(No,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(No,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[zs](e){_setValue(this,e)}[Ks](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[_s]();const t=this.w,a=this.h,{w:r,h:i,isBroken:n}=layoutNode(this,e);if(r&&""===this.w){if(n&&this[us]()[vs]()){this[Ls]();return HTMLResult.FAILURE}this.w=r}i&&""===this.h&&(this.h=i);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=a;this[Ls]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const s=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,s);if(s.margin){s.padding=s.margin;delete s.margin}const o=["xfaDraw"];this.font&&o.push("xfaFont");isPrintOnly(this)&&o.push("xfaPrintOnly");const c={style:s,id:this[Zs],class:o};this.name&&(c.xfaName=this.name);const l={name:"div",attributes:c,children:[]};applyAssist(this,c);const h=computeBbox(this,l,e),u=this.value?this.value[Ks](e).html:null;if(null===u){this.w=t;this.h=a;this[Ls]();return HTMLResult.success(createWrapper(this,l),h)}l.children.push(u);setPara(this,s,u);this.w=t;this.h=a;this[Ls]();return HTMLResult.success(createWrapper(this,l),h)}}class Edge extends XFAObject{constructor(e){super(No,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Ys]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(No,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(No,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(No,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(No,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(No,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(No,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(No,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(No,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(No,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ws](){return"text/html"===this.contentType}[Rs](e){if("text/html"===this.contentType&&e[Os]===eo.xhtml.id){this[Gn]=e;return!0}if("text/xml"===this.contentType){this[Gn]=e;return!0}return!1}[Ks](e){return"text/html"===this.contentType&&this[Gn]?this[Gn][Ks](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(No,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(No,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[xs](){return!0}[ps](){return!0}[zs](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[jn](e);t.value=e}t.value[zs](e)}}[vs](){return this.layout.endsWith("-tb")&&0===this[Jn].attempt&&this[Jn].numberInLine>0||this[ds]()[vs]()}[Cs](){const e=this[us]();if(!e[Cs]())return!1;if(void 0!==this[Jn]._isSplittable)return this[Jn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Jn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Jn].numberInLine)return!1;this[Jn]._isSplittable=!0;return!0}[Zn](){return flushHTML(this)}[Un](e,t){addHTML(this,e,t)}[ts](){return getAvailableSpace(this)}[Ks](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Zs],class:[]};setAccess(this,a.class);this[Jn]||=Object.create(null);Object.assign(this[Jn],{children:t,attributes:a,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[Cs]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const i=new Set(["field"]);if(this.layout.includes("row")){const e=this[us]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Jn].columnWidths=e;this[Jn].currentColumn=0}}const n=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),s=["xfaExclgroup"],o=layoutClass(this);o&&s.push(o);isPrintOnly(this)&&s.push("xfaPrintOnly");a.style=n;a.class=s;this.name&&(a.xfaName=this.name);this[_s]();const c="lr-tb"===this.layout||"rl-tb"===this.layout,l=c?2:1;for(;this[Jn].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[xs](){return!0}[zs](e){_setValue(this,e)}[Ks](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[gs]=this[gs];this[jn](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[jn](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Jn];this[_s]();const t=this.caption?this.caption[Ks](e).html:null,a=this.w,r=this.h;let i=0,n=0;if(this.margin){i=this.margin.leftInset+this.margin.rightInset;n=this.margin.topInset+this.margin.bottomInset}let s=null;if(""===this.w||""===this.h){let t=null,a=null,r=0,o=0;if(this.ui.checkButton)r=o=this.ui.checkButton.size;else{const{w:t,h:a}=layoutNode(this,e);if(null!==t){r=t;o=a}else o=function fonts_getMetrics(e,t=!1){let a=null;if(e){const t=stripQuotes(e.typeface),r=e[gs].fontFinder.find(t);a=selectFont(e,r)}if(!a)return{lineHeight:12,lineGap:2,lineNoGap:10};const r=e.size||10,i=a.lineHeight?Math.max(t?0:1.2,a.lineHeight):1.2,n=void 0===a.lineGap?.2:a.lineGap;return{lineHeight:i*r,lineGap:n*r,lineNoGap:Math.max(1,i-n)*r}}(this.font,!0).lineNoGap}s=getBorderDims(this.ui[ss]());r+=s.w;o+=s.h;if(this.caption){const{w:i,h:n,isBroken:s}=this.caption[ss](e);if(s&&this[us]()[vs]()){this[Ls]();return HTMLResult.FAILURE}t=i;a=n;switch(this.caption.placement){case"left":case"right":case"inline":t+=r;break;case"top":case"bottom":a+=o}}else{t=r;a=o}if(t&&""===this.w){t+=i;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(No,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=parseFloat(this[Gn].trim());this[Gn]=isNaN(e)?null:e}[Ks](e){return valueToHtml(null!==this[Gn]?this[Gn].toString():"")}}class template_Font extends XFAObject{constructor(e){super(No,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[qn](e){super[qn](e);this[gs].usedTypefaces.add(this.typeface)}[Ys](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[gs].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(No,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(No,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(No,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(No,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[Ks](){if(this.contentType&&!Lo.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[gs].images?.get(this.href);if(!e&&(this.href||!this[Gn]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[Gn]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,a]of _o)if(e.length>t.length&&t.every((t,a)=>t===e[a])){this.contentType=a;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let a;switch(this.aspect){case"fit":case"actual":break;case"height":a={height:"100%",objectFit:"fill"};break;case"none":a={width:"100%",height:"100%",objectFit:"fill"};break;case"width":a={width:"100%",objectFit:"fill"}}const r=this[ds]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:a,src:URL.createObjectURL(t),alt:r?ariaLabel(r[ds]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(No,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ks](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(No,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=parseInt(this[Gn].trim(),10);this[Gn]=isNaN(e)?null:e}[Ks](e){return valueToHtml(null!==this[Gn]?this[Gn].toString():"")}}class Issuers extends XFAObject{constructor(e){super(No,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(No,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Ks](){const e=[];for(const t of this[cs]())e.push(t[Gs]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(No,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(No,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(No,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[Ks](){const e=this[ds]()[ds](),t=this.edge||new Edge({}),a=t[Ys](),r=Object.create(null),i="visible"===t.presence?t.thickness:0;r.strokeWidth=measureToString(i);r.stroke=a.color;let n,s,o,c,l="100%",h="100%";if(e.w<=i){[n,s,o,c]=["50%",0,"50%","100%"];l=r.strokeWidth}else if(e.h<=i){[n,s,o,c]=[0,"50%","100%","50%"];h=r.strokeWidth}else"\\"===this.slope?[n,s,o,c]=[0,0,"100%","100%"]:[n,s,o,c]=[0,"100%","100%",0];const u={name:"svg",children:[{name:"line",attributes:{xmlns:Po,x1:n,y1:s,x2:o,y2:c,style:r}}],attributes:{xmlns:Po,width:l,height:h,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[u]});u.attributes.style.position="absolute";return HTMLResult.success(u)}}class Linear extends XFAObject{constructor(e){super(No,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){e=e?e[Ys]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Ys]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(No,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){this[Gn]=getStringOption(this[Gn],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(No,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(No,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(No,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(No,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const a=e.split(",",4).map(e=>getMeasurement(e.trim(),"-1"));if(a.length<4||a[2]<0||a[3]<0)return{x:t,y:t,width:t,height:t};const[r,i,n,s]=a;return{x:r,y:i,width:n,height:s}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(No,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(No,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","font","margin"),a=this[ds]()[ds](),r={name:"input",attributes:{type:"text",fieldId:a[Zs],dataId:a[Vn]?.[Zs]||a[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Occur extends XFAObject{constructor(e){super(No,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:-1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[qn](){const e=this[ds](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[Is](){if(!this[Jn]){this[Jn]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Jn].numberOfUsee.oddOrEven===t&&e.pagePosition===a);if(r)return r;r=this.pageArea.children.find(e=>"any"===e.oddOrEven&&e.pagePosition===a);if(r)return r;r=this.pageArea.children.find(e=>"any"===e.oddOrEven&&"any"===e.pagePosition);return r||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(No,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map((e,t)=>t%2==1?getMeasurement(e):e);this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Ys](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Ys]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(No,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(No,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){e=e?e[Ys]():"#FFFFFF";const t=this.color?this.color[Ys]():"#000000",a="repeating-linear-gradient",r=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${a}(to top,${r}) ${a}(to right,${r})`;case"crossDiagonal":return`${a}(45deg,${r}) ${a}(-45deg,${r})`;case"diagonalLeft":return`${a}(45deg,${r})`;case"diagonalRight":return`${a}(-45deg,${r})`;case"horizontal":return`${a}(to top,${r})`;case"vertical":return`${a}(to right,${r})`}return""}}class Picture extends StringObject{constructor(e){super(No,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(No,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(No,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){e=e?e[Ys]():"#FFFFFF";const t=this.color?this.color[Ys]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(No,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(No,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(No,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[Ks](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Ys](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ys]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;const r=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Ys](),i={name:"svg",children:[{name:"rect",attributes:{xmlns:Po,width:"100%",height:"100%",x:0,y:0,rx:r.radius,ry:r.radius,style:a}}],attributes:{xmlns:Po,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[ds]()[ds]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[i]});i.attributes.style.position="absolute";return HTMLResult.success(i)}}class RefElement extends StringObject{constructor(e){super(No,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(No,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(No,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(No,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(No,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(No,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(No,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](e){return e?e[Ys]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(No,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(No,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(No,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map(e=>"-1"===e?-1:getMeasurement(e));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[us](){const e=this[ds]();return e instanceof SubformSet?e[us]():e}[xs](){return!0}[vs](){return this.layout.endsWith("-tb")&&0===this[Jn].attempt&&this[Jn].numberInLine>0||this[ds]()[vs]()}*[ls](){yield*getContainedChildren(this)}[Zn](){return flushHTML(this)}[Un](e,t){addHTML(this,e,t)}[ts](){return getAvailableSpace(this)}[Cs](){const e=this[us]();if(!e[Cs]())return!1;if(void 0!==this[Jn]._isSplittable)return this[Jn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Jn]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Jn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Jn].numberInLine)return!1;this[Jn]._isSplittable=!0;return!0}[Ks](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[gs]=this[gs];this[jn](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[gs]=this[gs];this[jn](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[gs]=this[gs];this[jn](e);this.overflow.push(e)}this[Us](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Jn]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Zs],class:[]};setAccess(this,a.class);this[Jn]||=Object.create(null);Object.assign(this[Jn],{children:t,line:null,attributes:a,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[fs](),i=r[Jn].noLayoutFailure,n=this[Cs]();n||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[us]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Jn].columnWidths=e;this[Jn].currentColumn=0}}const o=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),c=["xfaSubform"],l=layoutClass(this);l&&c.push(l);a.style=o;a.class=c;this.name&&(a.xfaName=this.name);if(this.overflow){const t=this.overflow[ss]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[_s]();const h="lr-tb"===this.layout||"rl-tb"===this.layout,u=h?2:1;for(;this[Jn].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Jn].afterBreakAfter=y;return HTMLResult.breakNode(e)}}delete this[Jn];return y}}class SubformSet extends XFAObject{constructor(e){super(No,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[ls](){yield*getContainedChildren(this)}[us](){let e=this[ds]();for(;!(e instanceof Subform);)e=e[ds]();return e}[xs](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(No,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){this[Gn]=new Map(this[Gn].split(this.delimiter).map(e=>{(e=e.split("=",2))[0]=e[0].trim();return e}))}}class SubjectDNs extends XFAObject{constructor(e){super(No,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(No,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(No,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Yn](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[$s]=5e3}[Cs](){return!0}[qs](e,t){return e.startsWith("#")?[this[ms].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Vs](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Jn]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[Hn]();const t=e.pageSet.pageArea.children,a={name:"div",children:[]};let r=null,i=null,n=null;if(e.breakBefore.children.length>=1){i=e.breakBefore.children[0];n=i.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){i=e.subform.children[0].breakBefore.children[0];n=i.target}else if(e.break?.beforeTarget){i=e.break;n=i.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){i=e.subform.children[0].break;n=i.beforeTarget}if(i){const e=this[qs](n,i[ds]());if(e instanceof PageArea){r=e;i[Jn]={}}}r||=t[0];r[Jn]={numberOfUse:1};const s=r[ds]();s[Jn]={numberOfUse:1,pageIndex:s.pageArea.children.indexOf(r),pageSetIndex:0};let o,c=null,l=null,h=!0,u=0,d=0;for(;;){if(h)u=0;else{a.children.pop();if(3===++u){warn("XFA - Something goes wrong: please file a bug.");return a}}o=null;this[Jn].currentPageArea=r;const t=r[Ks]().html;a.children.push(t);if(c){this[Jn].noLayoutFailure=!0;t.children.push(c[Ks](r[Jn].space).html);c=null}if(l){this[Jn].noLayoutFailure=!0;t.children.push(l[Ks](r[Jn].space).html);l=null}const i=r.contentArea.children,n=t.children.filter(e=>e.attributes.class.includes("xfaContentarea"));h=!1;this[Jn].firstUnsplittable=null;this[Jn].noLayoutFailure=!1;const flush=t=>{const a=e[Zn]();if(a){h||=a.children?.length>0;n[t].children.push(a)}};for(let t=d,r=i.length;t0;n[t].children.push(u.html)}else!h&&a.children.length>1&&a.children.pop();return a}if(u.isBreak()){const e=u.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){c=this[qs](e.leader,e[ds]());c=c?c[0]:null}if(e.trailer){l=this[qs](e.trailer,e[ds]());l=l?l[0]:null}if("pageArea"===e.targetType){o=e[Jn].target;t=1/0}else if(e[Jn].target){o=e[Jn].target;d=e[Jn].index+1;t=1/0}else t=e[Jn].index;continue}if(this[Jn].overflowNode){const e=this[Jn].overflowNode;this[Jn].overflowNode=null;const a=e[ss](),r=a.target;a.addLeader=null!==a.leader;a.addTrailer=null!==a.trailer;flush(t);const n=t;t=1/0;if(r instanceof PageArea)o=r;else if(r instanceof ContentArea){const e=i.indexOf(r);if(-1!==e)e>n?t=e-1:d=e;else{o=r[ds]();d=o.contentArea.children.indexOf(r)}}continue}flush(t)}this[Jn].pageNumber+=1;o&&(o[Is]()?o[Jn].numberOfUse+=1:o=null);r=o||r[hs]();yield null}}}class Text extends ContentObject{constructor(e){super(No,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[_n](){return!0}[Rs](e){if(e[Os]===eo.xhtml.id){this[Gn]=e;return!0}warn(`XFA - Invalid content in Text: ${e[Ds]}.`);return!1}[Ns](e){this[Gn]instanceof XFAObject||super[Ns](e)}[Yn](){"string"==typeof this[Gn]&&(this[Gn]=this[Gn].replaceAll("\r\n","\n"))}[ss](){return"string"==typeof this[Gn]?this[Gn].split(/[\u2029\u2028\n]/).filter(e=>!!e).join("\n"):this[Gn][Gs]()}[Ks](e){if("string"==typeof this[Gn]){const e=valueToHtml(this[Gn]).html;if(this[Gn].includes("\u2029")){e.name="div";e.children=[];this[Gn].split("\u2029").map(e=>e.split(/[\u2028\n]/).flatMap(e=>[{name:"span",value:e},{name:"br"}])).forEach(t=>{e.children.push({name:"p",children:t})})}else if(/[\u2028\n]/.test(this[Gn])){e.name="div";e.children=[];this[Gn].split(/[\u2028\n]/).forEach(t=>{e.children.push({name:"span",value:t},{name:"br"})})}return HTMLResult.success(e)}return this[Gn][Ks](e)}}class TextEdit extends XFAObject{constructor(e){super(No,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","font","margin");let a;const r=this[ds]()[ds]();""===this.multiLine&&(this.multiLine=r instanceof Draw?1:0);a=1===this.multiLine?{name:"textarea",attributes:{dataId:r[Vn]?.[Zs]||r[Zs],fieldId:r[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:r[Vn]?.[Zs]||r[Zs],fieldId:r[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}};if(isRequired(r)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Time extends StringObject{constructor(e){super(No,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=this[Gn].trim();this[Gn]=e?new Date(e):null}[Ks](e){return valueToHtml(this[Gn]?this[Gn].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(No,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(No,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(No,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(No,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Fs](){return!1}}class Ui extends XFAObject{constructor(e){super(No,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ss](){if(void 0===this[Jn]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Jn]=t;return t}}this[Jn]=null}return this[Jn]}[Ks](e){const t=this[ss]();return t?t[Ks](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(No,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(No,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[zs](e){const t=this[ds]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[jn](this.image)}this.image[Gn]=e[Gn];return}const a=e[Ds];if(null===this[a]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Us](t)}}this[e[Ds]]=e;this[jn](e)}else this[a][Gn]=e[Gn]}[Gs](){if(this.exData)return"string"==typeof this.exData[Gn]?this.exData[Gn].trim():this.exData[Gn][Gs]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[Gn]||"").toString().trim()}return null}[Ks](e){for(const t of Object.getOwnPropertyNames(this)){const a=this[t];if(a instanceof XFAObject)return a[Ks](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(No,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Fs](){return!0}}class TemplateNamespace{static[Qs](e,t){if(TemplateNamespace.hasOwnProperty(e)){const a=TemplateNamespace[e](t);a[Ws](t);return a}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Uo=eo.datasets.id;function createText(e){const t=new Text({});t[Gn]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(eo.datasets.id,"data");this.emptyMerge=0===this.data[cs]().length;this.root.form=this.form=e.template[zn]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,a){e[Vn]=t;if(e[ps]())if(t[Ss]()){const a=t[ns]();e[zs](createText(a))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const a=t[cs]().map(e=>e[Gn].trim()).join("\n");e[zs](createText(a))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[Ss]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,a,r){if(!e)return null;let i,n;for(let r=0;r<3;r++){i=a[os](e,!1,!0);for(;;){n=i.next().value;if(!n)break;if(t===n[Ss]())return n}if(a[Os]===eo.datasets.id&&"data"===a[Ds])break;a=a[ds]()}if(!r)return null;i=this.data[os](e,!0,!1);n=i.next().value;if(n)return n;i=this.data[Qn](e,!0);n=i.next().value;return n?.[Ss]()?n:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:a,target:r,connection:i}of e.setProperty.children){if(i)continue;if(!a)continue;const n=searchNode(this.root,t,a,!1,!1);if(!n){warn(`XFA - Invalid reference: ${a}.`);continue}const[s]=n;if(!s[As](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const o=searchNode(this.root,e,r,!1,!1);if(!o){warn(`XFA - Invalid target: ${r}.`);continue}const[c]=o;if(!c[As](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const l=c[ds]();if(c instanceof SetProperty||l instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(c instanceof BindItems||l instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const h=s[Gs](),u=c[Ds];if(c instanceof XFAAttribute){const e=Object.create(null);e[u]=h;const t=Reflect.construct(Object.getPrototypeOf(l).constructor,[e]);l[u]=t[u];continue}if(c.hasOwnProperty(Gn)){c[Vn]=s;c[Gn]=h;c[Yn]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Us](t);e.items.clear();const a=new Items({}),r=new Items({});e[jn](a);e.items.push(a);e[jn](r);e.items.push(r);for(const{ref:i,labelRef:n,valueRef:s,connection:o}of e.bindItems.children){if(o)continue;if(!i)continue;const e=searchNode(this.root,t,i,!1,!1);if(e)for(const t of e){if(!t[As](this.datasets)){warn(`XFA - Invalid ref (${i}): must be a datasets child.`);continue}const e=searchNode(this.root,t,n,!0,!1);if(!e){warn(`XFA - Invalid label: ${n}.`);continue}const[o]=e;if(!o[As](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const c=searchNode(this.root,t,s,!0,!1);if(!c){warn(`XFA - Invalid value: ${s}.`);continue}const[l]=c;if(!l[As](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const h=createText(o[Gs]()),u=createText(l[Gs]());a[jn](h);a.text.push(h);r[jn](u);r.text.push(u)}else warn(`XFA - Invalid reference: ${i}.`)}}_bindOccurrences(e,t,a){let r;if(t.length>1){r=e[zn]();r[Us](r.occur);r.occur=null}this._bindValue(e,t[0],a);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const i=e[ds](),n=e[Ds],s=i[bs](e);for(let e=1,o=t.length;et.name===e.name).length:a[r].children.length;const n=a[bs](e)+1,s=t.initial-i;if(s){const t=e[zn]();t[Us](t.occur);t.occur=null;a[r].push(t);a[ys](n,t);for(let e=1;e0)this._bindOccurrences(r,[e[0]],null);else if(this.emptyMerge){const e=t[Os]===Uo?-1:t[Os],a=r[Vn]=new XmlObject(e,r.name||"root");t[jn](a);this._bindElement(r,a)}continue}if(!r[xs]())continue;let e=!1,i=null,n=null,s=null;if(r.bind){switch(r.bind.match){case"none":this._setAndBind(r,t);continue;case"global":e=!0;break;case"dataRef":if(!r.bind.ref){warn(`XFA - ref is empty in node ${r[Ds]}.`);this._setAndBind(r,t);continue}n=r.bind.ref}r.bind.picture&&(i=r.bind.picture[Gn])}const[o,c]=this._getOccurInfo(r);if(n){s=searchNode(this.root,t,n,!0,!1);if(null===s){s=createDataNode(this.data,t,n);if(!s)continue;this._isConsumeData()&&(s[$n]=!0);this._setAndBind(r,s);continue}this._isConsumeData()&&(s=s.filter(e=>!e[$n]));s.length>c?s=s.slice(0,c):0===s.length&&(s=null);s&&this._isConsumeData()&&s.forEach(e=>{e[$n]=!0})}else{if(!r.name){this._setAndBind(r,t);continue}if(this._isConsumeData()){const a=[];for(;a.length0?a:null}else{s=t[os](r.name,!1,this.emptyMerge).next().value;if(!s){if(0===o){a.push(r);continue}const e=t[Os]===Uo?-1:t[Os];s=r[Vn]=new XmlObject(e,r.name);this.emptyMerge&&(s[$n]=!0);t[jn](s);this._setAndBind(r,s);continue}this.emptyMerge&&(s[$n]=!0);s=[s]}}s?this._bindOccurrences(r,s,i):o>0?this._setAndBind(r,t):a.push(r)}a.forEach(e=>e[ds]()[Us](e))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[cs]()]];for(;t.length>0;){const a=t.at(-1),[r,i]=a;if(r+1===i.length){t.pop();continue}const n=i[++a[0]],s=e.get(n[Zs]);if(s)n[zs](s);else{const t=n[es]();for(const a of t.values()){const t=e.get(a[Zs]);if(t){a[zs](t);break}}}const o=n[cs]();o.length>0&&t.push([-1,o])}const a=[''];if(this.dataset)for(const e of this.dataset[cs]())"data"!==e[Ds]&&e[Js](a);this.data[Js](a);a.push("");return a.join("")}}const jo=eo.config.id;class Acrobat extends XFAObject{constructor(e){super(jo,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(jo,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(jo,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(jo,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(jo,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(jo,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(jo,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(jo,"adobeExtensionLevel",0,e=>e>=1&&e<=8)}}class Agent extends XFAObject{constructor(e){super(jo,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(jo,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(jo,"amd")}}class config_Area extends XFAObject{constructor(e){super(jo,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(jo,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(jo,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(jo,"base")}}class BatchOutput extends XFAObject{constructor(e){super(jo,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(jo,"behaviorOverride")}[Yn](){this[Gn]=new Map(this[Gn].trim().split(/\s+/).filter(e=>e.includes(":")).map(e=>e.split(":",2)))}}class Cache extends XFAObject{constructor(e){super(jo,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(jo,"change")}}class Common extends XFAObject{constructor(e){super(jo,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(jo,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(jo,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(jo,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(jo,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(jo,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(jo,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(jo,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(jo,"copies",1,e=>e>=1)}}class Creator extends StringObject{constructor(e){super(jo,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(jo,"currentPage",0,e=>e>=0)}}class Data extends XFAObject{constructor(e){super(jo,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(jo,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(jo,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(jo,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(jo,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(jo,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(jo,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(jo,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(jo,"embed")}}class config_Encrypt extends Option01{constructor(e){super(jo,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(jo,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(jo,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(jo,"enforce")}}class Equate extends XFAObject{constructor(e){super(jo,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(jo,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,a=this._unicodeRange;for(let r of a.split(",").map(e=>e.trim()).filter(e=>!!e)){r=r.split("-",2).map(e=>{const a=e.match(t);return a?parseInt(a[1],16):0});1===r.length&&r.push(r[0]);e.push(r)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(jo,"exclude")}[Yn](){this[Gn]=this[Gn].trim().split(/\s+/).filter(e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e))}}class ExcludeNS extends StringObject{constructor(e){super(jo,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(jo,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(jo,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(jo,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(jo,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(jo,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(jo,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(jo,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(jo,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(jo,"interactive")}}class Jog extends OptionObject{constructor(e){super(jo,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(jo,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(jo,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(jo,"level",0,e=>e>0)}}class Linearized extends Option01{constructor(e){super(jo,"linearized")}}class Locale extends StringObject{constructor(e){super(jo,"locale")}}class LocaleSet extends StringObject{constructor(e){super(jo,"localeSet")}}class Log extends XFAObject{constructor(e){super(jo,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(jo,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(jo,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(jo,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(jo,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(jo,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(jo,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(jo,"msgId",1,e=>e>=1)}}class NameAttr extends StringObject{constructor(e){super(jo,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(jo,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(jo,"numberOfCopies",null,e=>e>=2&&e<=5)}}class OpenAction extends XFAObject{constructor(e){super(jo,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(jo,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(jo,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(jo,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(jo,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(jo,"packets")}[Yn](){"*"!==this[Gn]&&(this[Gn]=this[Gn].trim().split(/\s+/).filter(e=>["config","datasets","template","xfdf","xslt"].includes(e)))}}class PageOffset extends XFAObject{constructor(e){super(jo,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(jo,"pageRange")}[Yn](){const e=this[Gn].trim().split(/\s+/).map(e=>parseInt(e,10)),t=[];for(let a=0,r=e.length;a!1)}}class Pcl extends XFAObject{constructor(e){super(jo,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(jo,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(jo,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(jo,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(jo,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(jo,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(jo,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(jo,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(jo,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(jo,"print")}}class PrintHighQuality extends Option01{constructor(e){super(jo,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(jo,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(jo,"printerName")}}class Producer extends StringObject{constructor(e){super(jo,"producer")}}class Ps extends XFAObject{constructor(e){super(jo,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(jo,"range")}[Yn](){this[Gn]=this[Gn].split(",",2).map(e=>e.split("-").map(e=>parseInt(e.trim(),10))).filter(e=>e.every(e=>!isNaN(e))).map(e=>{1===e.length&&e.push(e[0]);return e})}}class Record extends ContentObject{constructor(e){super(jo,"record")}[Yn](){this[Gn]=this[Gn].trim();const e=parseInt(this[Gn],10);!isNaN(e)&&e>=0&&(this[Gn]=e)}}class Relevant extends ContentObject{constructor(e){super(jo,"relevant")}[Yn](){this[Gn]=this[Gn].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(jo,"rename")}[Yn](){this[Gn]=this[Gn].trim();(this[Gn].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[Gn]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(jo,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(jo,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(jo,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(jo,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(jo,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(jo,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(jo,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(jo,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(jo,"startPage",0,e=>!0)}}class SubmitFormat extends OptionObject{constructor(e){super(jo,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(jo,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(jo,"subsetBelow",100,e=>e>=0&&e<=100)}}class SuppressBanner extends Option01{constructor(e){super(jo,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(jo,"tagged")}}class config_Template extends XFAObject{constructor(e){super(jo,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(jo,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(jo,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(jo,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(jo,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(jo,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(jo,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(jo,"uri")}}class config_Validate extends OptionObject{constructor(e){super(jo,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(jo,"validateApprovalSignatures")}[Yn](){this[Gn]=this[Gn].trim().split(/\s+/).filter(e=>["docReady","postSign"].includes(e))}}class ValidationMessaging extends OptionObject{constructor(e){super(jo,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(jo,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(jo,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(jo,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(jo,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(jo,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(jo,"window")}[Yn](){const e=this[Gn].split(",",2).map(e=>parseInt(e.trim(),10));if(e.some(e=>isNaN(e)))this[Gn]=[0,0];else{1===e.length&&e.push(e[0]);this[Gn]=e}}}class Xdc extends XFAObject{constructor(e){super(jo,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(jo,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(jo,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(jo,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[Qs](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Xo=eo.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Xo,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Xo,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Xo,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Xo,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Xo,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Xo,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Xo,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Xo,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Xo,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Xo,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Xo,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Xo,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[Qs](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const qo=eo.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(qo,"data",e)}[ks](){return!0}}class Datasets extends XFAObject{constructor(e){super(qo,"datasets",!0);this.data=null;this.Signature=null}[Rs](e){const t=e[Ds];("data"===t&&e[Os]===qo||"Signature"===t&&e[Os]===eo.signature.id)&&(this[t]=e);this[jn](e)}}class DatasetsNamespace{static[Qs](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const Ho=eo.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(Ho,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(Ho,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(Ho,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(Ho,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(Ho,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(Ho,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(Ho,"day")}}class DayNames extends XFAObject{constructor(e){super(Ho,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(Ho,"era")}}class EraNames extends XFAObject{constructor(e){super(Ho,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(Ho,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(Ho,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(Ho,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(Ho,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(Ho,"month")}}class MonthNames extends XFAObject{constructor(e){super(Ho,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(Ho,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(Ho,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(Ho,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(Ho,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(Ho,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(Ho,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(Ho,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(Ho,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[Qs](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Wo=eo.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Wo,"signature",!0)}}class SignatureNamespace{static[Qs](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const zo=eo.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(zo,"stylesheet",!0)}}class StylesheetNamespace{static[Qs](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const $o=eo.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super($o,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Bs](e){const t=eo[e[Ds]];return t&&e[Os]===t.id}}class XdpNamespace{static[Qs](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const Go=eo.xhtml.id,Vo=Symbol(),Ko=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),Jo=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,parseInt(e)/100).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,parseInt(e)/100).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Yo=/\s+/g,Zo=/[\r\n]+/g,Qo=/\r\n?/g;function mapStyle(e,t,a){const r=Object.create(null);if(!e)return r;const i=Object.create(null);for(const[t,a]of e.split(";").map(e=>e.split(":",2))){const e=Jo.get(t);if(""===e)continue;let n=a;e&&(n="string"==typeof e?e:e(a,i));t.endsWith("scale")?r.transform=r.transform?`${r[t]} ${n}`:n:r[t.replaceAll(/-([a-zA-Z])/g,(e,t)=>t.toUpperCase())]=n}r.fontFamily&&setFontFamily({typeface:r.fontFamily,weight:r.fontWeight||"normal",posture:r.fontStyle||"normal",size:i.fontSize||0},t,t[gs].fontFinder,r);if(a&&r.verticalAlign&&"0px"!==r.verticalAlign&&r.fontSize){const e=.583,t=.333,a=getMeasurement(r.fontSize);r.fontSize=measureToString(a*e);r.verticalAlign=measureToString(Math.sign(getMeasurement(r.verticalAlign))*a*t)}a&&r.fontSize&&(r.fontSize=`calc(${r.fontSize} * var(--total-scale-factor))`);fixTextIndent(r);return r}const ec=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(Go,t);this[Vo]=!1;this.style=e.style||""}[qn](e){super[qn](e);this.style=function checkStyle(e){return e.style?e.style.split(";").filter(e=>!!e.trim()).map(e=>e.split(":",2).map(e=>e.trim())).filter(([t,a])=>{"font-family"===t&&e[gs].usedTypefaces.add(a);return Ko.has(t)}).map(e=>e.join(":")).join(";"):""}(this)}[_n](){return!ec.has(this[Ds])}[Ns](e,t=!1){if(t)this[Vo]=!0;else{e=e.replaceAll(Zo,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Yo," "))}e&&(this[Gn]+=e)}[Es](e,t=!0){const a=Object.create(null),r={top:NaN,bottom:NaN,left:NaN,right:NaN};let i=null;for(const[e,t]of this.style.split(";").map(e=>e.split(":",2)))switch(e){case"font-family":a.typeface=stripQuotes(t);break;case"font-size":a.size=getMeasurement(t);break;case"font-weight":a.weight=t;break;case"font-style":a.posture=t;break;case"letter-spacing":a.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map(e=>getMeasurement(e));switch(e.length){case 1:r.top=r.bottom=r.left=r.right=e[0];break;case 2:r.top=r.bottom=e[0];r.left=r.right=e[1];break;case 3:r.top=e[0];r.bottom=e[2];r.left=r.right=e[1];break;case 4:r.top=e[0];r.left=e[1];r.bottom=e[2];r.right=e[3]}break;case"margin-top":r.top=getMeasurement(t);break;case"margin-bottom":r.bottom=getMeasurement(t);break;case"margin-left":r.left=getMeasurement(t);break;case"margin-right":r.right=getMeasurement(t);break;case"line-height":i=getMeasurement(t)}e.pushData(a,r,i);if(this[Gn])e.addString(this[Gn]);else for(const t of this[cs]())"#text"!==t[Ds]?t[Es](e):e.addString(t[Gn]);t&&e.popFont()}[Ks](e){const t=[];this[Jn]={children:t};this[Xn]({});if(0===t.length&&!this[Gn])return HTMLResult.EMPTY;let a;a=this[Vo]?this[Gn]?this[Gn].replaceAll(Qo,"\n"):void 0:this[Gn]||void 0;return HTMLResult.success({name:this[Ds],attributes:{href:this.href,style:mapStyle(this.style,this,this[Vo])},children:t,value:a})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Es](e){e.pushFont({weight:"bold"});super[Es](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[Ks](e){const t=super[Ks](e),{html:a}=t;if(!a)return HTMLResult.EMPTY;a.name="div";a.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[Gs](){return"\n"}[Es](e){e.addString("\n")}[Ks](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[Ks](e){const t=[];this[Jn]={children:t};this[Xn]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[Gn]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Es](e){e.pushFont({posture:"italic"});super[Es](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Es](e){super[Es](e,!1);e.addString("\n");e.addPara();e.popFont()}[Gs](){return this[ds]()[cs]().at(-1)===this?super[Gs]():super[Gs]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[Qs](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const tc={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[Qs](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[ms]=e}[Rs](e){this.element=e;return!0}[Yn](){super[Yn]();if(this.element.template instanceof Template){this[ms].set(js,this.element);this.element.template[Xs](this[ms]);this.element.template[ms]=this[ms]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Rs](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(eo).map(({id:e})=>e));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:a,namespace:r,prefixes:i}){const n=null!==r;if(n){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(r)}i&&this._addNamespacePrefix(i);if(a.hasOwnProperty(Ms)){const e=tc.datasets,t=a[Ms];let r=null;for(const[a,i]of Object.entries(t)){if(this._getNamespaceToUse(a)===e){r={xfa:i};break}}r?a[Ms]=r:delete a[Ms]}const s=this._getNamespaceToUse(e),o=s?.[Qs](t,a)||new Empty;o[ks]()&&this._nsAgnosticLevel++;(n||i||o[ks]())&&(o[Wn]={hasNamespace:n,prefixes:i,nsAgnostic:o[ks]()});return o}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[a,{check:r}]of Object.entries(eo))if(r(e)){t=tc[a];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:a}of e){const e=this._searchNamespace(a);let r=this._namespacePrefixes.get(t);if(!r){r=[];this._namespacePrefixes.set(t,r)}r.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:a,nsAgnostic:r}=e;t&&(this._currentNamespace=this._namespaceStack.pop());a&&a.forEach(({prefix:e})=>{this._namespacePrefixes.get(e).pop()});r&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=vn;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===vn){this._current[Yn]();return this._current.element}}onText(e){e=e.replace(this._nbsps,e=>e.slice(1)+" ");this._richText||this._current[_n]()?this._current[Ns](e,this._richText):this._whiteRegex.test(e)||this._current[Ns](e.trim())}onCdata(e){this._current[Ns](e)}_mkAttributes(e,t){let a=null,r=null;const i=Object.create({});for(const{name:n,value:s}of e)if("xmlns"===n)a?warn(`XFA - multiple namespace definition in <${t}>`):a=s;else if(n.startsWith("xmlns:")){const e=n.substring(6);r??=[];r.push({prefix:e,value:s})}else{const e=n.indexOf(":");if(-1===e)i[n]=s;else{const t=i[Ms]??=Object.create(null),[a,r]=[n.slice(0,e),n.slice(e+1)];(t[a]||=Object.create(null))[r]=s}}return[a,r,i]}_getNameAndPrefix(e,t){const a=e.indexOf(":");return-1===a?[e,null]:[e.substring(a+1),t?"":e.substring(0,a)]}onBeginElement(e,t,a){const[r,i,n]=this._mkAttributes(t,e),[s,o]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),c=this._builder.build({nsPrefix:o,name:s,attributes:n,namespace:r,prefixes:i});c[gs]=this._globalData;if(a){c[Yn]();this._current[Rs](c)&&c[Hs](this._ids);c[qn](this._builder)}else{this._stack.push(this._current);this._current=c}}onEndElement(e){const t=this._current;if(t[ws]()&&"string"==typeof t[Gn]){const e=new XFAParser;e._globalData=this._globalData;const a=e.parse(t[Gn]);t[Gn]=null;t[Rs](a)}t[Yn]();this._current=this._stack.pop();this._current[Rs](t)&&t[Hs](this._ids);t[qn](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[gs].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return!(!this.root||!this.form)}_createPagesHelper(){const e=this.form[Vs]();return new Promise((t,a)=>{const nextIteration=()=>{try{const a=e.next();a.done?t(a.value):setTimeout(nextIteration,0)}catch(e){a(e)}};setTimeout(nextIteration,0)})}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map(e=>{const{width:t,height:a}=e.attributes.style;return[0,0,parseInt(t),parseInt(a)]})}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[gs].images=e}setFonts(e){this.form[gs].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[gs].usedTypefaces){e=stripQuotes(e);this.form[gs].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[gs].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[Ds])){const e=XhtmlNamespace.body({});e[jn](t);t=e}const a=t[Ks]();if(!a.success)return null;const{html:r}=a,{attributes:i}=r;if(i){i.class&&(i.class=i.class.filter(e=>!e.startsWith("xfa")));i.dir="auto"}return{html:r,str:t[Gs]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments"),e.ensureCatalog("globalColorSpaceCache")]).then(([t,a,r,i,n,s])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:a,structTreeRoot:r,baseUrl:i,attachments:n,globalColorSpaceCache:s}),e=>{warn(`createGlobals: "${e}".`);return null})}static async create(e,t,a,r,i,n,s,o){const c=i?await this._getPageIndex(e,t,a.pdfManager):null;return a.pdfManager.ensure(this,"_create",[e,t,a,r,i,n,s,c,o])}static _create(e,t,a,r,i=!1,n=null,s=null,o=null,c=null){const l=e.fetchIfRef(t);if(!(l instanceof Dict))return;let h=l.get("Subtype");h=h instanceof Name?h.name:null;if(s&&!s.has(D[h.toUpperCase()]))return null;const{acroForm:u,pdfManager:d}=a,f=t instanceof Ref?t.toString():`annot_${r.createObjId()}`,g={xref:e,ref:t,dict:l,subtype:h,id:f,annotationGlobals:a,collectFields:i,orphanFields:n,needAppearances:!i&&!0===u.get("NeedAppearances"),pageIndex:o,evaluatorOptions:d.evaluatorOptions,pageRef:c};switch(h){case"Link":return new LinkAnnotation(g);case"Text":return new TextAnnotation(g);case"Widget":let e=getInheritableProperty({dict:l,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(g);case"Btn":return new ButtonWidgetAnnotation(g);case"Ch":return new ChoiceWidgetAnnotation(g);case"Sig":return new SignatureWidgetAnnotation(g)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(g);case"Popup":return new PopupAnnotation(g);case"FreeText":return new FreeTextAnnotation(g);case"Line":return new LineAnnotation(g);case"Square":return new SquareAnnotation(g);case"Circle":return new CircleAnnotation(g);case"PolyLine":return new PolylineAnnotation(g);case"Polygon":return new PolygonAnnotation(g);case"Caret":return new CaretAnnotation(g);case"Ink":return new InkAnnotation(g);case"Highlight":return new HighlightAnnotation(g);case"Underline":return new UnderlineAnnotation(g);case"Squiggly":return new SquigglyAnnotation(g);case"StrikeOut":return new StrikeOutAnnotation(g);case"Stamp":return new StampAnnotation(g);case"FileAttachment":return new FileAttachmentAnnotation(g);default:i||warn(h?`Unimplemented annotation type "${h}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(g)}}static async _getPageIndex(e,t,a){try{const r=await e.fetchIfRefAsync(t);if(!(r instanceof Dict))return-1;const i=r.getRaw("P");if(i instanceof Ref)try{return await a.ensureCatalog("getPageIndex",[i])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(r.has("Kids"))return-1;const n=await a.ensureDoc("numPages");for(let e=0;ee/255)||t}function getQuadPoints(e,t){const a=e.getArray("QuadPoints");if(!isNumberArray(a,null)||0===a.length||a.length%8>0)return null;const r=new Float32Array(a.length);for(let e=0,i=a.length;et[2]||gt[3]))return null;r.set([d,p,f,p,d,g,f,g],e)}return r}function getTransformMatrix(e,t,a){const r=new Float32Array([1/0,1/0,-1/0,-1/0]);Util.axialAlignedBoundingBox(t,a,r);const[i,n,s,o]=r;if(i===s||n===o)return[1,0,0,1,e[0],e[1]];const c=(e[2]-e[0])/(s-i),l=(e[3]-e[1])/(o-n);return[c,0,0,l,e[0]-i*c,e[1]-n*l]}class Annotation{constructor(e){const{dict:t,xref:a,annotationGlobals:r,ref:i,orphanFields:n}=e,s=n?.get(i);s&&t.set("Parent",s);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const o=t.get("MK");this.setBorderAndBackgroundColors(o);this.setRotation(o,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const c=!!(this.flags&j),l=!!(this.flags&X);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&_),noHTML:c&&l,isEditable:!1,structParent:-1};if(r.structTreeRoot){let a=t.get("StructParent");this.data.structParent=a=Number.isInteger(a)&&a>=0?a:-1;r.structTreeRoot.addAnnotationIdToPage(e.pageRef,a)}if(e.collectFields){const r=t.get("Kids");if(Array.isArray(r)){const e=[];for(const t of r)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(a,t,ie);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const h=t.get("IT");h instanceof Name&&(this.data.it=h.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:a}=this;if(void 0===e){if(void 0===t)return;return t?a&~L:a&~E|L}if(e){a|=L;return t?a&~U|E:a&~E|U}a&=~(E|U);return t?a&~L:a|L}_isViewable(e){return!this._hasFlag(e,N)&&!this._hasFlag(e,U)}_isPrintable(e){return this._hasFlag(e,L)&&!this._hasFlag(e,E)&&!this._hasFlag(e,N)}mustBeViewed(e,t){const a=e?.get(this.data.id)?.noView;return void 0!==a?!a:this.viewable&&!this._hasFlag(this.flags,E)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:a}=e,r=getInheritableProperty({dict:t,key:"DA"})||a.acroForm.get("DA");this._defaultAppearance="string"==typeof r?r:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&N&&"Annotation"!==this.constructor.name&&(this.flags^=N)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const a=e[t];if(a instanceof Name)switch(a.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=a.name;continue}warn(`Ignoring invalid lineEnding: ${a}`)}}setRotation(e,t){this.rotation=0;let a=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(a)&&0!==a){a%=360;a<0&&(a+=360);a%90==0&&(this.rotation=a)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const a=t.get("N");if(a instanceof BaseStream){this.appearance=a;return}if(!(a instanceof Dict))return;const r=e.get("AS");if(!(r instanceof Name&&a.has(r.name)))return;const i=a.get(r.name);i instanceof BaseStream&&(this.appearance=i)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}async loadResources(e,t){const a=await t.dict.getAsync("Resources");a&&await ObjectLoader.load(a,e,a.xref);return a}async getOperatorList(e,t,a,r){const{hasOwnCanvas:i,id:n,rect:o}=this.data;let c=this.appearance;const l=!!(i&&a&s);if(l&&(0===this.width||0===this.height)){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!l)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,u=await this.loadResources(ga,c),d=lookupRect(h.getArray("BBox"),[0,0,1,1]),f=lookupMatrix(h.getArray("Matrix"),fa),g=getTransformMatrix(o,d,f),p=new OperatorList;let m;this.oc&&(m=await e.parseMarkedContentProps(this.oc,null));void 0!==m&&p.addOp(Ct,["OC",m]);p.addOp(Rt,[n,o,g,f,l]);await e.getOperatorList({stream:c,task:t,resources:u,operatorList:p,fallbackFontDict:this._fallbackFontDict});p.addOp(Bt,[]);void 0!==m&&p.addOp(vt,[]);this.reset();return{opList:p,separateForm:!1,separateCanvas:l}}async save(e,t,a,r){return null}get overlaysTextContent(){return!1}get hasTextContent(){return!1}async extractTextContent(e,t,a){if(!this.appearance)return;const r=await this.loadResources(pa,this.appearance),i=[],n=[];let s=null;const o={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){s||=t.transform.slice(-2);n.push(t.str);if(t.hasEOL){i.push(n.join("").trimEnd());n.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:r,includeMarkedContent:!0,keepWhiteSpace:!0,sink:o,viewBox:a});this.reset();n.length&&i.push(n.join("").trimEnd());if(i.length>1||i[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),a=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(s,t,a);this.data.textContent=i}}_transformPoint(e,t,a){const{rect:r}=this.data;t||=[0,0,1,1];a||=[1,0,0,1,0,0];const i=getTransformMatrix(r,t,a);i[4]-=r[0];i[5]-=r[1];const n=e.slice();Util.applyTransform(n,i);Util.applyTransform(n,a);return n}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let a=e;const r=new RefSet;e.objId&&r.put(e.objId);for(;a.has("Parent");){a=a.get("Parent");if(!(a instanceof Dict)||a.objId&&r.has(a.objId))break;a.objId&&r.put(a.objId);a.has("T")&&t.unshift(stringToPDFString(a.get("T")))}return t.join(".")}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=Q;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const a=(t[2]-t[0])/2,r=(t[3]-t[1])/2;if(a>0&&r>0&&(e>a||e>r)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=Q;break;case"D":this.style=ee;break;case"B":this.style=te;break;case"I":this.style=ae;break;case"U":this.style=re}}setDashArray(e,t=!1){if(Array.isArray(e)){let a=!0,r=!0;for(const t of e){if(!(+t>=0)){a=!1;break}t>0&&(r=!1)}if(0===e.length||a&&!r){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const a=t.get("RT");this.data.replyType=a instanceof Name?a.name:R}let a=null;if(this.data.replyType===M){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;a=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;a=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=a instanceof Ref?a.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:a,fillColor:r,blendMode:i,strokeAlpha:n,fillAlpha:s,pointsCallback:o}){const c=this.data.rect=[1/0,1/0,-1/0,-1/0],l=["q"];t&&l.push(t);a&&l.push(`${a[0]} ${a[1]} ${a[2]} RG`);r&&l.push(`${r[0]} ${r[1]} ${r[2]} rg`);const h=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=h.length;e"string"==typeof e).map(e=>stringToPDFString(e)):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,U)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);return 0===t?fa:getRotationMatrix(t,this.width,this.height)}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const a=0===t||180===t?`0 0 ${this.width} ${this.height} re`:`0 0 ${this.height} ${this.width} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${a} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${a} S `}return r}async getOperatorList(e,t,a,r){if(a&l&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,a,r);const i=await this._getAppearance(e,t,a,r);if(this.appearance&&null===i)return super.getOperatorList(e,t,a,r);const n=new OperatorList;if(!this._defaultAppearance||null===i)return{opList:n,separateForm:!1,separateCanvas:!1};const o=!!(this.data.hasOwnCanvas&&a&s),c=[0,0,this.width,this.height],h=getTransformMatrix(this.data.rect,c,[1,0,0,1,0,0]);let u;this.oc&&(u=await e.parseMarkedContentProps(this.oc,null));void 0!==u&&n.addOp(Ct,["OC",u]);n.addOp(Rt,[this.data.id,this.data.rect,h,this.getRotationMatrix(r),o]);const d=new StringStream(i);await e.getOperatorList({stream:d,task:t,resources:this._fieldResources.mergedResources,operatorList:n});n.addOp(Bt,[]);void 0!==u&&n.addOp(vt,[]);return{opList:n,separateForm:!1,separateCanvas:o}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);t.setIfArray("BC",getPdfColorArray(this.borderColor));t.setIfArray("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,a,r){const{dict:i,ref:n}=function getParentToUpdate(e,t,a){const r=new RefSet,i=e,n={dict:null,ref:null};for(;e instanceof Dict&&!r.has(t);){r.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return n;e=a.fetch(t)}if(e instanceof Dict&&e!==i){n.dict=e;n.ref=t}return n}(e,this.ref,a);if(i){if(!r.has(n)){const e=i.clone();e.set("V",t);r.put(n,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,r){const i=a?.get(this.data.id),n=this._buildFlags(i?.noView,i?.noPrint);let s=i?.value,o=i?.rotation;if(s===this.data.fieldValue||void 0===s){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;s||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(s)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(s,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let l=null;if(!this._needAppearances){l=await this._getAppearance(e,t,c,a);if(null===l&&void 0===n)return}let h=!1;if(l?.needAppearances){h=!0;l=null}const{xref:u}=e,d=u.fetchIfRef(this.ref);if(!(d instanceof Dict))return;const f=new Dict(u);for(const e of d.getKeys())"AP"!==e&&f.set(e,d.getRaw(e));if(void 0!==n){f.set("F",n);if(null===l&&!h){const e=d.getRaw("AP");e&&f.set("AP",e)}}const g={path:this.data.fieldName,value:s},p=this.setValue(f,Array.isArray(s)?s.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(s),u,r);this.amendSavedDict(a,p||f);const m=this._getMKDict(o);m&&f.set("MK",m);r.put(this.ref,{data:f,xfa:g,needAppearances:h});if(null!==l){const e=u.getNewTemporaryRef(),t=new Dict(u);f.set("AP",t);t.set("N",e);const i=this._getSaveFieldResources(u),n=new StringStream(l),s=n.dict=new Dict(u);s.setIfName("Subtype","Form");s.set("Resources",i);const c=o%180==0?[0,0,this.width,this.height]:[0,0,this.height,this.width];s.set("BBox",c);const h=this.getRotationMatrix(a);h!==fa&&s.set("Matrix",h);r.put(e,{data:n,xfa:null,needAppearances:!1})}f.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,a,r){if(this.data.password)return null;const n=r?.get(this.data.id);let s,o;if(n){s=n.formattedValue||n.value;o=n.rotation}if(void 0===o&&void 0===s&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const l=this.getBorderAndBackgroundAppearances(r);if(void 0===s){s=this.data.fieldValue;if(!s)return`/Tx BMC q ${l}Q EMC`}Array.isArray(s)&&1===s.length&&(s=s[0]);assert("string"==typeof s,"Expected `value` to be a string.");s=s.trimEnd();if(this.data.combo){const e=this.data.options.find(({exportValue:e})=>s===e);s=e?.displayValue||s}if(""===s)return`/Tx BMC q ${l}Q EMC`;void 0===o&&(o=this.rotation);let h,u=-1;if(this.data.multiLine){h=s.split(/\r\n?|\n/).map(e=>e.normalize("NFC"));u=h.length}else h=[s.replace(/\r\n?|\n/,"").normalize("NFC")];let{width:d,height:f}=this;90!==o&&270!==o||([d,f]=[f,d]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let g,p,m,b=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const y=[];let w=!1;for(const e of h){const t=b.encodeString(e);t.length>1&&(w=!0);y.push(t.join(""))}if(w&&a&c)return{needAppearances:!0};if(w&&this._isOffscreenCanvasSupported){const a=this.data.comb?"monospace":"sans-serif",r=new FakeUnicodeFont(e.xref,a),i=r.createFontResources(h.join("")),n=i.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const o=r.fontName.name;b=await WidgetAnnotation._getFontData(e,t,{fontName:o,fontSize:0},i);for(let e=0,t=y.length;e2)return`/Tx BMC q ${l}BT `+g+` 1 0 0 1 ${numberToString(2)} ${numberToString(C)} Tm (${escapeString(y[0])}) Tj ET Q EMC`;return`/Tx BMC q ${l}BT `+g+` 1 0 0 1 0 0 Tm ${this._renderText(y[0],b,p,d,k,{shift:0},2,C)} ET Q EMC`}static async _getFontData(e,t,a,r){const i=new OperatorList,n={font:null,clone(){return this}},{fontName:s,fontSize:o}=a;await e.handleSetFont(r,[s&&Name.get(s),o],null,i,t,n,null);return n.font}_getTextWidth(e,t){return Math.sumPrecise(t.charsToGlyphs(e).map(e=>e.width))/1e3}_computeFontSize(e,t,r,i,n){let{fontSize:s}=this.data.defaultAppearanceData,o=(s||12)*a,c=Math.round(e/o);if(!s){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===n){const n=this._getTextWidth(r,i);s=roundWithTwoDigits(Math.min(e/a,t/n));c=1}else{const l=r.split(/\r\n?|\n/),h=[];for(const e of l){const t=i.encodeString(e).join(""),a=i.charsToGlyphs(t),r=i.getCharPositions(t);h.push({line:t,glyphs:a,positions:r})}const isTooBig=a=>{let r=0;for(const n of h){r+=this._splitLine(null,i,a,t,n).length*a;if(r>e)return!0}return!1};c=Math.max(c,n);for(;;){o=e/c;s=roundWithTwoDigits(o/a);if(!isTooBig(s))break;c++}}const{fontName:l,fontColor:h}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:a}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(a,!0)}`}({fontSize:s,fontName:l,fontColor:h})}return[this._defaultAppearance,s,e/c]}_renderText(e,t,a,r,i,n,s,o){let c;if(1===i){c=(r-this._getTextWidth(e,t)*a)/2}else if(2===i){c=r-this._getTextWidth(e,t)*a-s}else c=s;const l=numberToString(c-n.shift);n.shift=c;return`${l} ${o=numberToString(o)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:a,acroFormResources:r}=this._fieldResources,i=this.data.defaultAppearanceData?.fontName;if(!i)return t||Dict.empty;for(const e of[t,a])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(i))return e}if(r instanceof Dict){const a=r.get("Font");if(a instanceof Dict&&a.has(i)){const r=new Dict(e);r.set(i,a.getRaw(i));const n=new Dict(e);n.set("Font",r);return Dict.merge({xref:e,dictArray:[n,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=E;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let a=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(a)||a<0||a>2)&&(a=null);this.data.textAlignment=a;let r=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(r)||r<0)&&(r=0);this.data.maxLen=r;this.data.multiLine=this.hasFieldFlag(W);this.data.comb=this.hasFieldFlag(Z)&&!this.data.multiLine&&!this.data.password&&!this.hasFieldFlag(K)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(Y);const{data:{actions:i}}=this;if(!i)return;const n=/^AF(Date|Time)_(?:Keystroke|Format)(?:Ex)?\(['"]?([^'"]+)['"]?\);$/;let s=!1;(1===i.Format?.length&&1===i.Keystroke?.length&&n.test(i.Format[0])&&n.test(i.Keystroke[0])||0===i.Format?.length&&1===i.Keystroke?.length&&n.test(i.Keystroke[0])||0===i.Keystroke?.length&&1===i.Format?.length&&n.test(i.Format[0]))&&(s=!0);const o=[];i.Format&&o.push(...i.Format);i.Keystroke&&o.push(...i.Keystroke);if(s){delete i.Keystroke;i.Format=o}for(const e of o){const t=e.match(n);if(!t)continue;const a="Date"===t[1];let r=t[2];const i=parseInt(r,10);isNaN(i)||Math.floor(Math.log10(i))+1!==t[2].length||(r=(a?kn:Cn)[i]??r);this.data.datetimeFormat=r;if(!s)break;if(a){if(/HH|MM|ss|h/.test(r)){this.data.datetimeType="datetime-local";this.data.timeStep=/ss/.test(r)?1:60}else this.data.datetimeType="date";break}this.data.datetimeType="time";this.data.timeStep=/ss/.test(r)?1:60;break}}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,a,r,i,n,s,o,c,l,h){const u=i/this.data.maxLen,d=this.getBorderAndBackgroundAppearances(h),f=[],g=t.getCharPositions(a);for(const[e,t]of g)f.push(`(${escapeString(a.substring(e,t))}) Tj`);const p=f.join(` ${numberToString(u)} 0 Td `);return`/Tx BMC q ${d}BT `+e+` 1 0 0 1 ${numberToString(s)} ${numberToString(o+c)} Tm ${p} ET Q EMC`}_getMultilineAppearance(e,t,a,r,i,n,s,o,c,l,h,u){const d=[],f=i-2*o,g={shift:0};for(let e=0,n=t.length;er){c.push(e.substring(d,a));d=a;f=p;l=-1;u=-1}else{f+=p;l=a;h=i;u=t}else if(f+p>r)if(-1!==l){c.push(e.substring(d,h));d=h;t=u+1;l=-1;f=0}else{c.push(e.substring(d,a));d=a;f=p}else f+=p}dt?`\\${t}`:"\\s+");new RegExp(`^\\s*${n}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.data.password,charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,datetimeFormat:this.data.datetimeFormat,hasDatetimeHTML:!!this.data.datetimeType,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;const t=this.hasFieldFlag($),a=this.hasFieldFlag(G);this.data.checkBox=!t&&!a;this.data.radioButton=t&&!a;this.data.pushButton=a;this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,r){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,r);let i=null,n=null;if(r){const e=r.get(this.data.id);i=e?e.value:null;n=e?e.rotation:null}if(null===i&&this.appearance)return super.getOperatorList(e,t,a,r);null==i&&(i=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const s=i?this.checkedAppearance:this.uncheckedAppearance;if(s){const i=this.appearance,o=lookupMatrix(s.dict.getArray("Matrix"),fa);n&&s.dict.set("Matrix",this.getRotationMatrix(r));this.appearance=s;const c=super.getOperatorList(e,t,a,r);this.appearance=i;s.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,a,r){this.data.checkBox?this._saveCheckbox(e,t,a,r):this.data.radioButton&&this._saveRadioButton(e,t,a,r)}async _saveCheckbox(e,t,a,r){if(!a)return;const i=a.get(this.data.id),n=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,o=i?.value;if(void 0===s&&void 0===n){if(void 0===o)return;if(this.data.fieldValue===this.data.exportValue===o)return}let c=e.xref.fetchIfRef(this.ref);if(!(c instanceof Dict))return;c=c.clone();void 0===s&&(s=this.rotation);void 0===o&&(o=this.data.fieldValue===this.data.exportValue);const l={path:this.data.fieldName,value:o?this.data.exportValue:""},h=Name.get(o?this.data.exportValue:"Off");this.setValue(c,h,e.xref,r);c.set("AS",h);c.set("M",`D:${getModificationDate()}`);void 0!==n&&c.set("F",n);const u=this._getMKDict(s);u&&c.set("MK",u);r.put(this.ref,{data:c,xfa:l,needAppearances:!1})}async _saveRadioButton(e,t,a,r){if(!a)return;const i=a.get(this.data.id),n=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,o=i?.value;if(void 0===s&&void 0===n){if(void 0===o)return;if(this.data.fieldValue===this.data.buttonValue===o)return}let c=e.xref.fetchIfRef(this.ref);if(!(c instanceof Dict))return;c=c.clone();void 0===o&&(o=this.data.fieldValue===this.data.buttonValue);void 0===s&&(s=this.rotation);const l={path:this.data.fieldName,value:o?this.data.buttonValue:""},h=Name.get(o?this.data.buttonValue:"Off");o&&this.setValue(c,h,e.xref,r);c.set("AS",h);c.set("M",`D:${getModificationDate()}`);void 0!==n&&c.set("F",n);const u=this._getMKDict(s);u&&c.set("MK",u);r.put(this.ref,{data:c,xfa:l,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const{width:a,height:r}=this,i=[0,0,a,r],n=.8*Math.min(a,r);let s,o;if("check"===t){s={width:.755*n,height:.705*n};o="3"}else if("disc"===t){s={width:.791*n,height:.705*n};o="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const c=`q BT /PdfJsZaDb ${n} Tf 0 g ${numberToString((a-s.width)/2)} ${numberToString((r-s.height)/2)} Td (${o}) Tj ET Q`,l=new Dict(e.xref);l.set("FormType",1);l.setIfName("Subtype","Form");l.setIfName("Type","XObject");l.set("BBox",i);l.set("Matrix",[1,0,0,1,0,0]);l.set("Length",c.length);const h=new Dict(e.xref),u=new Dict(e.xref);u.set("PdfJsZaDb",this.fallbackFontDict);h.set("Font",u);l.set("Resources",h);this.checkedAppearance=new StringStream(c);this.checkedAppearance.dict=l;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const a=t.get("N");if(!(a instanceof Dict))return;const r=this._decodeFormValue(e.dict.get("AS"));"string"==typeof r&&(this.data.fieldValue=r);const i=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",n=this._decodeFormValue(a.getKeys());if(0===n.length)n.push("Off",i);else if(1===n.length)"Off"===n[0]?n.push(i):n.unshift("Off");else if(n.includes(i)){n.length=0;n.push("Off",i)}else{const e=n.find(e=>"Off"!==e);n.length=0;n.push("Off",e)}n.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=n[1];const s=a.get(this.data.exportValue);this.checkedAppearance=s instanceof BaseStream?s:null;const o=a.get("Off");this.uncheckedAppearance=o instanceof BaseStream?o:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const a=t.get("V");a instanceof Name&&(this.data.fieldValue=this._decodeFormValue(a))}const a=e.dict.get("AP");if(!(a instanceof Dict))return;const r=a.get("N");if(!(r instanceof Dict))return;for(const e of r.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const i=r.get(this.data.buttonValue);this.checkedAppearance=i instanceof BaseStream?i:null;const n=r.get("Off");this.uncheckedAppearance=n instanceof BaseStream?n:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:a}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:a.baseUrl,docAttachments:a.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.setIfName("BaseFont","ZapfDingbats");e.setIfName("Type","FallbackType");e.setIfName("Subtype","FallbackType");e.setIfName("Encoding","ZapfDingbatsEncoding");return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const r=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(r))for(let e=0,t=r.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map(e=>({exportValue:e,displayValue:e})));this.data.combo=this.hasFieldFlag(V);this.data.multiSelect=this.hasFieldFlag(J);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let a=e?.get(this.data.id)?.value;Array.isArray(a)||(a=[a]);const r=[],{options:i}=this.data;for(let e=0,t=0,n=i.length;ea){a=r;t=e}}[f,g]=this._computeFontSize(e,c-4,t,d,-1)}const p=g*a,m=(p-g)/2,b=Math.floor(l/p);let y=0;if(u.length>0){const e=Math.min(...u),t=Math.max(...u);y=Math.max(0,t-b+1);y>e&&(y=e)}const w=Math.min(y+b+1,h),x=["/Tx BMC q",`1 1 ${c} ${l} re W n`];if(u.length){x.push("0.600006 0.756866 0.854904 rg");for(const e of u)y<=e&&ee.trimEnd());const{coords:e,bbox:t,matrix:r}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,r)}if(this._isOffscreenCanvasSupported){const i=e.dict.get("CA"),n=new FakeUnicodeFont(r,"sans-serif");this.appearance=n.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,i);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,date:n,fontSize:s,oldAnnotation:o,rect:c,rotation:l,user:h,value:u}=e,d=o||new Dict(t);d.setIfNotExists("Type",Name.get("Annot"));d.setIfNotExists("Subtype",Name.get("FreeText"));d.set(o?"M":"CreationDate",`D:${getModificationDate(n)}`);o&&d.delete("RC");d.setIfArray("Rect",c);const f=`/Helv ${s} Tf ${getPdfColor(i,!0)}`;d.set("DA",f);d.setIfDefined("Contents",stringToAsciiOrUTF16BE(u));d.setIfNotExists("F",4);d.setIfNotExists("Border",[0,0,0]);d.setIfNumber("Rotate",l);d.setIfDefined("T",stringToAsciiOrUTF16BE(h));if(a||r){const e=new Dict(t);d.set("AP",e);e.set("N",a||r)}return d}static async createNewAppearanceStream(e,t,r){const{baseFontRef:i,evaluator:n,task:s}=r,{color:o,fontSize:c,rect:l,rotation:h,value:u}=e;if(!o)return null;const d=new Dict(t),f=new Dict(t);if(i)f.set("Helv",i);else{const e=new Dict(t);e.setIfName("BaseFont","Helvetica");e.setIfName("Type","Font");e.setIfName("Subtype","Type1");e.setIfName("Encoding","WinAnsiEncoding");f.set("Helv",e)}d.set("Font",f);const g=await WidgetAnnotation._getFontData(n,s,{fontName:"Helv",fontSize:c},d),[p,m,b,y]=l;let w=b-p,x=y-m;h%180!=0&&([w,x]=[x,w]);const S=u.split("\n"),k=c/1e3;let C=-1/0;const v=[];for(let e of S){const t=g.encodeString(e);if(t.length>1)return null;e=t.join("");v.push(e);let a=0;const r=g.charsToGlyphs(e);for(const e of r)a+=e.width*k;C=Math.max(C,a)}let F=1;C>w&&(F=w/C);let T=1;const O=a*c,D=1*c,M=O*S.length;M>x&&(T=x/M);const R=c*Math.min(F,T);let N,E,L;switch(h){case 0:L=[1,0,0,1];E=[l[0],l[1],w,x];N=[l[0],l[3]-D];break;case 90:L=[0,1,-1,0];E=[l[1],-l[2],w,x];N=[l[1],-l[0]-D];break;case 180:L=[-1,0,0,-1];E=[-l[2],-l[3],w,x];N=[-l[2],-l[1]-D];break;case 270:L=[0,-1,1,0];E=[-l[3],l[0],w,x];N=[-l[3],l[2]-D]}const _=["q",`${L.join(" ")} 0 0 cm`,`${E.join(" ")} re W n`,"BT",`${getPdfColor(o,!0)}`,`0 Tc /Helv ${numberToString(R)} Tf`];_.push(`${N.join(" ")} Td (${escapeString(v[0])}) Tj`);const U=numberToString(O);for(let e=1,t=v.length;e{e.push(`${r[0]} ${r[1]} m`,`${r[2]} ${r[3]} l`,"S");return[t[0]-o,t[7]-o,t[2]+o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=D.SQUARE;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA"),i=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),n=i?r:null;if(0===this.borderStyle.width&&!i)return;this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:i,strokeAlpha:r,fillAlpha:n,pointsCallback:(e,t)=>{const a=t[4]+this.borderStyle.width/2,r=t[5]+this.borderStyle.width/2,n=t[6]-t[4]-this.borderStyle.width,s=t[3]-t[7]-this.borderStyle.width;e.push(`${a} ${r} ${n} ${s} re`);i?e.push("B"):e.push("S");return[t[0],t[7],t[2],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=D.CIRCLE;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA"),i=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),n=i?r:null;if(0===this.borderStyle.width&&!i)return;const s=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:i,strokeAlpha:r,fillAlpha:n,pointsCallback:(e,t)=>{const a=t[0]+this.borderStyle.width/2,r=t[1]-this.borderStyle.width/2,n=t[6]-this.borderStyle.width/2,o=t[7]+this.borderStyle.width/2,c=a+(n-a)/2,l=r+(o-r)/2,h=(n-a)/2*s,u=(o-r)/2*s;e.push(`${c} ${o} m`,`${c+h} ${o} ${n} ${l+u} ${n} ${l} c`,`${n} ${l-u} ${c+h} ${r} ${c} ${r} c`,`${c-h} ${r} ${a} ${l-u} ${a} ${l} c`,`${a} ${l+u} ${c-h} ${o} ${c} ${o} c`,"h");i?e.push("B"):e.push("S");return[t[0],t[7],t[2],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=D.POLYLINE;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const r=t.getArray("Vertices");if(!isNumberArray(r,null))return;const i=this.data.vertices=Float32Array.from(r);if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA");let n,s=getRgbColor(t.getArray("IC"),null);s&&(s=getPdfColorArray(s));n=s?this.color?s.every((t,a)=>t===e[a])?"f":"B":"f":"S";const o=this.borderStyle.width||1,c=2*o,l=[1/0,1/0,-1/0,-1/0];for(let e=0,t=i.length;e{for(let t=0,a=i.length;t{for(const t of this.data.inkLists){for(let a=0,r=t.length;a0){const e=new Dict(t);g.set("BS",e);e.set("W",d)}g.setIfArray("C",getPdfColorArray(n));g.setIfNumber("CA",o);if(r||a){const e=new Dict(t);g.set("AP",e);e.set("N",a||r)}return g}static async createNewAppearanceStream(e,t,a){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,a);const{color:r,rect:i,paths:n,thickness:s,opacity:o}=e;if(!r)return null;const c=[`${s} w 1 J 1 j`,`${getPdfColor(r,!1)}`];1!==o&&c.push("/R0 gs");for(const e of n.lines){c.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,a=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,date:n,oldAnnotation:s,opacity:o,rect:c,rotation:l,user:h,quadPoints:u}=e,d=s||new Dict(t);d.setIfNotExists("Type",Name.get("Annot"));d.setIfNotExists("Subtype",Name.get("Highlight"));d.set(s?"M":"CreationDate",`D:${getModificationDate(n)}`);d.setIfArray("Rect",c);d.setIfNotExists("F",4);d.setIfNotExists("Border",[0,0,0]);d.setIfNumber("Rotate",l);d.setIfArray("QuadPoints",u);d.setIfArray("C",getPdfColorArray(i));d.setIfNumber("CA",o);d.setIfDefined("T",stringToAsciiOrUTF16BE(h));if(a||r){const e=new Dict(t);d.set("AP",e);e.set("N",a||r)}return d}static async createNewAppearanceStream(e,t,a){const{color:r,rect:i,outlines:n,opacity:s}=e;if(!r)return null;const o=[`${getPdfColor(r,!0)}`,"/R0 gs"],c=[];for(const e of n){c.length=0;c.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,a=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=D.SQUIGGLY;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA");this._setDefaultAppearance({xref:a,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:r,pointsCallback:(e,t)=>{const a=(t[1]-t[5])/6;let r=a,i=t[4];const n=t[5],s=t[6];e.push(`${i} ${n+r} m`);do{i+=2;r=0===r?a:0;e.push(`${i} ${n+r} l`)}while(i{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class StampAnnotation extends MarkupAnnotation{#Be=null;constructor(e){super(e);this.data.annotationType=D.STAMP;this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!0;this.#Be??=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}if(null!==this.#Be){this.data.hasOwnCanvas=this.#Be;this.#Be=null}return!t?.has(this.data.id)}static async createImage(e,t){const{width:a,height:r}=e,i=new OffscreenCanvas(a,r),n=i.getContext("2d",{alpha:!0});n.drawImage(e,0,0);const s=n.getImageData(0,0,a,r).data,o=new Uint32Array(s.buffer),c=o.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(c){n.fillStyle="white";n.fillRect(0,0,a,r);n.drawImage(e,0,0)}const l=i.convertToBlob({type:"image/jpeg",quality:1}).then(e=>e.arrayBuffer()),h=Name.get("XObject"),u=Name.get("Image"),d=new Dict(t);d.set("Type",h);d.set("Subtype",u);d.set("BitsPerComponent",8);d.setIfName("ColorSpace","DeviceRGB");d.setIfName("Filter","DCTDecode");d.set("BBox",[0,0,a,r]);d.set("Width",a);d.set("Height",r);let f=null;if(c){const e=new Uint8Array(o.length);if(FeatureTest.isLittleEndian)for(let t=0,a=o.length;t>>24;else for(let t=0,a=o.length;t=0&&n<=1?n:null}}const ac={get r(){return shadow(this,"r",new Uint8Array([7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21]))},get k(){return shadow(this,"k",new Int32Array([-680876936,-389564586,606105819,-1044525330,-176418897,1200080426,-1473231341,-45705983,1770035416,-1958414417,-42063,-1990404162,1804603682,-40341101,-1502002290,1236535329,-165796510,-1069501632,643717713,-373897302,-701558691,38016083,-660478335,-405537848,568446438,-1019803690,-187363961,1163531501,-1444681467,-51403784,1735328473,-1926607734,-378558,-2022574463,1839030562,-35309556,-1530992060,1272893353,-155497632,-1094730640,681279174,-358537222,-722521979,76029189,-640364487,-421815835,530742520,-995338651,-198630844,1126891415,-1416354905,-57434055,1700485571,-1894986606,-1051523,-2054922799,1873313359,-30611744,-1560198380,1309151649,-145523070,-1120210379,718787259,-343485551]))}};function calculateMD5(e,t,a){let r=1732584193,i=-271733879,n=-1732584194,s=271733878;const o=a+72&-64,c=new Uint8Array(o);let l,h;for(l=0;l>5&255;c[l++]=a>>13&255;c[l++]=a>>21&255;c[l++]=a>>>29&255;l+=3;const d=new Int32Array(16),{k:f,r:g}=ac;for(l=0;l>>32-n)|0;a=r}r=r+a|0;i=i+o|0;n=n+u|0;s=s+p|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&i,i>>8&255,i>>16&255,i>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&s,s>>8&255,s>>16&255,s>>>24&255])}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const a=t.firstChild;return"value"===a?.nodeName?t.children.map(e=>decodeString(e.textContent)):decodeString(t.textContent)}}class SingleIntersector{#Pe;minX=1/0;minY=1/0;maxX=-1/0;maxY=-1/0;#Ee=null;#Le=[];#_e=[];#Ue=-1;#je=!1;constructor(e){this.#Pe=e;const t=e.data.quadPoints;if(t){for(let e=0,a=t.length;e8&&(this.#Ee=t)}else[this.minX,this.minY,this.maxX,this.maxY]=e.data.rect}#Xe(e,t){if(this.minX>=e||this.maxX<=e||this.minY>=t||this.maxY<=t)return!1;const a=this.#Ee;if(!a)return!0;if(this.#Ue>=0){const r=this.#Ue;if(!(a[r]>=e||a[r+2]<=e||a[r+5]>=t||a[r+1]<=t))return!0;this.#Ue=-1}for(let r=0,i=a.length;r=e||a[r+2]<=e||a[r+5]>=t||a[r+1]<=t)){this.#Ue=r;return!0}return!1}addGlyph(e,t,a){if(!this.#Xe(e,t)){this.disableExtraChars();return!1}if(this.#_e.length>0){this.#Le.push(this.#_e.join(""));this.#_e.length=0}this.#Le.push(a);this.#je=!0;return!0}addExtraChar(e){this.#je&&this.#_e.push(e)}disableExtraChars(){if(this.#je){this.#je=!1;this.#_e.length=0}}setText(){this.#Pe.data.overlaidText=this.#Le.join("")}}const rc=64;class Intersector{#qe=[];#He=[];#We;#ze;#$e;#Ge;#Ve;#Ke;constructor(e){let t=1/0,a=1/0,r=-1/0,i=-1/0;const n=this.#qe;for(const s of e){if(!s.data.quadPoints&&!s.data.rect)continue;const e=new SingleIntersector(s);n.push(e);t=Math.min(t,e.minX);a=Math.min(a,e.minY);r=Math.max(r,e.maxX);i=Math.max(i,e.maxY)}this.#We=t;this.#$e=a;this.#ze=r;this.#Ge=i;this.#Ve=63/(r-t);this.#Ke=63/(i-a);for(const e of n){const t=this.#Je(e.minX,e.minY),a=this.#Je(e.maxX,e.maxY),r=(a-t)%rc,i=Math.floor((a-t)/rc);for(let a=t;a<=t+i*rc;a+=rc)for(let t=0;t<=r;t++){let r=this.#He[a+t];r||(this.#He[a+t]=r=[]);r.push(e)}}}#Je(e,t){return Math.floor((e-this.#We)*this.#Ve)+Math.floor((t-this.#$e)*this.#Ke)*rc}addGlyph(e,t,a,r){const i=e[4]+t/2,n=e[5]+a/2;if(ithis.#ze||n>this.#Ge)return;const s=this.#He[this.#Je(i,n)];if(s)for(const e of s)e.addGlyph(i,n,r)}addExtraChar(e){for(const t of this.#qe)t.addExtraChar(e)}setText(){for(const e of this.#qe)e.setText()}}class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}rotateRight(e){let t,a;if(32&e){a=this.low;t=this.high}else{t=this.low;a=this.high}e&=31;this.low=t>>>e|a<<32-e;this.high=a>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let a=(this.high>>>0)+(e.high>>>0);t>4294967295&&(a+=1);this.low=0|t;this.high=0|a}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const ic={get k(){return shadow(this,"k",[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)])}};function ch(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.not();i.and(r);e.xor(i)}function maj(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.and(r);e.xor(i);i.assign(a);i.and(r);e.xor(i)}function sigma(e,t,a){e.assign(t);e.rotateRight(28);a.assign(t);a.rotateRight(34);e.xor(a);a.assign(t);a.rotateRight(39);e.xor(a)}function sigmaPrime(e,t,a){e.assign(t);e.rotateRight(14);a.assign(t);a.rotateRight(18);e.xor(a);a.assign(t);a.rotateRight(41);e.xor(a)}function littleSigma(e,t,a){e.assign(t);e.rotateRight(1);a.assign(t);a.rotateRight(8);e.xor(a);a.assign(t);a.shiftRight(7);e.xor(a)}function littleSigmaPrime(e,t,a){e.assign(t);e.rotateRight(19);a.assign(t);a.rotateRight(61);e.xor(a);a.assign(t);a.shiftRight(6);e.xor(a)}function calculateSHA512(e,t,a,r=!1){let i,n,s,o,c,l,h,u;if(r){i=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);s=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);l=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);u=new Word64(1203062813,3204075428)}else{i=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);s=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);l=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);u=new Word64(1541459225,327033209)}const d=128*Math.ceil((a+17)/128),f=new Uint8Array(d);let g,p;for(g=0;g>>29&255;f[g++]=a>>21&255;f[g++]=a>>13&255;f[g++]=a>>5&255;f[g++]=a<<3&255;const b=new Array(80);for(g=0;g<80;g++)b[g]=new Word64(0,0);const{k:y}=ic;let w=new Word64(0,0),x=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0),C=new Word64(0,0),v=new Word64(0,0),F=new Word64(0,0),T=new Word64(0,0);const O=new Word64(0,0),D=new Word64(0,0),M=new Word64(0,0),R=new Word64(0,0);let N,E;for(g=0;g>>t|e<<32-t}function calculate_sha256_ch(e,t,a){return e&t^~e&a}function calculate_sha256_maj(e,t,a){return e&t^e&a^t&a}function calculate_sha256_sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function calculate_sha256_sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function calculate_sha256_littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}function calculate_sha256_littleSigmaPrime(e){return rotr(e,17)^rotr(e,19)^e>>>10}function calculateSHA256(e,t,a){let r=1779033703,i=3144134277,n=1013904242,s=2773480762,o=1359893119,c=2600822924,l=528734635,h=1541459225;const u=64*Math.ceil((a+9)/64),d=new Uint8Array(u);let f,g;for(f=0;f>>29&255;d[f++]=a>>21&255;d[f++]=a>>13&255;d[f++]=a>>5&255;d[f++]=a<<3&255;const m=new Uint32Array(64),{k:b}=nc;for(f=0;f>24&255,r>>16&255,r>>8&255,255&r,i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s>>24&255,s>>16&255,s>>8&255,255&s,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,l>>24&255,l>>16&255,l>>8&255,255&l,h>>24&255,h>>16&255,h>>8&255,255&h])}class DecryptStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.dict=e.dict;this.decrypt=a;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.stream.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.stream.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const a=this.bufferLength,r=a+e.length;this.ensureBuffer(r).set(e,a);this.bufferLength=r}getOriginalStream(){return this}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),a=e.length;for(let e=0;e<256;++e)t[e]=e;for(let r=0,i=0;r<256;++r){const n=t[r];i=i+n+e[r%a]&255;t[r]=t[i];t[i]=n}this.s=t}encryptBlock(e){let t=this.a,a=this.b;const r=this.s,i=e.length,n=new Uint8Array(i);for(let s=0;st<128?t<<1:t<<1^27);constructor(){this.buffer=new Uint8Array(16);this.bufferPosition=0}_expandKey(e){unreachable("Cannot call `_expandKey` on the base class")}_decrypt(e,t){let a,r,i;const n=new Uint8Array(16);n.set(e);for(let e=0,a=this._keySize;e<16;++e,++a)n[e]^=t[a];for(let e=this._cyclesOfRepetition-1;e>=1;--e){a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e)n[e]=this._inv_s[n[e]];for(let a=0,r=16*e;a<16;++a,++r)n[a]^=t[r];for(let e=0;e<16;e+=4){const t=this._mix[n[e]],r=this._mix[n[e+1]],i=this._mix[n[e+2]],s=this._mix[n[e+3]];a=t^r>>>8^r<<24^i>>>16^i<<16^s>>>24^s<<8;n[e]=a>>>24&255;n[e+1]=a>>16&255;n[e+2]=a>>8&255;n[e+3]=255&a}}a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e){n[e]=this._inv_s[n[e]];n[e]^=t[e]}return n}_encrypt(e,t){const a=this._s;let r,i,n;const s=new Uint8Array(16);s.set(e);for(let e=0;e<16;++e)s[e]^=t[e];for(let e=1;e=r;--a)if(e[a]!==t){t=0;break}o-=t;n[n.length-1]=e.subarray(0,16-t)}}const c=new Uint8Array(o);for(let e=0,t=0,a=n.length;e=256&&(o=255&(27^o))}for(let t=0;t<4;++t){a[e]=r^=a[e-32];e++;a[e]=i^=a[e-32];e++;a[e]=n^=a[e-32];e++;a[e]=s^=a[e-32];e++}}return a}}class PDFBase{_hash(e,t,a){unreachable("Abstract method `_hash` called")}checkOwnerPassword(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);return isArrayEqual(this._hash(e,i,a),r)}checkUserPassword(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);return isArrayEqual(this._hash(e,r,[]),a)}getOwnerKey(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);const n=this._hash(e,i,a);return new AES256Cipher(n).decryptBlock(r,!1,new Uint8Array(16))}getUserKey(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);const i=this._hash(e,r,[]);return new AES256Cipher(i).decryptBlock(a,!1,new Uint8Array(16))}}class PDF17 extends PDFBase{_hash(e,t,a){return calculateSHA256(t,0,t.length)}}class PDF20 extends PDFBase{_hash(e,t,a){let r=calculateSHA256(t,0,t.length).subarray(0,32),i=[0],n=0;for(;n<64||i.at(-1)>n-32;){const t=e.length+r.length+a.length,s=new Uint8Array(t);let o=0;s.set(e,o);o+=e.length;s.set(r,o);o+=r.length;s.set(a,o);const c=new Uint8Array(64*t);for(let e=0,a=0;e<64;e++,a+=t)c.set(s,a);i=new AES128Cipher(r.subarray(0,16)).encrypt(c,r.subarray(16,32));const l=Math.sumPrecise(i.slice(0,16))%3;0===l?r=calculateSHA256(i,0,i.length):1===l?r=calculateSHA384(i,0,i.length):2===l&&(r=calculateSHA512(i,0,i.length));n++}return r.subarray(0,32)}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const a=new this.StreamCipherConstructor;return new DecryptStream(e,t,function cipherTransformDecryptStream(e,t){return a.decryptBlock(e,t)})}decryptString(e){const t=new this.StringCipherConstructor;let a=stringToBytes(e);a=t.decryptBlock(a,!0);return bytesToString(a)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const a=16-e.length%16;e+=String.fromCharCode(a).repeat(a);const r=new Uint8Array(16);crypto.getRandomValues(r);let i=stringToBytes(e);i=t.encrypt(i,r);const n=new Uint8Array(16+i.length);n.set(r);n.set(i,16);return bytesToString(n)}let a=stringToBytes(e);a=t.encrypt(a);return bytesToString(a)}}class CipherTransformFactory{static get _defaultPasswordBytes(){return shadow(this,"_defaultPasswordBytes",new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]))}#Ye(e,t,a,r,i,n,s,o,c,l,h,u){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const d=6===e?new PDF20:new PDF17;return d.checkUserPassword(t,o,s)?d.getUserKey(t,c,h):t.length&&d.checkOwnerPassword(t,r,n,a)?d.getOwnerKey(t,i,n,l):null}#Ze(e,t,a,r,i,n,s,o){const c=40+a.length+e.length,l=new Uint8Array(c);let h,u,d=0;if(t){u=Math.min(32,t.length);for(;d>8&255;l[d++]=i>>16&255;l[d++]=i>>>24&255;l.set(e,d);d+=e.length;if(n>=4&&!o){l.fill(255,d,d+4);d+=4}let f=calculateMD5(l,0,d);const g=s>>3;if(n>=3)for(h=0;h<50;++h)f=calculateMD5(f,0,g);const p=f.subarray(0,g);let m,b;if(n>=3){d=0;l.set(CipherTransformFactory._defaultPasswordBytes,d);d+=32;l.set(e,d);d+=e.length;m=new ARCFourCipher(p);b=m.encryptBlock(calculateMD5(l,0,d));u=p.length;const t=new Uint8Array(u);for(h=1;h<=19;++h){for(let e=0;er[t]===e)?p:null}#Qe(e,t,a,r){const i=new Uint8Array(32);let n=0;const s=Math.min(32,e.length);for(;n>3;if(a>=3)for(o=0;o<50;++o)c=calculateMD5(c,0,c.length);let h,u;if(a>=3){u=t;const e=new Uint8Array(l);for(o=19;o>=0;o--){for(let t=0;t>8&255;n[s++]=e>>16&255;n[s++]=255&t;n[s++]=t>>8&255;if(r){n[s++]=115;n[s++]=65;n[s++]=108;n[s++]=84}return calculateMD5(n,0,s).subarray(0,Math.min(i+5,16))}#tt(e,t,a,r,i){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const n=this,s=e.get(t.name),o=s?.get("CFM");if(!o||"None"===o.name)return function(){return new NullCipher};if("V2"===o.name)return function(){return new ARCFourCipher(n.#et(a,r,i,!1))};if("AESV2"===o.name)return function(){return new AES128Cipher(n.#et(a,r,i,!0))};if("AESV3"===o.name)return function(){return new AES256Cipher(i)};throw new FormatError("Unknown crypto method")}constructor(e,t,a){const r=e.get("Filter");if(!isName(r,"Standard"))throw new FormatError("unknown encryption method");this.filterName=r.name;this.dict=e;const i=e.get("V");if(!Number.isInteger(i)||1!==i&&2!==i&&4!==i&&5!==i)throw new FormatError("unsupported encryption algorithm");this.algorithm=i;let n=e.get("Length");if(!n)if(i<=3)n=40;else{const t=e.get("CF"),a=e.get("StmF");if(t instanceof Dict&&a instanceof Name){t.suppressEncryption=!0;const e=t.get(a.name);n=e?.get("Length")||128;n<40&&(n<<=3)}}if(!Number.isInteger(n)||n<40||n%8!=0)throw new FormatError("invalid key length");const s=stringToBytes(e.get("O")),o=stringToBytes(e.get("U")),c=s.subarray(0,32),l=o.subarray(0,32),h=e.get("P"),u=e.get("R"),d=(4===i||5===i)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=d;const f=stringToBytes(t);let g,p;if(a){if(6===u)try{a=utf8StringToString(a)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}g=stringToBytes(a)}if(5!==i)p=this.#Ze(f,g,c,l,h,u,n,d);else{const t=s.subarray(32,40),a=s.subarray(40,48),r=o.subarray(0,48),i=o.subarray(32,40),n=o.subarray(40,48),h=stringToBytes(e.get("OE")),d=stringToBytes(e.get("UE")),f=stringToBytes(e.get("Perms"));p=this.#Ye(u,g,c,t,a,r,l,i,n,h,d,f)}if(!p){if(!a)throw new PasswordException("No password given",Yt);const e=this.#Qe(g,c,u,n);p=this.#Ze(f,e,c,l,h,u,n,d)}if(!p)throw new PasswordException("Incorrect Password",Zt);if(4===i&&p.length<16){this.encryptionKey=new Uint8Array(16);this.encryptionKey.set(p)}else this.encryptionKey=p;if(i>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#tt(this.cf,this.strf,e,t,this.encryptionKey),this.#tt(this.cf,this.stmf,e,t,this.encryptionKey));const a=this.#et(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(a)};return new CipherTransform(cipherConstructor,cipherConstructor)}}class XRef{constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[s,o]=n;if(!Number.isInteger(s)||!Number.isInteger(o))throw new FormatError(`Invalid XRef range fields: ${s}, ${o}`);if(!Number.isInteger(a)||!Number.isInteger(r)||!Number.isInteger(i))throw new FormatError(`Invalid XRef entry fields length: ${s}, ${o}`);for(let n=t.entryNum;n=e.length);){a+=String.fromCharCode(r);r=e[t]}return a}function skipUntil(e,t,a){const r=a.length,i=e.length;let n=0;for(;t=r)break;t++;n++}return n}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,a=/^(\d+)\s+(\d+)\s+obj\b/,r=new Uint8Array([116,114,97,105,108,101,114]),i=new Uint8Array([115,116,97,114,116,120,114,101,102]),n=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const s=this.stream;s.pos=0;const o=s.getBytes(),c=bytesToString(o),l=o.length;let h=s.start;const u=[],d=[];for(;h=l)break;f=o[h]}while(10!==f&&13!==f);continue}const g=readToken(o,h);let p;if(g.startsWith("xref")&&(4===g.length||/\s/.test(g[4]))){h+=skipUntil(o,h,r);u.push(h);h+=skipUntil(o,h,i)}else if(p=a.exec(g)){const t=0|p[1],a=0|p[2],r=h+g.length;let i,u=!1;if(this.entries[t]){if(this.entries[t].gen===a)try{new Parser({lexer:new Lexer(s.makeSubStream(r))}).getObj();u=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${g}): "${e}".`):u=!0}}else u=!0;u&&(this.entries[t]={offset:h-s.start,gen:a,uncompressed:!0});e.lastIndex=r;const f=e.exec(c);if(f){i=e.lastIndex+1-h;if("endobj"!==f[1]){warn(`indexObjects: Found "${f[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);i-=f[1].length+1}}else i=l-h;const m=o.subarray(h,h+i),b=skipUntil(m,0,n);if(b0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this.getBoundingBox("MediaBox")||sc)}get cropBox(){return shadow(this,"cropBox",this.getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const a=Util.intersect(e,t);if(a&&a[2]-a[0]>0&&a[3]-a[1]>0)return shadow(this,"view",a);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this.#nt("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}#st(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}async getContentStream(){const e=await this.pdfManager.ensure(this,"content");return e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this.#st.bind(this)):new NullStream}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#ot(e,t,a){const r=[];for(const i of e)if(i.id){const e=Ref.fromString(i.id);if(!e){warn(`A non-linked annotation cannot be modified: ${i.id}`);continue}if(i.deleted){t.put(e,e);if(i.popupRef){const e=Ref.fromString(i.popupRef);e&&t.put(e,e)}continue}if(i.popup?.deleted){const e=Ref.fromString(i.popupRef);e&&t.put(e,e)}a?.put(e);i.ref=e;r.push(this.xref.fetchAsync(e).then(e=>{e instanceof Dict&&(i.oldAnnotation=e.clone())},()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)}));delete i.id}await Promise.all(r)}async saveNewAnnotations(e,t,a,r,i){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const n=this.#it(e),s=new RefSetCache,o=new RefSet;await this.#ot(a,s,o);const c=this.pageDict,l=this.annotations.filter(e=>!(e instanceof Ref&&s.has(e))),h=await AnnotationFactory.saveNewAnnotations(n,t,a,r,i);for(const{ref:e}of h.annotations)e instanceof Ref&&!o.has(e)&&l.push(e);const u=c.clone();u.set("Annots",l);i.put(this.ref,{data:u});for(const e of s)i.put(e,{data:null})}async save(e,t,a,r){const i=this.#it(e),n=await this._parsedAnnotations,s=[];for(const e of n)s.push(e.save(i,t,a,r).catch(function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null}));return Promise.all(s)}async loadResources(e){await(this.#rt??=this.pdfManager.ensure(this,"resources"));await ObjectLoader.load(this.resources,e,this.xref)}async#ct(e,t){const a=e?.get("Resources");if(!(a instanceof Dict&&a.size))return this.resources;await ObjectLoader.load(a,t,this.xref);return Dict.merge({xref:this.xref,dictArray:[a,this.resources],mergeSubDicts:!0})}async getOperatorList({handler:e,sink:t,task:a,intent:r,cacheKey:i,annotationStorage:c=null,modifiedIds:d=null}){const g=this.getContentStream(),p=this.loadResources(ga),m=this.#it(e),b=this.xfaFactory?null:getNewAnnotationsMap(c),y=b?.get(this.pageIndex);let w=Promise.resolve(null),x=null;if(y){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const r=new Set;for(const{bitmapId:e,bitmap:t}of y)!e||t||r.has(e)||r.add(e);const{isOffscreenCanvasSupported:i}=this.evaluatorOptions;if(r.size>0){const e=y.slice();for(const[t,a]of c)t.startsWith(f)&&a.bitmap&&r.has(a.bitmapId)&&e.push(a);t=AnnotationFactory.generateImages(e,this.xref,i)}else t=AnnotationFactory.generateImages(y,this.xref,i);x=new RefSet;w=Promise.all([e,this.#ot(y,x,null)]).then(([e])=>e?AnnotationFactory.printNewAnnotations(e,m,a,y,t):null)}const S=Promise.all([g,p]).then(async([n])=>{const s=await this.#ct(n.dict,ga),o=new OperatorList(r,t);e.send("StartRenderPage",{transparency:m.hasBlendModes(s,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:i});await m.getOperatorList({stream:n,task:a,resources:s,operatorList:o});return o});let[k,C,v]=await Promise.all([S,this._parsedAnnotations,w]);if(v){C=C.filter(e=>!(e.ref&&x.has(e.ref)));for(let e=0,t=v.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace));if(r>=0){C.splice(r,1,a);v.splice(e--,1);t--}}}C=C.concat(v)}if(0===C.length||r&h){k.flush(!0);return{length:k.totalLength}}const F=!!(r&l),T=!!(r&u),O=!!(r&n),D=!!(r&s),M=!!(r&o),R=[];for(const e of C)(O||D&&e.mustBeViewed(c,F)&&e.mustBeViewedWhenEditing(T,d)||M&&e.mustBePrinted(c))&&R.push(e.getOperatorList(m,a,r,c).catch(function(e){warn(`getOperatorList - ignoring annotation data during "${a.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}}));const N=await Promise.all(R);let E=!1,L=!1;for(const{opList:e,separateForm:t,separateCanvas:a}of N){k.addOpList(e);E||=t;L||=a}k.flush(!0,{form:E,canvas:L});return{length:k.totalLength}}async extractTextContent({handler:e,task:t,includeMarkedContent:a,disableNormalization:r,sink:i,intersector:n=null}){const s=this.getContentStream(),o=this.loadResources(pa),c=this.pdfManager.ensureCatalog("lang"),[l,,h]=await Promise.all([s,o,c]),u=await this.#ct(l.dict,pa);return this.#it(e).getTextContent({stream:l,task:t,resources:u,includeMarkedContent:a,disableNormalization:r,sink:i,viewBox:this.view,lang:h,intersector:n})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;try{const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return await this.pdfManager.ensure(t,"serializable")}catch(e){warn(`getStructTree: "${e}".`);return null}}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,a){const r=await this._parsedAnnotations;if(0===r.length)return r;const i=[],c=[];let l;const h=!!(a&n),u=!!(a&s),d=!!(a&o),f=[];for(const a of r){const r=h||u&&a.viewable;(r||d&&a.printable)&&i.push(a.data);if(a.hasTextContent&&r){l??=this.#it(e);c.push(a.extractTextContent(l,t,[-1/0,-1/0,1/0,1/0]).catch(function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)}))}else a.overlaysTextContent&&r&&f.push(a)}if(f.length>0){const a=new Intersector(f);c.push(this.extractTextContent({handler:e,task:t,includeMarkedContent:!1,disableNormalization:!1,sink:null,viewBox:this.view,lang:null,intersector:a}).then(()=>{a.setText()}))}await Promise.all(c);return i}get annotations(){const e=this.#nt("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){const e=this.pdfManager.ensure(this,"annotations").then(async e=>{if(0===e.length)return e;const[t,a]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const r=a?.orphanFields,i=[];for(const a of e)i.push(AnnotationFactory.create(this.xref,a,t,this._localIdFactory,!1,r,null,this.ref).catch(function(e){warn(`_parsedAnnotations: "${e}".`);return null}));const n=[];let s,o;for(const e of await Promise.all(i))e&&(e instanceof WidgetAnnotation?(o||=[]).push(e):e instanceof PopupAnnotation?(s||=[]).push(e):n.push(e));o&&n.push(...o);s&&n.push(...s);return n});this.#at=!0;return shadow(this,"_parsedAnnotations",e)}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,se))}async collectAnnotationsByType(e,t,a,r,i){const{pageIndex:n}=this;if(this.#at){const e=await this._parsedAnnotations;for(const{data:t}of e)if(!a||a.has(t.annotationType)){t.pageIndex=n;r.push(Promise.resolve(t))}return}const s=await this.pdfManager.ensure(this,"annotations");for(const o of s)r.push(AnnotationFactory.create(this.xref,o,i,this._localIdFactory,!1,null,a,this.ref).then(async a=>{if(!a)return null;a.data.pageIndex=n;if(a.hasTextContent&&a.viewable){const r=this.#it(e);await a.extractTextContent(r,t,[-1/0,-1/0,1/0,1/0])}return a.data}).catch(function(e){warn(`collectAnnotationsByType: "${e}".`);return null}))}}const oc=new Uint8Array([37,80,68,70,45]),cc=new Uint8Array([115,116,97,114,116,120,114,101,102]),lc=new Uint8Array([101,110,100,111,98,106]);function find(e,t,a=1024,r=!1){const i=t.length,n=e.peekBytes(a),s=n.length-i;if(s<=0)return!1;if(r){const a=i-1;let r=n.length-1;for(;r>=a;){let s=0;for(;s=i){e.pos+=r-a;return!0}r--}}else{let a=0;for(;a<=s;){let r=0;for(;r=i){e.pos+=a;return!0}a++}}return!1}class PDFDocument{#lt=new Map;#ht=null;constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);const a={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++a.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,lc)){e.skip(6);let a=e.peekByte();for(;isWhiteSpace(a);){e.pos++;a=e.peekByte()}t=e.pos-e.start}}else{const a=1024,r=cc.length;let i=!1,n=e.end;for(;!i&&n>0;){n-=a-r;n<0&&(n=0);e.pos=n;i=find(e,cc,a,!0)}if(i){e.skip(9);let a;do{a=e.getByte()}while(isWhiteSpace(a));let r="";for(;a>=32&&a<=57;){r+=String.fromCharCode(a);a=e.getByte()}t=parseInt(r,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,oc))return;e.moveStart();e.skip(oc.length);let t,a="";for(;(t=e.getByte())>32&&a.length<7;)a+=String.fromCharCode(t);ua.test(a)?this.#ht=a:warn(`Invalid PDF header version: ${a}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}#ut(e,t=0){return!!Array.isArray(e)&&e.every(e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("#hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this.#ut(e.get("Kids"),t)}const a=isName(e.get("FT"),"Sig"),r=e.get("Rect"),i=Array.isArray(r)&&r.every(e=>0===e);return a&&i})}get _xfaStreams(){const{acroForm:e}=this.catalog;if(!e)return null;const t=e.get("XFA"),a=new Map(["xdp:xdp","template","datasets","config","connectionSet","localeSet","stylesheet","/xdp:xdp"].map(e=>[e,null]));if(t instanceof BaseStream&&!t.isEmpty){a.set("xdp:xdp",t);return a}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,r=t.length;el.handleSetFont(r,[Name.get(e),1],null,h,t,d,a,i).catch(e=>{warn(`loadXfaFonts: "${e}".`);return null}),f=[];for(const[e,t]of i){const a=t.get("FontDescriptor");if(!(a instanceof Dict))continue;let r=a.get("FontFamily");r=r.replaceAll(/[ ]+(\d)/g,"$1");const i={fontFamily:r,fontWeight:a.get("FontWeight"),italicAngle:-a.get("ItalicAngle")};validateCSSFont(i)&&f.push(parseFont(e,null,i))}await Promise.all(f);const g=this.xfaFactory.setFonts(u);if(!g)return;n.ignoreErrors=!0;f.length=0;u.length=0;const p=new Set;for(const e of g)getXfaFontName(`${e}-Regular`)||p.add(e);p.size&&g.push("PdfJS-Fallback");for(const e of g)if(!p.has(e))for(const t of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const a=`${e}-${t.name}`;f.push(parseFont(a,getXfaFontDict(a),{fontFamily:e,fontWeight:t.fontWeight,italicAngle:t.italicAngle}))}await Promise.all(f);this.xfaFactory.appendFonts(u,p)}loadXfaResources(e,t){return Promise.all([this.#ft(e,t).catch(()=>{}),this.#dt()])}serializeXfaData(e){return this.xfaFactory?this.xfaFactory.serializeData(e):null}get version(){return this.catalog.version||this.#ht}get formInfo(){const e={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},{acroForm:t}=this.catalog;if(!t)return shadow(this,"formInfo",e);try{const a=t.get("Fields"),r=Array.isArray(a)&&a.length>0;e.hasFields=r;const i=t.get("XFA");e.hasXfa=Array.isArray(i)&&i.length>0||i instanceof BaseStream&&!i.isEmpty;const n=!!(1&t.get("SigFlags")),s=n&&this.#ut(a);e.hasAcroForm=r&&!s;e.hasSignatures=n}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const{catalog:e,formInfo:t,xref:a}=this,r={PDFFormatVersion:this.version,Language:e.lang,EncryptFilterName:a.encrypt?.filterName??null,IsLinearized:!!this.linearization,IsAcroFormPresent:t.hasAcroForm,IsXFAPresent:t.hasXfa,IsCollectionPresent:!!e.collection,IsSignaturesPresent:t.hasSignatures};let i;try{i=a.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(i instanceof Dict))return shadow(this,"documentInfo",r);for(const[e,t]of i){switch(e){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof t){r[e]=stringToPDFString(t);continue}break;case"Trapped":if(t instanceof Name){r[e]=t;continue}break;default:let a;switch(typeof t){case"string":a=stringToPDFString(t);break;case"number":case"boolean":a=t;break;default:t instanceof Name&&(a=t)}if(void 0===a){warn(`Bad value, for custom key "${e}", in Info: ${t}.`);continue}r.Custom??=Object.create(null);r.Custom[e]=a;continue}warn(`Bad value, for key "${e}", in Info: ${t}.`)}return shadow(this,"documentInfo",r)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let a,r;if(Array.isArray(t)&&validate(t[0])){a=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(r=stringToBytes(t[1]))}else a=calculateMD5(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(a),r?toHexUtil(r):null])}async#gt(e){const{catalog:t,linearization:a,xref:r}=this,i=Ref.get(a.objectNumberFirst,0);try{const e=await r.fetchAsync(i);if(e instanceof Dict){let a=e.getRaw("Type");a instanceof Ref&&(a=await r.fetchAsync(a));if(isName(a,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(i)||t.pageKidsCountCache.put(i,1);t.pageIndexCache.has(i)||t.pageIndexCache.put(i,0);return[e,i]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(a){warn(`_getLinearizationPage: "${a.message}".`);return t.getPageDict(e)}}getPage(e){const t=this.#lt.get(e);if(t)return t;const{catalog:a,linearization:r,xfaFactory:i}=this;let n;n=i?Promise.resolve([Dict.empty,null]):r?.pageFirst===e?this.#gt(e):a.getPageDict(e);n=n.then(([t,r])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:r,globalIdFactory:this._globalIdFactory,fontCache:a.fontCache,builtInCMapCache:a.builtInCMapCache,standardFontDataCache:a.standardFontDataCache,globalColorSpaceCache:a.globalColorSpaceCache,globalImageCache:a.globalImageCache,systemFontCache:a.systemFontCache,nonBlendModesSet:a.nonBlendModesSet,xfaFactory:i}));this.#lt.set(e,n);return n}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this.#lt.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:a}=this;t.setActualNumPages();let r;try{await Promise.all([a.ensureDoc("xfaFactory"),a.ensureDoc("linearization"),a.ensureCatalog("numPages")]);if(this.xfaFactory)return;r=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(r))throw new FormatError("Page count is not an integer.");if(r<=1)return;await this.getPage(r-1)}catch(i){this.#lt.delete(r-1);await this.cleanup();if(i instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${r}.`);let n;try{n=await t.getAllPageDicts(e)}catch(a){if(a instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[r,i]]of n){let n;if(r instanceof Error){n=Promise.reject(r);n.catch(()=>{})}else n=Promise.resolve(new Page({pdfManager:a,xref:this.xref,pageIndex:e,pageDict:r,ref:i,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalColorSpaceCache:this.globalColorSpaceCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this.#lt.set(e,n)}t.setActualNumPages(n.size)}}async fontFallback(e,t){const{catalog:a,pdfManager:r}=this;for(const i of await Promise.all(a.fontCache))if(i.loadedName===e){i.fallback(t,r.evaluatorOptions);return}}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#pt(e,t,a,r,i,n,s){const{xref:o}=this;if(!(a instanceof Ref)||n.has(a))return;n.put(a);const c=await o.fetchAsync(a);if(!(c instanceof Dict))return;let l=await c.getAsync("Subtype");l=l instanceof Name?l.name:null;if("Link"===l)return;if(c.has("T")){const t=stringToPDFString(await c.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let a=c;for(;;){a=a.getRaw("Parent")||t;if(a instanceof Ref){if(n.has(a))break;a=await o.fetchAsync(a)}if(!(a instanceof Dict))break;if(a.has("T")){const t=stringToPDFString(await a.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!c.has("Parent")&&isName(c.get("Subtype"),"Widget")&&s.put(a,t);r.has(e)||r.set(e,[]);r.get(e).push(AnnotationFactory.create(o,a,i,null,!0,s,null,null).then(e=>e?.getFieldObject()).catch(function(e){warn(`#collectFieldObjects: "${e}".`);return null}));if(!c.has("Kids"))return;const h=await c.getAsync("Kids");if(Array.isArray(h))for(const t of h)await this.#pt(e,a,t,r,i,n,s)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then(async e=>{if(!e.hasFields)return null;const t=await this.annotationGlobals;if(!t)return null;const{acroForm:a}=t,r=new RefSet,i=Object.create(null),n=new Map,s=new RefSetCache;for(const e of a.get("Fields"))await this.#pt("",null,e,n,t,r,s);const o=[];for(const[e,t]of n)o.push(Promise.all(t).then(t=>{(t=t.filter(e=>!!e)).length>0&&(i[e]=t)}));await Promise.all(o);return{allFields:objectSize(i)>0?i:null,orphanFields:s}}))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t?.allFields&&Object.values(t.allFields).some(e=>e.some(e=>null!==e.actions))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const a of e)a instanceof Ref&&t.push(a.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor({docBaseUrl:e,docId:t,enableXfa:a,evaluatorOptions:r,handler:i,password:n}){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e);this._docId=t;this._password=n;this.enableXfa=a;r.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;r.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(r);ImageResizer.setOptions(r);JpegStream.setOptions(r);OperatorList.setOptions(r);const s={...r,handler:i};JpxImage.setOptions(s);IccColorSpace.setOptions(s);CmykICCBasedCS.setOptions(s)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,a){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,a){const r=e[t];return"function"==typeof r?r.apply(e,a):r}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,a){try{const r=e[t];return"function"==typeof r?r.apply(e,a):r}catch(r){if(!(r instanceof MissingDataException))throw r;await this.requestRange(r.begin,r.end);return this.ensure(e,t,a)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const hc=1,uc=2,dc=1,fc=2,gc=3,pc=4,mc=5,bc=6,yc=7,wc=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof PasswordException||e instanceof ResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"ResponseException":return new ResponseException(e.message,e.status,e.missing);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#mt=new AbortController;constructor(e,t,a){this.sourceName=e;this.targetName=t;this.comObj=a;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);a.addEventListener("message",this.#bt.bind(this),{signal:this.#mt.signal})}#bt({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#yt(e);return}if(e.callback){const t=e.callbackId,a=this.callbackCapabilities[t];if(!a)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===hc)a.resolve(e.data);else{if(e.callback!==uc)throw new Error("Unexpected callback case");a.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const a=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:a,targetName:r,callback:hc,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:a,targetName:r,callback:uc,callbackId:e.callbackId,reason:wrapReason(t)})});return}e.streamId?this.#wt(e):t(e.data)}on(e,t){const a=this.actionHandler;if(a[e])throw new Error(`There is already an actionName called "${e}"`);a[e]=t}send(e,t,a){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},a)}sendWithPromise(e,t,a){const r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},a)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,a,r){const i=this.streamId++,n=this.sourceName,s=this.targetName,o=this.comObj;return new ReadableStream({start:a=>{const c=Promise.withResolvers();this.streamControllers[i]={controller:a,startCall:c,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:n,targetName:s,action:e,streamId:i,data:t,desiredSize:a.desiredSize},r);return c.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[i].pullCall=t;o.postMessage({sourceName:n,targetName:s,stream:bc,streamId:i,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[i].cancelCall=t;this.streamControllers[i].isClosed=!0;o.postMessage({sourceName:n,targetName:s,stream:dc,streamId:i,reason:wrapReason(e)});return t.promise}},a)}#wt(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this,s=this.actionHandler[e.action],o={enqueue(e,n=1,s){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=n;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}i.postMessage({sourceName:a,targetName:r,stream:pc,streamId:t,chunk:e},s)},close(){if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:gc,streamId:t});delete n.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:mc,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[t]=o;Promise.try(s,e.data,o).then(function(){i.postMessage({sourceName:a,targetName:r,stream:wc,streamId:t,success:!0})},function(e){i.postMessage({sourceName:a,targetName:r,stream:wc,streamId:t,reason:wrapReason(e)})})}#yt(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this.streamControllers[t],s=this.streamSinks[t];switch(e.stream){case wc:e.success?n.startCall.resolve():n.startCall.reject(wrapReason(e.reason));break;case yc:e.success?n.pullCall.resolve():n.pullCall.reject(wrapReason(e.reason));break;case bc:if(!s){i.postMessage({sourceName:a,targetName:r,stream:yc,streamId:t,success:!0});break}s.desiredSize<=0&&e.desiredSize>0&&s.sinkCapability.resolve();s.desiredSize=e.desiredSize;Promise.try(s.onPull||onFn).then(function(){i.postMessage({sourceName:a,targetName:r,stream:yc,streamId:t,success:!0})},function(e){i.postMessage({sourceName:a,targetName:r,stream:yc,streamId:t,reason:wrapReason(e)})});break;case pc:assert(n,"enqueue should have stream controller");if(n.isClosed)break;n.controller.enqueue(e.chunk);break;case gc:assert(n,"close should have stream controller");if(n.isClosed)break;n.isClosed=!0;n.controller.close();this.#xt(n,t);break;case mc:assert(n,"error should have stream controller");n.controller.error(wrapReason(e.reason));this.#xt(n,t);break;case fc:e.success?n.cancelCall.resolve():n.cancelCall.reject(wrapReason(e.reason));this.#xt(n,t);break;case dc:if(!s)break;const o=wrapReason(e.reason);Promise.try(s.onCancel||onFn,o).then(function(){i.postMessage({sourceName:a,targetName:r,stream:fc,streamId:t,success:!0})},function(e){i.postMessage({sourceName:a,targetName:r,stream:fc,streamId:t,reason:wrapReason(e)})});s.sinkCapability.reject(o);s.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#xt(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#mt?.abort();this.#mt=null}}async function writeObject(e,t,a,{encrypt:r=null,encryptRef:i=null}){const n=r&&i!==e?r.createCipherTransform(e.num,e.gen):null;a.push(`${e.num} ${e.gen} obj\n`);await writeValue(t,a,n);a.push("\nendobj\n")}async function writeDict(e,t,a){t.push("<<");for(const[r,i]of e.getRawEntries()){t.push(` /${escapePDFName(r)} `);await writeValue(i,t,a)}t.push(">>")}async function writeValue(e,t,a){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await async function writeArray(e,t,a){t.push("[");for(let r=0,i=e.length;r=256&&!o)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(r).then(async()=>{await t.ready;await t.close()}).catch(()=>{});const a=await new Response(e.readable).arrayBuffer();r=new Uint8Array(a);let c,l;if(n){if(!o){c=Array.isArray(n)?[Name.get("FlateDecode"),...n]:[Name.get("FlateDecode"),n];s&&(l=Array.isArray(s)?[null,...s]:[null,s])}}else c=Name.get("FlateDecode");c&&i.set("Filter",c);l&&i.set("DecodeParms",l)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let c=bytesToString(r);a&&(c=a.encryptString(c));i.set("Length",c.length);await writeDict(i,t,a);t.push(" stream\n",c,"\nendstream")}(e,t,a):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,a,r){for(let i=t+a-1;i>a-1;i--){r[i]=255&e;e>>=8}return a+t}function writeString(e,t,a){const r=e.length;for(let i=0;i1&&(n=a.documentElement.searchNode([i.at(-1)],0));n?n.childNodes=Array.isArray(r)?r.map(e=>new SimpleDOMNode("value",e)):[new SimpleDOMNode("#text",r)]:warn(`Node not found for path: ${t}`)}const r=[];a.documentElement.dump(r);return r.join("")}(r.fetchIfRef(t).getString(),a)}const i=new StringStream(e);i.dict=new Dict(r);i.dict.setIfName("Type","EmbeddedFile");a.put(t,{data:i})}function getIndexes(e){const t=[];for(const{ref:a}of e)a.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(a.num,1);return t}function computeIDs(e,t,a){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const r=function computeMD5(e,t){const a=Math.floor(Date.now()/1e3),r=t.filename||"",i=[a.toString(),r,e.toString(),...t.infoMap.values()],n=Math.sumPrecise(i.map(e=>e.length)),s=new Uint8Array(n);let o=0;for(const e of i)o=writeString(e,o,s);return bytesToString(calculateMD5(s,0,s.length))}(e,t);a.set("ID",[t.fileIds[0]||r,r])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:a,xref:r=null,hasXfa:i=!1,xfaDatasetsRef:n=null,hasXfaDatasetsEntry:s=!1,needAppearances:o,acroFormRef:c=null,acroForm:l=null,xfaData:h=null,useXrefStream:u=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:a,hasXfa:r,hasXfaDatasetsEntry:i,xfaDatasetsRef:n,needAppearances:s,changes:o}){!r||i||n||warn("XFA - Cannot save it");if(!s&&(!r||!n||i))return;const c=t.clone();if(r&&!i){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,n);c.set("XFA",e)}s&&c.set("NeedAppearances",!0);o.put(a,{data:c})}({xref:r,acroForm:l,acroFormRef:c,hasXfa:i,hasXfaDatasetsEntry:s,xfaDatasetsRef:n,needAppearances:o,changes:a});i&&updateXFA({xfaData:h,xfaDatasetsRef:n,changes:a,xref:r});const d=function getTrailerDict(e,t,a){const r=new Dict(null);r.setIfDefined("Prev",e?.startXRef);const i=e.newRef;if(a){t.put(i,{data:""});r.set("Size",i.num+1);r.setIfName("Type","XRef")}else r.set("Size",i.num);r.setIfDefined("Root",e?.rootRef);r.setIfDefined("Info",e?.infoRef);r.setIfDefined("Encrypt",e?.encryptRef);return r}(t,a,u),f=[],g=await async function writeChanges(e,t,a=[]){const r=[];for(const[i,{data:n,objStreamRef:s,index:o}]of e.items())if(s)r.push({ref:i,data:n,objStreamRef:s,index:o});else if(null!==n&&"string"!=typeof n){await writeObject(i,n,a,t);r.push({ref:i,data:a.join("")});a.length=0}else r.push({ref:i,data:n});return r.sort((e,t)=>e.ref.num-t.ref.num)}(a,r,f);let p=e.length;const m=e.at(-1);if(10!==m&&13!==m){f.push("\n");p+=1}for(const{data:e}of g)null!==e&&f.push(e);await(u?async function getXRefStreamTable(e,t,a,r,i){const n=[];let s=0,o=0;for(const{ref:e,data:r,objStreamRef:i,index:c}of a){let a;s=Math.max(s,t);if(i){a=c;n.push([2,i.num,a])}else if(null!==r){a=Math.min(e.gen,65535);n.push([1,t,a]);t+=r.length}else{a=Math.min(e.gen+1,65535);n.push([0,0,a])}o=Math.max(o,a)}r.set("Index",getIndexes(a));const c=[1,getSizeInBytes(s),getSizeInBytes(o)];r.set("W",c);computeIDs(t,e,r);const l=Math.sumPrecise(c),h=new Uint8Array(l*n.length),u=new Stream(h);u.dict=r;let d=0;for(const[e,t,a]of n){d=writeInt(e,c[0],d,h);d=writeInt(t,c[1],d,h);d=writeInt(a,c[2],d,h)}await writeObject(e.newRef,u,i,{});i.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,p,g,d,f):async function getXRefTable(e,t,a,r,i){i.push("xref\n");const n=getIndexes(a);let s=0;for(const{ref:e,data:r}of a){if(e.num===n[s]){i.push(`${n[s]} ${n[s+1]}\n`);s+=2}if(null!==r){i.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=r.length}else i.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,r);i.push("trailer\n");await writeDict(r,i,null);i.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,p,g,d,f));const b=e.length+Math.sumPrecise(f.map(e=>e.length)),y=new Uint8Array(b);y.set(e);let w=e.length;for(const e of f)w=writeString(e,w,y);return y}class PageData{constructor(e,t){this.page=e;this.documentData=t;this.annotations=null;this.pointingNamedDestinations=null;t.pagesMap.put(e.ref,this)}}class DocumentData{constructor(e){this.document=e;this.destinations=null;this.pageLabels=null;this.pagesMap=new RefSetCache;this.oldRefMapping=new RefSetCache;this.dedupNamedDestinations=new Map;this.usedNamedDestinations=new Set;this.postponedRefCopies=new RefSetCache;this.usedStructParents=new Set;this.oldStructParentMapping=new Map;this.structTreeRoot=null;this.parentTree=null;this.idTree=null;this.roleMap=null;this.classMap=null;this.namespaces=null;this.structTreeAF=null;this.structTreePronunciationLexicon=[]}}class XRefWrapper{constructor(e){this.entries=e}fetch(e){return e instanceof Ref?this.entries[e.num]:e}}class PDFEditor{constructor({useObjectStreams:e=!0,title:t="",author:a=""}={}){this.hasSingleFile=!1;this.currentDocument=null;this.oldPages=[];this.newPages=[];this.xref=[null];this.xrefWrapper=new XRefWrapper(this.xref);this.newRefCount=1;[this.rootRef,this.rootDict]=this.newDict;[this.infoRef,this.infoDict]=this.newDict;[this.pagesRef,this.pagesDict]=this.newDict;this.namesDict=null;this.useObjectStreams=e;this.objStreamRefs=e?new Set:null;this.version="1.7";this.title=t;this.author=a;this.pageLabels=null;this.namedDestinations=new Map;this.parentTree=new Map;this.structTreeKids=[];this.idTree=new Map;this.classMap=new Dict;this.roleMap=new Dict;this.namespaces=new Map;this.structTreeAF=[];this.structTreePronunciationLexicon=[]}get newRef(){return Ref.get(this.newRefCount++,0)}get newDict(){const e=this.newRef;return[e,this.xref[e.num]=new Dict]}async#St(e,t){const a=this.newRef;this.xref[a.num]=await this.#At(e,!0,t);return a}cloneDict(e){const t=e.clone();t.xref=this.xrefWrapper;return t}async#At(e,t,a){if(e instanceof Ref){const{currentDocument:{oldRefMapping:t}}=this;let r=t.get(e);if(r)return r;const i=e;if("number"==typeof(e=await a.fetchAsync(i)))return e;r=this.newRef;t.put(i,r);this.xref[r.num]=await this.#At(e,!0,a);return r}const r=[],{currentDocument:{postponedRefCopies:i}}=this;if(Array.isArray(e)){t&&(e=e.slice());for(let t=0,n=e.length;te[t]=a):r.push(this.#At(e[t],!0,a).then(a=>e[t]=a))}await Promise.all(r);return e}let n;if(e instanceof BaseStream){({dict:n}=e=e.getOriginalStream().clone());n.xref=this.xrefWrapper}else if(e instanceof Dict){t&&((e=e.clone()).xref=this.xrefWrapper);n=e}if(n){for(const[e,t]of n.getRawEntries()){const s=i.get(t);s?s.push(t=>n.set(e,t)):r.push(this.#At(t,!0,a).then(t=>n.set(e,t)))}await Promise.all(r)}return e}async#kt(e,t,a,r,i,n,s,o=new RefSet){const{currentDocument:{pagesMap:c,oldRefMapping:l}}=this,h=t.getRaw("Pg");if(h instanceof Ref&&!c.has(h))return null;let u;const d=u=t.getRaw("K");if(d instanceof Ref){if(o.has(d))return null;u=await a.fetchAsync(d);Array.isArray(u)||(u=[d])}u=Array.isArray(u)?u:[u];const f=[],g=[];for(let t of u){const h=t instanceof Ref?t:null;if(h){if(o.has(h))continue;o.put(h);t=await a.fetchAsync(h)}if("number"==typeof t){f.push(t);continue}if(!(t instanceof Dict))continue;const u=t.getRaw("Pg");if(u instanceof Ref&&!c.has(u))continue;const d=t.get("Type");if(!d||isName(d,"StructElem")){let e=!1;if(h&&r.has(h)){if(!isName(t.get("S"),"Link"))continue;e=!0}const c=await this.#kt(h,t,a,r,i,n,s,o);if(c){g.push(f.length);f.push(c);h&&l.put(h,c);e&&this.xref[c.num].setIfName("S","Span")}continue}if(isName(d,"OBJR")){if(!h)continue;const t=l.get(h);if(!t)continue;const a=this.xref[t.num].getRaw("Obj");if(a instanceof Ref){const t=this.xref[a.num];if(t instanceof Dict&&!t.has("StructParent")&&e){const a=this.parentTree.size;this.parentTree.set(a,[l,e]);t.set("StructParent",a)}}f.push(t);continue}if(isName(d,"MCR")){const e=await this.#At(h||t,!0,a);f.push(e);continue}if(h){const e=await this.#At(h,!0,a);f.push(e)}}if(0!==u.length&&0===f.length)return null;const p=this.newRef,m=this.xref[p.num]=this.cloneDict(t);m.delete("ID");m.delete("C");m.delete("K");m.delete("P");m.delete("S");await this.#At(m,!1,a);const b=t.get("C");if(b instanceof Name){const e=n.get(b.name);e?m.set("C",Name.get(e)):m.set("C",b)}else if(Array.isArray(b)){const e=[];for(const t of b)if(t instanceof Name){const a=n.get(t.name);a?e.push(Name.get(a)):e.push(t)}m.set("C",e)}const y=t.get("S");if(y instanceof Name){const e=s.get(y.name);e?m.set("S",Name.get(e)):m.set("S",y)}const w=t.get("ID");if("string"==typeof w){const e=stringToPDFString(w,!1),t=i.get(e);t?m.set("ID",stringToAsciiOrUTF16BE(t)):m.set("ID",w)}let x=m.get("A");if(x){Array.isArray(x)||(x=[x]);for(let e of x){e=this.xrefWrapper.fetch(e);if(isName(e.get("O"),"Table")&&e.has("Headers")){const t=this.xrefWrapper.fetch(e.getRaw("Headers"));if(Array.isArray(t))for(let e=0,a=t.length;e1&&m.set("K",f);return p}async extractPages(e){const t=[];let a=0;this.hasSingleFile=1===e.length;const r=[];for(const{document:i,includePages:n,excludePages:s}of e){if(!i)continue;const e=new DocumentData(i);r.push(e);t.push(this.#Ct(e));let o,c,l,h;for(const e of n||[])Array.isArray(e)?(c||=[]).push(e):(o||=new Set).add(e);for(const e of s||[])Array.isArray(e)?(h||=[]).push(e):(l||=new Set).add(e);for(let r=0,n=i.numPages;r=t&&r<=a){e=!0;break}if(e)continue}let n=!1;o&&(n=o.has(r));if(!n&&c)for(const[e,t]of c)if(r>=e&&r<=t){n=!0;break}n||o||c||(n=!0);if(!n)continue;const s=a++;t.push(i.getPage(r).then(t=>{this.oldPages[s]=new PageData(t,e)}))}}await Promise.all(t);t.length=0;this.#vt(r);this.#Ft();for(const e of this.oldPages)t.push(this.#It(e));await Promise.all(t);this.#Tt();this.#Ot(r);for(let e=0,t=this.oldPages.length;ee.destinations=t),t.ensureCatalog("rawPageLabels").then(t=>e.pageLabels=t),t.ensureCatalog("structTreeRoot").then(t=>e.structTreeRoot=t)]);const r=e.structTreeRoot;if(r){const t=r.dict,i=t.get("ParentTree");if(i){const t=new NumberTree(i,a);e.parentTree=t.getAll(!0)}const n=t.get("IDTree");if(n){const t=new NameTree(n,a);e.idTree=t.getAll(!0)}e.roleMap=t.get("RoleMap")||null;e.classMap=t.get("ClassMap")||null;let s=t.get("Namespaces")||null;s&&!Array.isArray(s)&&(s=[s]);e.namespaces=s;e.structTreeAF=t.get("AF")||null;e.structTreePronunciationLexicon=t.get("PronunciationLexicon")||null}}async#It(e){const{page:{xref:t,annotations:a},documentData:{pagesMap:r,destinations:i,usedNamedDestinations:n}}=e;if(!a)return;const s=[];let o=[],c=0;for(const e of a){const a=c++;s.push(t.fetchIfRefAsync(e).then(async t=>{if(!isName(t.get("Subtype"),"Link")){o[a]=e;return}const s=t.get("A"),c=s instanceof Dict?s.get("D"):t.get("Dest");if(c&&(!Array.isArray(c)||c[0]instanceof Ref&&!r.has(c[0]))){if("string"==typeof c){const t=stringToPDFString(c,!0);if(i.has(t)){o[a]=e;n.add(t)}}}else o[a]=e}))}await Promise.all(s);o=o.filter(e=>!!e);e.annotations=o.length>0?o:null}#Ot(e){for(const{postponedRefCopies:t,pagesMap:a}of e)for(const e of a.keys())t.put(e,[])}#Mt(e){for(const{postponedRefCopies:t,oldRefMapping:a}of e){for(const[e,r]of t.items()){const t=a.get(e);for(const e of r)e(t)}t.clear()}}#Bt(e,t,a=new RefSet){if(e instanceof Ref){if(!a.has(e)){a.put(e);this.#Bt(this.xref[e.num],t,a)}return}if(Array.isArray(e)){for(const r of e)this.#Bt(r,t,a);return}let r;e instanceof BaseStream?({dict:r}=e):e instanceof Dict&&(r=e);if(r){t(r);for(const e of r.getRawValues())this.#Bt(e,t,a)}}async#Rt(e){let t=0;const{parentTree:a}=this;for(let e=0,r=this.newPages.length;e{const c=e.get("StructParent")??e.get("StructParents");if("number"!=typeof c)return;s.add(c);let l=r.get(c);const h=l instanceof Ref?l:null;if(h){const e=o.fetch(h);Array.isArray(e)&&(l=e)}Array.isArray(l)&&l.every(e=>null===e)&&(l=null);if(!l){e.has("StructParent")?e.delete("StructParent"):e.delete("StructParents");return}let u=n.get(c);if(void 0===u){u=t++;n.set(c,u);a.set(u,[i,l])}e.has("StructParent")?e.set("StructParent",u):e.set("StructParents",u)})}const{structTreeKids:r,idTree:i,classMap:n,roleMap:s,namespaces:o,structTreeAF:c,structTreePronunciationLexicon:l}=this;for(const t of e){const{document:{xref:e},oldRefMapping:a,parentTree:h,usedStructParents:u,structTreeRoot:d,idTree:f,classMap:g,roleMap:p,namespaces:m,structTreeAF:b,structTreePronunciationLexicon:y}=t;if(!d)continue;this.currentDocument=t;const w=new RefSet;for(const[e,t]of h||[])!u.has(e)&&t instanceof Ref&&w.put(t);const x=new Map;for(const[e,t]of f||[]){let a=e;if(i.has(e))for(let t=1;;t++){const r=`${e}_${t}`;if(!i.has(r)){x.set(e,r);a=r;break}}i.set(a,t)}const S=new Map;if(g?.size>0)for(let[t,a]of g){a=await this.#At(a,!0,e);if(n.has(t))for(let e=1;;e++){const a=`${t}_${e}`;if(!n.has(a)){S.set(t,a);t=a;break}}n.set(t,a)}const k=new Map;if(p?.size>0)for(const[e,t]of p){const a=s.get(e);if(a){if(a!==t)for(let a=1;;a++){const r=`${e}_${a}`;if(!s.has(r)){k.set(e,r);s.set(r,t);break}}}else s.set(e,t)}if(m?.length>0)for(const t of m){const a=await e.fetchIfRefAsync(t);let r=a.get("NS");if(!r||o.has(r))continue;r=stringToPDFString(r,!1);const i=await this.#At(a,!0,e);o.set(r,i)}if(b)for(const t of b)c.push(await this.#At(t,!0,e));if(y)for(const t of y)l.push(await this.#At(t,!0,e));let C=d.dict.get("K");if(C){C=Array.isArray(C)?C:[C];for(let t of C){const a=t instanceof Ref?t:null;if(a&&w.has(a))continue;t=await e.fetchIfRefAsync(t);const i=await this.#kt(a,t,e,w,x,S,k);i&&r.push(i)}for(const[e,t]of f||[]){const r=a.get(t),n=x.get(e)||e;r?i.set(n,r):i.delete(n)}}}for(const[e,[t,r]]of a){if(!r){a.delete(e);continue}if(!Array.isArray(r)){const i=t.get(r);void 0===i?a.delete(e):a.set(e,i);continue}const i=r.map(e=>e instanceof Ref&&t.get(e)||null);0===i.length||i.every(e=>null===e)?a.delete(e):a.set(e,i)}this.currentDocument=null}#vt(e){for(const t of e){if(!t.destinations)continue;const{destinations:e,pagesMap:a}=t,r=t.destinations=new Map;for(const[t,i]of Object.entries(e)){const e=i[0],n=a.get(e);if(n){(n.pointingNamedDestinations||=new Set).add(t);r.set(t,i)}}}}#Tt(){const{namedDestinations:e}=this;for(let t=0,a=this.oldPages.length;t{"string"==typeof r&&e.set(a,t.get(stringToPDFString(r,!0))||r)};for(const t of e){const e=this.xref[t.num];if(!isName(e.get("Subtype"),"Link"))continue;const a=e.get("A");if(a instanceof Dict&&a.has("D")){const e=a.get("D");fixDestination(a,"D",e);continue}const r=e.get("Dest");fixDestination(e,"Dest",r)}}async#Ft(){if(!this.hasSingleFile)return;const{documentData:{document:e,pageLabels:t}}=this.oldPages[0];if(!t)return;const a=e.numPages,r=[],i=new Set(this.oldPages.map(({page:{pageIndex:e}})=>e));let n=null,s=-1;for(let e=0;ee!==l[t])&&f.set(e,a)}const p=t.userUnit;1!==p&&f.set("UserUnit",p);f.setIfDict("Resources",await this.#At(h,!0,o));if(r){const e=await this.#At(r,!0,o);this.#Nt(e,n);f.setIfArray("Annots",e)}if(this.useObjectStreams){const e=this.newRefCount,t=[];for(let a=g;a0;){const{dict:e,kids:t,parentRef:a}=i.pop();if(t.length<=16){e.set("Kids",t);for(const e of t)this.xref[e.num].set("Parent",a);continue}const r=Math.max(16,Math.ceil(t.length/16)),n=[];for(let e=0;ee.localeCompare(t):([e],[t])=>e-t),[r,i]=this.newDict,n=[{dict:i,entries:a}],s=t?"Names":"Nums";for(;n.length>0;){const{dict:e,entries:t}=n.pop();if(t.length<=64){e.set("Limits",[t[0][0],t.at(-1)[0]]);e.set(s,t.flat());continue}const a=[],r=Math.max(64,Math.ceil(t.length/64));for(let e=0;e0){const e=this.#Et(Array.from(this.parentTree.entries()),!1);this.xref[e.num].setIfName("Type","ParentTree");r.set("ParentTree",e);r.set("ParentTreeNextKey",this.parentTree.size)}if(this.idTree.size>0){const e=this.#Et(Array.from(this.idTree.entries()),!0);this.xref[e.num].setIfName("Type","IDTree");r.set("IDTree",e)}if(this.classMap.size>0){const e=this.newRef;this.xref[e.num]=this.classMap;r.set("ClassMap",e)}if(this.roleMap.size>0){const e=this.newRef;this.xref[e.num]=this.roleMap;r.set("RoleMap",e)}if(this.namespaces.size>0){const e=this.newRef;this.xref[e.num]=Array.from(this.namespaces.values());r.set("Namespaces",e)}if(this.structTreeAF.length>0){const e=this.newRef;this.xref[e.num]=this.structTreeAF;r.set("AF",e)}if(this.structTreePronunciationLexicon.length>0){const e=this.newRef;this.xref[e.num]=this.structTreePronunciationLexicon;r.set("PronunciationLexicon",e)}t.set("StructTreeRoot",a)}async#jt(){const{rootDict:e}=this;e.setIfName("Type","Catalog");e.setIfName("Version",this.version);this.#Pt();this.#Lt();this.#_t();this.#Ut()}#Xt(){const e=new Map;if(this.hasSingleFile){const{xref:{trailer:t}}=this.oldPages[0].documentData.document,a=t.get("Info");for(const[t,r]of a||[])"string"==typeof r&&e.set(t,stringToPDFString(r))}e.delete("ModDate");e.set("CreationDate",getModificationDate());e.set("Creator","PDF.js");e.set("Producer","Firefox");this.author&&e.set("Author",this.author);this.title&&e.set("Title",this.title);for(const[t,a]of e)this.infoDict.set(t,stringToAsciiOrUTF16BE(a));return e}async#qt(){if(!this.hasSingleFile)return[null,null,null];const{documentData:e}=this.oldPages[0],{document:{xref:{trailer:t,encrypt:a}}}=e;if(!t.has("Encrypt"))return[null,null,null];const r=t.get("Encrypt");if(!(r instanceof Dict))return[null,null,null];this.currentDocument=e;const i=[await this.#St(r,t.xref),a,t.get("ID")];this.currentDocument=null;return i}async#Ht(){const e=new RefSetCache;e.put(Ref.get(0,65535),{data:null});for(let t=1,a=this.xref.length;te.charCodeAt(0)),250,222,250,206];return incrementalUpdate({originalData:new Uint8Array(s),changes:i,xrefInfo:{startXRef:null,rootRef:this.rootRef,infoRef:this.infoRef,encryptRef:t,newRef:n,fileIds:r||[null,null],infoMap:e},useXrefStream:this.useObjectStreams,xref:{encrypt:a,encryptRef:t}})}}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const a=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(a);return a}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then(e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength})}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,a){this._msgHandler=a;this.onProgress=null;const r=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=r.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!e&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let a=!1;e.on("test",t=>{if(!a){a=!0;e.send("test",t instanceof Uint8Array)}});e.on("configure",e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(Qt=e)}(e.verbosity)});e.on("GetDocRequest",e=>this.createDocumentHandler(e,t))}static createDocumentHandler(e,t){let a,r=!1,i=null;const n=new Set,s=getVerbosityLevel(),{docId:o,apiVersion:c}=e,l="5.4.530";if(c!==l)throw new Error(`The API version "${c}" does not match the Worker version "${l}".`);const buildMsg=(e,t)=>`The \`${e}.prototype\` contains unexpected enumerable property "${t}", thus breaking e.g. \`for...in\` iteration of ${e}s.`;for(const e in{})throw new Error(buildMsg("Object",e));for(const e in[])throw new Error(buildMsg("Array",e));const h=o+"_worker";let u=new MessageHandler(h,o,t);function ensureNotTerminated(){if(r)throw new Error("Worker was terminated")}function startWorkerTask(e){n.add(e)}function finishWorkerTask(e){e.finish();n.delete(e)}async function loadDocument(e){await a.ensureDoc("checkHeader");await a.ensureDoc("parseStartXRef");await a.ensureDoc("parse",[e]);await a.ensureDoc("checkFirstPage",[e]);await a.ensureDoc("checkLastPage",[e]);const t=await a.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaResources");startWorkerTask(e);await a.ensureDoc("loadXfaResources",[u,e]);finishWorkerTask(e)}const[r,i]=await Promise.all([a.ensureDoc("numPages"),a.ensureDoc("fingerprints")]);return{numPages:r,fingerprints:i,htmlForXfa:t?await a.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();u.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);u.sendWithPromise("PasswordRequest",e).then(function({password:e}){finishWorkerTask(t);a.updatePassword(e);pdfManagerReady()}).catch(function(){finishWorkerTask(t);u.send("DocException",e)})}else u.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,function(e){ensureNotTerminated();e instanceof XRefParseException?a.requestLoadedStream().then(function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)}):onFailure(e)})}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:a,rangeChunkSize:r,length:n,docBaseUrl:s,enableXfa:c,evaluatorOptions:l}){const h={source:null,disableAutoFetch:a,docBaseUrl:s,docId:o,enableXfa:c,evaluatorOptions:l,handler:u,length:n,password:t,rangeChunkSize:r};if(e){h.source=e;return new LocalPdfManager(h)}const d=new PDFWorkerStream(u),f=d.getFullReader(),g=Promise.withResolvers();let p,m=[],b=0;f.headersReady.then(function(){if(f.isRangeSupported){h.source=d;h.length=f.contentLength;h.disableAutoFetch||=f.isStreamingSupported;p=new NetworkPdfManager(h);for(const e of m)p.sendProgressiveData(e);m=[];g.resolve(p);i=null}}).catch(function(e){g.reject(e);i=null});new Promise(function(e,t){const readChunk=function({value:e,done:a}){try{ensureNotTerminated();if(a){if(!p){const e=arrayBuffersToBytes(m);m=[];n&&e.length!==n&&warn("reported HTTP length is different from actual");h.source=e;p=new LocalPdfManager(h);g.resolve(p)}i=null;return}b+=e.byteLength;f.isStreamingSupported||u.send("DocProgress",{loaded:b,total:Math.max(b,f.contentLength||0)});p?p.sendProgressiveData(e):m.push(e);f.read().then(readChunk,t)}catch(e){t(e)}};f.read().then(readChunk,t)}).catch(function(e){g.reject(e);i=null});i=e=>{d.cancelAllRequests(e)};return g.promise})(e).then(function(e){if(r){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}a=e;a.requestLoadedStream(!0).then(e=>{u.send("DataLoaded",{length:e.bytes.byteLength})})}).then(pdfManagerReady,onFailure)}u.on("GetPage",function(e){return a.getPage(e.pageIndex).then(function(e){return Promise.all([a.ensure(e,"rotate"),a.ensure(e,"ref"),a.ensure(e,"userUnit"),a.ensure(e,"view")]).then(function([e,t,a,r]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:a,view:r}})})});u.on("GetPageIndex",function(e){const t=Ref.get(e.num,e.gen);return a.ensureCatalog("getPageIndex",[t])});u.on("GetDestinations",function(e){return a.ensureCatalog("destinations")});u.on("GetDestination",function(e){return a.ensureCatalog("getDestination",[e.id])});u.on("GetPageLabels",function(e){return a.ensureCatalog("pageLabels")});u.on("GetPageLayout",function(e){return a.ensureCatalog("pageLayout")});u.on("GetPageMode",function(e){return a.ensureCatalog("pageMode")});u.on("GetViewerPreferences",function(e){return a.ensureCatalog("viewerPreferences")});u.on("GetOpenAction",function(e){return a.ensureCatalog("openAction")});u.on("GetAttachments",function(e){return a.ensureCatalog("attachments")});u.on("GetDocJSActions",function(e){return a.ensureCatalog("jsActions")});u.on("GetPageJSActions",function({pageIndex:e}){return a.getPage(e).then(e=>a.ensure(e,"jsActions"))});u.on("GetAnnotationsByType",async function({types:e,pageIndexesToSkip:t}){const[r,i]=await Promise.all([a.ensureDoc("numPages"),a.ensureDoc("annotationGlobals")]);if(!i)return null;const n=[],s=[];let o=null;try{for(let c=0,l=r;ct&&t.collectAnnotationsByType(u,o,e,s,i)||[]))}await Promise.all(n);return(await Promise.all(s)).filter(e=>!!e)}finally{o&&finishWorkerTask(o)}});u.on("GetOutline",function(e){return a.ensureCatalog("documentOutline")});u.on("GetOptionalContentConfig",function(e){return a.ensureCatalog("optionalContentConfig")});u.on("GetPermissions",function(e){return a.ensureCatalog("permissions")});u.on("GetMetadata",function(e){return Promise.all([a.ensureDoc("documentInfo"),a.ensureCatalog("metadata"),a.ensureCatalog("hasStructTree")])});u.on("GetMarkInfo",function(e){return a.ensureCatalog("markInfo")});u.on("GetData",function(e){return a.requestLoadedStream().then(e=>e.bytes)});u.on("GetAnnotations",function({pageIndex:e,intent:t}){return a.getPage(e).then(function(a){const r=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(r);return a.getAnnotationsData(u,r,t).then(e=>{finishWorkerTask(r);return e},e=>{finishWorkerTask(r);throw e})})});u.on("GetFieldObjects",function(e){return a.ensureDoc("fieldObjects").then(e=>e?.allFields||null)});u.on("HasJSActions",function(e){return a.ensureDoc("hasJSActions")});u.on("GetCalculationOrderIds",function(e){return a.ensureDoc("calculationOrderIds")});u.on("ExtractPages",async function({pageInfos:e}){if(!e){warn("extractPages: nothing to extract.");return null}Array.isArray(e)||(e=[e]);let t=0;for(const r of e)if(null===r.document)r.document=a.pdfDocument;else if(ArrayBuffer.isView(r.document)){const e=new LocalPdfManager({source:r.document,docId:`${o}_extractPages_${t++}`,handler:u,password:r.password??null,evaluatorOptions:Object.assign({},a.evaluatorOptions)});let i=!1,n=!0;for(;;)try{await e.requestLoadedStream();await e.ensureDoc("checkHeader");await e.ensureDoc("parseStartXRef");await e.ensureDoc("parse",[i]);break}catch(t){if(t instanceof XRefParseException){if(!1===i){i=!0;continue}n=!1;warn("extractPages: XRefParseException.")}else if(t instanceof PasswordException){const a=new WorkerTask(`PasswordException: response ${t.code}`);startWorkerTask(a);try{const{password:a}=await u.sendWithPromise("PasswordRequest",t);e.updatePassword(a)}catch{n=!1;warn("extractPages: invalid password.")}finally{finishWorkerTask(a)}}else{n=!1;warn("extractPages: invalid document.")}if(!n)break}n||(r.document=null);if(await e.ensureDoc("isPureXfa")){r.document=null;warn("extractPages does not support pure XFA documents.")}else r.document=e.pdfDocument}else warn("extractPages: invalid document.");try{const t=new PDFEditor;return await t.extractPages(e)}catch(e){console.error(e);return null}});u.on("SaveDocument",async function({isPureXfa:e,numPages:t,annotationStorage:r,filename:i}){const n=[a.requestLoadedStream(),a.ensureCatalog("acroForm"),a.ensureCatalog("acroFormRef"),a.ensureDoc("startXRef"),a.ensureDoc("xref"),a.ensureCatalog("structTreeRoot")],s=new RefSetCache,o=[],c=e?null:getNewAnnotationsMap(r),[l,h,d,f,g,p]=await Promise.all(n),m=g.trailer.getRaw("Root")||null;let b;if(c){p?await p.canUpdateStructTree({pdfManager:a,newAnnotationsByPage:c})&&(b=p):await StructTreeRoot.canCreateStructureTree({catalogRef:m,pdfManager:a,newAnnotationsByPage:c})&&(b=null);const e=AnnotationFactory.generateImages(r.values(),g,a.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===b?o:[];for(const[r,i]of c)t.push(a.getPage(r).then(t=>{const a=new WorkerTask(`Save (editor): page ${r}`);startWorkerTask(a);return t.saveNewAnnotations(u,a,i,e,s).finally(function(){finishWorkerTask(a)})}));null===b?o.push(Promise.all(t).then(async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:c,xref:g,catalogRef:m,pdfManager:a,changes:s})})):b&&o.push(Promise.all(t).then(async()=>{await b.updateStructureTree({newAnnotationsByPage:c,pdfManager:a,changes:s})}))}if(e)o.push(a.ensureDoc("serializeXfaData",[r]));else for(let e=0;ee.needAppearances),S=h instanceof Dict&&h.get("XFA")||null;let k=null,C=!1;if(Array.isArray(S)){for(let e=0,t=S.length;e{g.resetNewTemporaryRef()})});u.on("GetOperatorList",function(e,t){const r=e.pageIndex;a.getPage(r).then(function(a){const i=new WorkerTask(`GetOperatorList: page ${r}`);startWorkerTask(i);const n=s>=ce?Date.now():0;a.getOperatorList({handler:u,sink:t,task:i,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then(function(e){finishWorkerTask(i);n&&info(`page=${r+1} - getOperatorList: time=${Date.now()-n}ms, len=${e.length}`);t.close()},function(e){finishWorkerTask(i);i.terminated||t.error(e)})})});u.on("GetTextContent",function(e,t){const{pageIndex:r,includeMarkedContent:i,disableNormalization:n}=e;a.getPage(r).then(function(e){const a=new WorkerTask("GetTextContent: page "+r);startWorkerTask(a);const o=s>=ce?Date.now():0;e.extractTextContent({handler:u,task:a,sink:t,includeMarkedContent:i,disableNormalization:n}).then(function(){finishWorkerTask(a);o&&info(`page=${r+1} - getTextContent: time=`+(Date.now()-o)+"ms");t.close()},function(e){finishWorkerTask(a);a.terminated||t.error(e)})})});u.on("GetStructTree",function(e){return a.getPage(e.pageIndex).then(e=>a.ensure(e,"getStructTree"))});u.on("FontFallback",function(e){return a.fontFallback(e.id,u)});u.on("Cleanup",function(e){return a.cleanup(!0)});u.on("Terminate",function(e){r=!0;const t=[];if(a){a.terminate(new AbortException("Worker was terminated."));const e=a.cleanup();t.push(e);a=null}else clearGlobalCaches();i?.(new AbortException("Worker was terminated."));for(const e of n){t.push(e.finished);e.terminate()}return Promise.all(t).then(function(){u.destroy();u=null})});u.on("Ready",function(t){setupDoc(e);e=null});return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}globalThis.pdfjsWorker={WorkerMessageHandler};export{WorkerMessageHandler}; \ No newline at end of file diff --git a/frontend/dist/sw.js b/frontend/dist/sw.js deleted file mode 100644 index 6113676..0000000 --- a/frontend/dist/sw.js +++ /dev/null @@ -1,61 +0,0 @@ -const CACHE_NAME = 'kitchen-app-v3' -const SHELL_URLS = [ - '/manifest.json', - '/kds-manifest.json', -] - -self.addEventListener('install', (event) => { - event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_URLS)) - ) - self.skipWaiting() -}) - -self.addEventListener('activate', (event) => { - event.waitUntil( - caches.keys().then((keys) => - Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))) - ) - ) - self.clients.claim() -}) - -self.addEventListener('fetch', (event) => { - const url = new URL(event.request.url) - - // Never cache API/auth calls - if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/auth/')) { - return - } - - // Navigation requests (HTML pages): always network-first - if (event.request.mode === 'navigate') { - event.respondWith( - fetch(event.request) - .then((response) => { - const clone = response.clone() - caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone)) - return response - }) - .catch(() => caches.match(event.request).then((c) => c || caches.match('/'))) - ) - return - } - - // Static assets (JS/CSS with content hashes): cache-first - event.respondWith( - caches.match(event.request).then((cached) => { - return cached || fetch(event.request).then((response) => { - if (event.request.method === 'GET' && response.status === 200) { - const clone = response.clone() - caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone)) - } - return response - }) - }).catch(() => { - if (event.request.mode === 'navigate') { - return caches.match('/') - } - }) - ) -})